Search Results

Search found 7 results on 1 pages for 'textutils'.

Page 1/1 | 1 

  • Intelligent "Subtraction" of one text logfile from another

    - by Vi
    Example: Application generates large text log file A with many different messages. It generates similarly large log file B when does not function correctly. I want to see what messages in file B are essentially new, i.e. to filter-out everything from A. Trivial prototype is: Sort | uniq both files Join files sort | uniq -c grep -v "^2" This produces symmetric difference and inconvenient. How to do it better? (including non-symmetric difference and preserving of messages order in B) Program should first analyse A and learn which messages are common, then analyse B showing with messages needs attention. Ideally it should automatically disregard things like timestamps, line numbers or other volatile things. Example. A: 0:00:00.234 Received buffer 0x324234 0:00:00.237 Processeed buffer 0x324234 0:00:00.238 Send buffer 0x324255 0:00:03.334 Received buffer 0x324255 0:00:03.337 Processeed buffer 0x324255 0:00:03.339 Send buffer 0x324255 0:00:05.171 Received buffer 0x32421A 0:00:05.173 Processeed buffer 0x32421A 0:00:05.178 Send buffer 0x32421A B: 0:00:00.134 Received buffer 0x324111 0:00:00.137 Processeed buffer 0x324111 0:00:00.138 Send buffer 0x324111 0:00:03.334 Received buffer 0x324222 0:00:03.337 Processeed buffer 0x324222 0:00:03.338 Error processing buffer 0x324222 0:00:03.339 Send buffer 0x3242222 0:00:05.271 Received buffer 0x3242FA 0:00:05.273 Processeed buffer 0x3242FA 0:00:05.278 Send buffer 0x3242FA 0:00:07.280 Send buffer 0x3242FA failed Result: 0:00:03.338 Error processing buffer 0x324222 0:00:07.280 Send buffer 0x3242FA failed One of ways of solving it can be something like that: Split each line to logical units: 0:00:00.134 Received buffer 0x324111,0:00:00.134,Received,buffer,0x324111,324111,Received buffer, \d:\d\d:\d\d\.\d\d\d, \d+:\d+:\d+.\d+, 0x[0-9A-F]{6}, ... It should find individual words, simple patterns in numbers, common layouts (e.g. "some date than text than number than text than end_of_line"), also handle combinations of above. As it is not easy task, user assistance (adding regexes with explicit "disregard that","make the main factor","don't split to parts","consider as date/number","take care of order/quantity of such messages" rules) should be supported (but not required) for it. Find recurring units and "categorize" lines, filter out too volatile things like timestamps, addresses or line numbers. Analyse the second file, find things that has new logical units (one-time or recurring), or anything that will "amaze" the system which has got used to the first file. Example of doing some bit of this manually: $ cat A | head -n 1 0:00:00.234 Received buffer 0x324234 $ cat A | egrep -v "Received buffer" | head -n 1 0:00:00.237 Processeed buffer 0x324234 $ cat A | egrep -v "Received buffer|Processeed buffer" | head -n 1 0:00:00.238 Send buffer 0x324255 $ cat A | egrep -v "Received buffer|Processeed buffer|Send buffer" | head -n 1 $ cat B | egrep -v "Received buffer|Processeed buffer|Send buffer" 0:00:03.338 Error processing buffer 0x324222 0:00:07.280 Send buffer 0x3242FA failed This is a boring thing (there are a lot of message types); also I can accidentally include some too broad pattern. Also it can't handle complicated things like interrelation between messages. I know that it is AI-related. May be there are already developed tools?

    Read the article

  • Decode HTML entities in android

    - by johboh
    Hi there. I need to decode HTML entities, e.g. from ö to ö, and & to &. URLEncoder.decode(str) does not do the job (convert from % notations). TextUtils has a HTMLencode, but not a HTMLdecode. Are there any function for decoding HTML entities? Regards, Johan

    Read the article

  • NullPointerException when linking to Service that uses ContentProvider

    - by Danny Chia
    H.i everyone, this is my first post here! Anyways, I'm trying to write a "todo list" application. It stores the data in a ContentProvider, which is accessed via a Service. However, my app crashes at launch. My code is below: Manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.examples.todolist" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="True"> <activity android:name=".ToDoList" android:label="@string/app_name" android:theme="@style/ToDoTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="TodoService"/> <provider android:name="TodoProvider" android:authorities="com.examples.provider.todolist" /> </application> <uses-sdk android:minSdkVersion="7" /> </manifest> ToDoList.java: package com.examples.todolist; import com.examples.todolist.TodoService.LocalBinder; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.view.ContextMenu; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class ToDoList extends Activity { static final private int ADD_NEW_TODO = Menu.FIRST; static final private int REMOVE_TODO = Menu.FIRST + 1; private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY"; private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY"; private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY"; private boolean addingNew = false; private ArrayList<ToDoItem> todoItems; private ListView myListView; private EditText myEditText; private ToDoItemAdapter aa; int entries = 0; int notifs = 0; //ToDoDBAdapter toDoDBAdapter; Cursor toDoListCursor; TodoService mService; boolean mBound = false; /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myListView = (ListView)findViewById(R.id.myListView); myEditText = (EditText)findViewById(R.id.myEditText); todoItems = new ArrayList<ToDoItem>(); int resID = R.layout.todolist_item; aa = new ToDoItemAdapter(this, resID, todoItems); myListView.setAdapter(aa); myEditText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { ToDoItem newItem = new ToDoItem(myEditText.getText().toString(), 0); mService.insertTask(newItem); updateArray(); myEditText.setText(""); entries++; Toast.makeText(ToDoList.this, "Entry added", Toast.LENGTH_SHORT).show(); aa.notifyDataSetChanged(); cancelAdd(); return true; } return false; } }); registerForContextMenu(myListView); restoreUIState(); populateTodoList(); } private void populateTodoList() { // Get all the todo list items from the database. toDoListCursor = mService. getAllToDoItemsCursor(); startManagingCursor(toDoListCursor); // Update the array. updateArray(); Toast.makeText(this, "Todo list retrieved", Toast.LENGTH_SHORT).show(); } private void updateArray() { toDoListCursor.requery(); todoItems.clear(); if (toDoListCursor.moveToFirst()) do { String task = toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_TASK)); long created = toDoListCursor.getLong(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_CREATION_DATE)); int taskid = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_ID)); ToDoItem newItem = new ToDoItem(task, new Date(created), taskid); todoItems.add(0, newItem); } while(toDoListCursor.moveToNext()); aa.notifyDataSetChanged(); } private void restoreUIState() { // Get the activity preferences object. SharedPreferences settings = getPreferences(0); // Read the UI state values, specifying default values. String text = settings.getString(TEXT_ENTRY_KEY, ""); Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false); // Restore the UI to the previous state. if (adding) { addNewItem(); myEditText.setText(text); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition()); super.onSaveInstanceState(outState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { int pos = -1; if (savedInstanceState != null) if (savedInstanceState.containsKey(SELECTED_INDEX_KEY)) pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1); myListView.setSelection(pos); } @Override protected void onPause() { super.onPause(); // Get the activity preferences object. SharedPreferences uiState = getPreferences(0); // Get the preferences editor. SharedPreferences.Editor editor = uiState.edit(); // Add the UI state preference values. editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString()); editor.putBoolean(ADDING_ITEM_KEY, addingNew); // Commit the preferences. editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Create and add new menu items. MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE, R.string.add_new); MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); // Assign icons itemAdd.setIcon(R.drawable.add_new_item); itemRem.setIcon(R.drawable.remove_item); // Allocate shortcuts to each of them. itemAdd.setShortcut('0', 'a'); itemRem.setShortcut('1', 'r'); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); int idx = myListView.getSelectedItemPosition(); String removeTitle = getString(addingNew ? R.string.cancel : R.string.remove); MenuItem removeItem = menu.findItem(REMOVE_TODO); removeItem.setTitle(removeTitle); removeItem.setVisible(addingNew || idx > -1); return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Selected To Do Item"); menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); int index = myListView.getSelectedItemPosition(); switch (item.getItemId()) { case (REMOVE_TODO): { if (addingNew) { cancelAdd(); } else { removeItem(index); } return true; } case (ADD_NEW_TODO): { addNewItem(); return true; } } return false; } @Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); switch (item.getItemId()) { case (REMOVE_TODO): { AdapterView.AdapterContextMenuInfo menuInfo; menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int index = menuInfo.position; removeItem(index); return true; } } return false; } @Override public void onDestroy() { super.onDestroy(); } private void cancelAdd() { addingNew = false; myEditText.setVisibility(View.GONE); } private void addNewItem() { addingNew = true; myEditText.setVisibility(View.VISIBLE); myEditText.requestFocus(); } private void removeItem(int _index) { // Items are added to the listview in reverse order, so invert the index. //toDoDBAdapter.removeTask(todoItems.size()-_index); ToDoItem item = todoItems.get(_index); final long selectedId = item.getTaskId(); mService.removeTask(selectedId); entries--; Toast.makeText(this, "Entry deleted", Toast.LENGTH_SHORT).show(); updateArray(); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, TodoService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; public class TimedToast extends AsyncTask<Long, Integer, Integer> { @Override protected Integer doInBackground(Long... arg0) { if (notifs < 15) { try { Toast.makeText(ToDoList.this, entries + " entries left", Toast.LENGTH_SHORT).show(); notifs++; Thread.sleep(20000); } catch (InterruptedException e) { } } return 0; } } } TodoService.java: package com.examples.todolist; import android.app.Service; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.os.Binder; import android.os.IBinder; public class TodoService extends Service { private final IBinder mBinder = new LocalBinder(); @Override public IBinder onBind(Intent arg0) { return mBinder; } public class LocalBinder extends Binder { TodoService getService() { return TodoService.this; } } public void insertTask(ToDoItem _task) { ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_CREATION_DATE, _task.getCreated().getTime()); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.insert(TodoProvider.CONTENT_URI, values); } public void updateTask(ToDoItem _task) { long tid = _task.getTaskId(); ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.update(TodoProvider.CONTENT_URI, values, TodoProvider.KEY_ID + "=" + tid, null); } public void removeTask(long tid) { ContentResolver cr = getContentResolver(); cr.delete(TodoProvider.CONTENT_URI, TodoProvider.KEY_ID + "=" + tid, null); } public Cursor getAllToDoItemsCursor() { ContentResolver cr = getContentResolver(); return cr.query(TodoProvider.CONTENT_URI, null, null, null, null); } } TodoProvider.java: package com.examples.todolist; import android.content.*; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.net.Uri; import android.text.TextUtils; import android.util.Log; public class TodoProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://com.examples.provider.todolist/todo"); @Override public boolean onCreate() { Context context = getContext(); todoHelper dbHelper = new todoHelper(context, DATABASE_NAME, null, DATABASE_VERSION); todoDB = dbHelper.getWritableDatabase(); return (todoDB == null) ? false : true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder tb = new SQLiteQueryBuilder(); tb.setTables(TODO_TABLE); // If this is a row query, limit the result set to the passed in row. switch (uriMatcher.match(uri)) { case TASK_ID: tb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); break; default: break; } // If no sort order is specified sort by date / time String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = KEY_ID; } else { orderBy = sort; } // Apply the query to the underlying database. Cursor c = tb.query(todoDB, projection, selection, selectionArgs, null, null, orderBy); // Register the contexts ContentResolver to be notified if // the cursor result set changes. c.setNotificationUri(getContext().getContentResolver(), uri); // Return a cursor to the query result. return c; } @Override public Uri insert(Uri _uri, ContentValues _initialValues) { // Insert the new row, will return the row number if // successful. long rowID = todoDB.insert(TODO_TABLE, "task", _initialValues); // Return a URI to the newly inserted row on success. if (rowID > 0) { Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(uri, null); return uri; } throw new SQLException("Failed to insert row into " + _uri); } @Override public int delete(Uri uri, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.delete(TODO_TABLE, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.delete(TODO_TABLE, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.update(TODO_TABLE, values, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.update(TODO_TABLE, values, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case TASKS: return "vnd.android.cursor.dir/vnd.examples.task"; case TASK_ID: return "vnd.android.cursor.item/vnd.examples.task"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } // Create the constants used to differentiate between the different URI // requests. private static final int TASKS = 1; private static final int TASK_ID = 2; private static final UriMatcher uriMatcher; // Allocate the UriMatcher object, where a URI ending in 'tasks' will // correspond to a request for all tasks, and 'tasks' with a // trailing '/[rowID]' will represent a single task row. static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("com.examples.provider.Todolist", "tasks", TASKS); uriMatcher.addURI("com.examples.provider.Todolist", "tasks/#", TASK_ID); } //The underlying database private SQLiteDatabase todoDB; private static final String TAG = "TodoProvider"; private static final String DATABASE_NAME = "todolist.db"; private static final int DATABASE_VERSION = 1; private static final String TODO_TABLE = "todolist"; // Column Names public static final String KEY_ID = "_id"; public static final String KEY_TASK = "task"; public static final String KEY_CREATION_DATE = "date"; public long insertTask(ToDoItem _task) { // Create a new row of values to insert. ContentValues newTaskValues = new ContentValues(); // Assign values for each row. newTaskValues.put(KEY_TASK, _task.getTask()); newTaskValues.put(KEY_CREATION_DATE, _task.getCreated().getTime()); // Insert the row. return todoDB.insert(TODO_TABLE, null, newTaskValues); } public boolean updateTask(long _rowIndex, String _task) { ContentValues newValue = new ContentValues(); newValue.put(KEY_TASK, _task); return todoDB.update(TODO_TABLE, newValue, KEY_ID + "=" + _rowIndex, null) > 0; } public boolean removeTask(long _rowIndex) { return todoDB.delete(TODO_TABLE, KEY_ID + "=" + _rowIndex, null) > 0; } // Helper class for opening, creating, and managing database version control private static class todoHelper extends SQLiteOpenHelper { private static final String DATABASE_CREATE = "create table " + TODO_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_TASK + " TEXT, " + KEY_CREATION_DATE + " INTEGER);"; public todoHelper(Context cn, String name, CursorFactory cf, int ver) { super(cn, name, cf, ver); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE); onCreate(db); } } } I've omitted the other files as I'm sure they are correct. When I run the program, LogCat shows that the NullPointerException occurs in populateTodoList(), at toDoListCursor = mService.getAllToDoItemsCursor(). mService is the Cursor object returned by TodoService. I've added the service to the Manifest file, but I still cannot find out why it's causing an exception. Thanks in advance.

    Read the article

  • Return value changed after finally

    - by Nestor
    I have the following code: public bool ProcessData(String data) { try { result= CheckData(data); if (TextUtils.isEmpty(result)) { summary="Data is invalid"; return false; } ... finally { Period period = new Period(startTime, new LocalDateTime()); String duration = String.format("Duration: %s:%s", period.getMinutes(), period.getSeconds()); LogCat(duration); } return true; As I learned from this question, the finally block is executed after the return statement. So I modified my code according to that, and in the finally I inserted code that does not modify the output. Strangely, the code OUTSIDE the finally block does. My method always returns true. As suggested, it is not a good idea to have 2 return. What should I do?

    Read the article

  • Error when call 'qb.query(db, projection, selection, selectionArgs, null, null, orderBy);'

    - by smalltalk1960s
    Hi all, I make a content provider named 'DictionaryProvider' (Based on NotepadProvider). When my program run to command 'qb.query(db, projection, selection, selectionArgs, null, null, orderBy);', error happen. I don't know how to fix. please help me. Below is my code // file main calling DictionnaryProvider @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dictionary); final String[] PROJECTION = new String[] { DicColumns._ID, // 0 DicColumns.KEY_WORD, // 1 DicColumns.KEY_DEFINITION // 2 }; Cursor c = managedQuery(DicColumns.CONTENT_URI, PROJECTION, null, null, DicColumns.DEFAULT_SORT_ORDER); String str = ""; if (c.moveToFirst()) { int wordColumn = c.getColumnIndex("KEY_WORD"); int defColumn = c.getColumnIndex("KEY_DEFINITION"); do { // Get the field values str = ""; str += c.getString(wordColumn); str +="\n"; str +=c.getString(defColumn); } while (c.moveToNext()); } Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } // file DictionaryProvider.java package com.example.helloandroid; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import com.example.helloandroid.Dictionary.DicColumns; public class DictionaryProvider extends ContentProvider { //private static final String TAG = "DictionaryProvider"; private DictionaryOpenHelper dbdic; static final int DATABASE_VERSION = 1; static final String DICTIONARY_DATABASE_NAME = "dictionarydb"; static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final UriMatcher sUriMatcher; private static HashMap<String, String> sDicProjectionMap; @Override public int delete(Uri arg0, String arg1, String[] arg2) { // TODO Auto-generated method stub return 0; } @Override public String getType(Uri arg0) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri arg0, ContentValues arg1) { // TODO Auto-generated method stub return null; } @Override public boolean onCreate() { // TODO Auto-generated method stub dbdic = new DictionaryOpenHelper(getContext(), DICTIONARY_DATABASE_NAME, null, DATABASE_VERSION); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(DICTIONARY_TABLE_NAME); switch (sUriMatcher.match(uri)) { case 1: qb.setProjectionMap(sDicProjectionMap); break; case 2: qb.setProjectionMap(sDicProjectionMap); qb.appendWhere(DicColumns._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sortOrder)) { orderBy = DicColumns.DEFAULT_SORT_ORDER; } else { orderBy = sortOrder; } // Get the database and run the query SQLiteDatabase db = dbdic.getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy); // Tell the cursor what uri to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(Dictionary.AUTHORITY, "dictionary", 1); sUriMatcher.addURI(Dictionary.AUTHORITY, "dictionary/#", 2); sDicProjectionMap = new HashMap<String, String>(); sDicProjectionMap.put(DicColumns._ID, DicColumns._ID); sDicProjectionMap.put(DicColumns.KEY_WORD, DicColumns.KEY_WORD); sDicProjectionMap.put(DicColumns.KEY_DEFINITION, DicColumns.KEY_DEFINITION); // Support for Live Folders. /*sLiveFolderProjectionMap = new HashMap<String, String>(); sLiveFolderProjectionMap.put(LiveFolders._ID, NoteColumns._ID + " AS " + LiveFolders._ID); sLiveFolderProjectionMap.put(LiveFolders.NAME, NoteColumns.TITLE + " AS " + LiveFolders.NAME);*/ // Add more columns here for more robust Live Folders. } } // file Dictionary.java package com.example.helloandroid; import android.net.Uri; import android.provider.BaseColumns; /** * Convenience definitions for DictionaryProvider */ public final class Dictionary { public static final String AUTHORITY = "com.example.helloandroid.provider.Dictionary"; // This class cannot be instantiated private Dictionary() {} /** * Dictionary table */ public static final class DicColumns implements BaseColumns { // This class cannot be instantiated private DicColumns() {} /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary"); /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ //public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single note. */ //public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /** * The key_word of the dictionary * <P>Type: TEXT</P> */ public static final String KEY_WORD = "KEY_WORD"; /** * The key_definition of word * <P>Type: TEXT</P> */ public static final String KEY_DEFINITION = "KEY_DEFINITION"; } } thanks so much

    Read the article

  • Programmatic Text Wrapping in TextView

    - by Andrew
    I'm working on a custom widget for my application to replicate the look of a Preference button for layouts. The issue is the 'summary' text wont wrap when it hits the right wall of the view. One of the goals I'm trying to keep is that this widget is completely made from java with no xml attributes. here's what the widget looks like at the moment: http://dl.dropbox.com/u/56017670/Screenshot_2012-09-05-17-22-45.png notice that the middle two don't wrap the text but the text obviously runs right off the edge of the widget below is the code I'm using to create the text view. public void setSummary(String summary) { if (!TextUtils.isEmpty(summary)) { if (mSummaryView == null) { mSummaryView = new TextView(mContext); mSummaryView.setTextSize(14); mSummaryView.setTextColor(mContext.getResources().getColor( android.R.color.tertiary_text_dark)); addView(mSummaryView); } mSummaryView.setText(summary); mSummaryView.setVisibility(View.VISIBLE); } else { if (mSummaryView != null) { mSummaryView.setVisibility(View.GONE); } } mSummaryText = summary; } and here is the code I'm using to layout mSummaryView mSummaryView.layout( mPreferencePadding + mIconWidth, centerVertical + (mCombinedTextHeight / 2) - mSummaryHeight, width - mPreferencePadding, centerVertical + (mCombinedTextHeight / 2)); I've tried to add mSummaryView.setSingleLine(false); along with quite a few other tricks but they all ended in the same way.

    Read the article

  • Action bar with Search View. Reverse compatibility issues

    - by suresh
    I am building a sample app to demonstrate SearchView with filter and other Action Bar items. I am able to successfully run this app on 4.2(Nexus 7). But it is not running on 2.3. I googled about the issue. Came to know that i should use SherLock Action bar. I just went to http://actionbarsherlock.com/download.html, downloaded the zip file and added the library as informed in the video: http://www.youtube.com/watch?v=4GJ6yY1lNNY&feature=player_embedde by WiseManDesigns. But still I am unable to figure out the issue. Here is my code: SearchViewActionBar.java public class SearchViewActionBar extends Activity implements SearchView.OnQueryTextListener { private SearchView mSearchView; private TextView mStatusView; int mSortMode = -1; private ListView mListView; private ArrayAdapter<String> mAdapter; protected CharSequence[] _options = { "Wild Life", "River", "Hill Station", "Temple", "Bird Sanctuary", "Hill", "Amusement Park"}; protected boolean[] _selections = new boolean[ _options.length ]; private final String[] mStrings = Cheeses.sCheeseStrings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); setContentView(R.layout.activity_main); // mStatusView = (TextView) findViewById(R.id.status_text); // mSearchView = (SearchView) findViewById(R.id.search_view); mListView = (ListView) findViewById(R.id.list_view); mListView.setAdapter(mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings)); mListView.setTextFilterEnabled(true); //setupSearchView(); } private void setupSearchView() { mSearchView.setIconifiedByDefault(true); mSearchView.setOnQueryTextListener(this); mSearchView.setSubmitButtonEnabled(false); //mSearchView.setQueryHint(getString(R.string.cheese_hunt_hint)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.searchview_in_menu, menu); MenuItem searchItem = menu.findItem(R.id.action_search); mSearchView = (SearchView) searchItem.getActionView(); //setupSearchView(searchItem); setupSearchView(); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (mSortMode != -1) { Drawable icon = menu.findItem(mSortMode).getIcon(); menu.findItem(R.id.action_sort).setIcon(icon); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { String c="Category"; String s=(String) item.getTitle(); if(s.equals(c)) { System.out.println("same"); showDialog( 0 ); } //System.out.println(s); Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } protected Dialog onCreateDialog( int id ) { return new AlertDialog.Builder( this ) .setTitle( "Category" ) .setMultiChoiceItems( _options, _selections, new DialogSelectionClickHandler() ) .setPositiveButton( "SAVE", new DialogButtonClickHandler() ) .create(); } public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener { public void onClick( DialogInterface dialog, int clicked, boolean selected ) { Log.i( "ME", _options[ clicked ] + " selected: " + selected ); } } public class DialogButtonClickHandler implements DialogInterface.OnClickListener { public void onClick( DialogInterface dialog, int clicked ) { switch( clicked ) { case DialogInterface.BUTTON_POSITIVE: printSelectedPlanets(); break; } } } protected void printSelectedPlanets() { for( int i = 0; i < _options.length; i++ ){ Log.i( "ME", _options[ i ] + " selected: " + _selections[i] ); } } public void onSort(MenuItem item) { mSortMode = item.getItemId(); invalidateOptionsMenu(); } public boolean onQueryTextChange(String newText) { if (TextUtils.isEmpty(newText)) { mListView.clearTextFilter(); } else { mListView.setFilterText(newText.toString()); } return true; } public boolean onQueryTextSubmit(String query) { mStatusView.setText("Query = " + query + " : submitted"); return false; } public boolean onClose() { mStatusView.setText("Closed!"); return false; } protected boolean isAlwaysExpanded() { return false; } }

    Read the article

1