I have an android application. In this app I used a AutoCompleteTextView with custom SimpleCursorAdapter. In AutoCompleteTextView addTextChangedListener's onTextChanged method,
I am using below Code
SearchFeedResultsAdaptorCustomer mSearchViewAdapter = new SearchFeedResultsAdaptorCustomer(this.getActivity(), R.layout.searchview_customer, null,
columns, null, -1000);
textView = (AutoCompleteTextView) mRoot.findViewById(R.id.search_box);
textView.setAdapter(mSearchViewAdapter);
textView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
loadData(s.toString());
} catch (JSONException e) {
e.printStackTrace();
}
textView.setAdapter(mSearchViewAdapter);
}
#Override
public void afterTextChanged(Editable s) {
}
});
And the loadData method is:
private void loadData(String searchText) throws JSONException {
ArrayList<JSONObject> filterCustomers = new ArrayList<>();
if (searchText == null || searchText == "") {
filterCustomers = prgmNameList;
} else {
int i = 0;
for (JSONObject customer : prgmNameList) {
if (customer.getString("fullName").toUpperCase().contains(searchText.toUpperCase())) {
filterCustomers.add(customer);
}
}
}
Log.e("searchhh", "load data" + filterCustomers.size());
MatrixCursor matrixCursor = convertToCursor(filterCustomers);
mSearchViewAdapter.changeCursor(matrixCursor);
}
private MatrixCursor convertToCursor(ArrayList<JSONObject> customerList) throws JSONException {
MatrixCursor cursor = new MatrixCursor(columns);
int i = 0;
for (JSONObject customer : customerList) {
String[] temp = new String[8];
i = i + 1;
temp[0] = "" + i;
temp[1] = String.valueOf(customer.getString("accountNumber"));
temp[2] = String.valueOf(customer.getString("address"));
temp[3] = String.valueOf(customer.getString("email"));
temp[4] = String.valueOf(customer.getString("fullName"));
temp[5] = String.valueOf(customer.getString("mobile"));
float point;
if (customer.getString("earn_point") == null) {
point = 0;
} else {
point = Float.parseFloat(customer.getString("earn_point").toString());
}
temp[6] = String.valueOf(point);
temp[7] = String.valueOf(customer.getString("uid"));
cursor.addRow(temp);
}
return cursor;
}
It shows data as list of drop down but when I clicked a list item, I got following error.
Here is my click item method:
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Position", "pos:"+position);
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
//or
//Cursor cursor = (Cursor) parent.getItem(position);
//MatrixCursor matrix = (MatrixCursor)parent.getItemAtPosition(position);
cursor.moveToPosition(position);
Log.e("Position", "pos:"+cursor.getCount());
String feedName = cursor.getString(1);
searchView.setQuery("", false);
searchView.clearFocus();
name.setText(cursor.getString(4));
mobile.setText(cursor.getString(5));
email.setText(cursor.getString(3));
point.setText(cursor.getString(6));
account.setText(cursor.getString(7));
usepontHidden.setText(String.valueOf(0));
}
});
Here is the error message:
08-04 12:19:18.692 2619-2619/? E/AndroidRuntime: FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: After last row.
at android.database.MatrixCursor.get(MatrixCursor.java:73)
at android.database.MatrixCursor.getString(MatrixCursor.java:229)
at com.nybsys.tillbox.sales.FragmentTwo$2.onItemClick(FragmentTwo.java:234)
at android.widget.AutoCompleteTextView.performCompletion(AutoCompleteTextView.java:902)
at android.widget.AutoCompleteTextView.access$500(AutoCompleteTextView.java:91)
at android.widget.AutoCompleteTextView$DropDownItemClickListener.onItemClick(AutoCompleteTextView.java:1192)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
at android.widget.AbsListView$1.run(AbsListView.java:3571)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Related
I made an app in android and it is working fine but when I shifted my app to my main app it start showing error from that point package name is same as that of my previous app then also this is the error that i am getting .I followed many question but cant able to find any solution .
FATAL EXCEPTION: main
Process: unnion.neelay.beatbox, PID: 12739
java.lang.RuntimeException: Unable to start activity ComponentInfo{unnion.neelay.beatbox/unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
it is showing null point exception but it was working properly when not added to the main app.
the ringdroid select activity
public class RingdroidSelectActivity
extends ListActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private SearchView mFilter;
private SimpleCursorAdapter mAdapter;
private boolean mWasGetContentIntent;
private boolean mShowAll;
private Cursor mExternalCursor;
// Result codes
private static final int EXT_STORAGE_PERMISSION_REQ_CODE = 2;
private static final int WRITE_EXTERNAL_STORAGE = 4;
private static final int READ_PHONE_STATE = 3;
private static final int WRITE_SETTINGS = 3;
private static final int CHANGE_CONFIGURATION = 1;
private static final int MODIFY_AUDIO_SETTINGS = 5;
private static final int INTERNET = 6;
private static final int REQUEST_CODE_EDIT = 1;
private static final int REQUEST_CODE_CHOOSE_CONTACT = 2;
// Context menu
private static final int CMD_EDIT = 4;
private static final int CMD_DELETE = 5;
private static final int CMD_SET_AS_DEFAULT = 6;
private static final int CMD_SET_AS_CONTACT = 7;
public RingdroidSelectActivity() {
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
checkReadStoragePermission();
mShowAll = false;
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
if (status.equals(Environment.MEDIA_SHARED)) {
showFinalAlert(getResources().getText(R.string.sdcard_shared));
return;
}
if (!status.equals(Environment.MEDIA_MOUNTED)) {
showFinalAlert(getResources().getText(R.string.no_sdcard));
return;
}
Intent intent = getIntent();
mWasGetContentIntent = intent.getAction().equals(
Intent.ACTION_GET_CONTENT);
// Inflate our UI from its XML layout description.
setContentView(R.layout.media_select);
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowTitleEnabled(false);
try {
mAdapter = new SimpleCursorAdapter(
this,
// Use a template that displays a text view
R.layout.media_select_row,
null,
// Map from database columns...
new String[]{
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media._ID},
// To widget ids in the row layout...
new int[]{
R.id.row_artist,
R.id.row_title,
R.id.row_icon,
R.id.row_options_button},
0);
setListAdapter(mAdapter);
// Normal click - open the editor
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
startRingdroidEditor();
}
});
mExternalCursor = null;
getLoaderManager().initLoader(EXTERNAL_CURSOR_ID, null, this);
} catch (SecurityException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 1
} catch (IllegalArgumentException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 2
}
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.row_options_button) {
// Get the arrow ImageView and set the onClickListener to open the context menu.
ImageView iv = (ImageView) view;
iv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openContextMenu(v);
}
});
return true;
} else if (view.getId() == R.id.row_icon) {
setSoundIconFromCursor((ImageView) view, cursor);
return true;
}
return false;
}
});
// Long-press opens a context menu
registerForContextMenu(getListView());
}
private void setSoundIconFromCursor(ImageView view, Cursor cursor) {
if (0 != cursor.getInt(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
view.setImageResource(R.drawable.type_music);
((View) view.getParent()).setBackgroundColor(
getResources().getColor(R.color.type_bkgnd_music));
}
String filename = cursor.getString(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.DATA));
}
/**
* Called with an Activity we started with an Intent returns.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent dataIntent) {
if (requestCode != REQUEST_CODE_EDIT) {
return;
}
if (resultCode != RESULT_OK) {
return;
}
setResult(RESULT_OK, dataIntent);
//finish(); // TODO(nfaralli): why would we want to quit the app here?
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.select_options, menu);
mFilter = (SearchView) menu.findItem(R.id.action_search_filter).getActionView();
if (mFilter != null) {
mFilter.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
refreshListView();
return true;
}
public boolean onQueryTextSubmit(String query) {
refreshListView();
return true;
}
});
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_record).setVisible(true);
// TODO(nfaralli): do we really need a "Show all audio" item now?
menu.findItem(R.id.action_show_all_audio).setVisible(true);
menu.findItem(R.id.action_show_all_audio).setEnabled(!mShowAll);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_record:
onRecord();
return true;
case R.id.action_show_all_audio:
mShowAll = true;
refreshListView();
return true;
default:
return false;
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,
View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Cursor c = mAdapter.getCursor();
String title = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
menu.setHeaderTitle(title);
menu.add(0, CMD_EDIT, 0, R.string.context_menu_edit);
menu.add(0, CMD_DELETE, 0, R.string.context_menu_delete);
// Add items to the context menu item based on file type
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_ringtone);
menu.add(0, CMD_SET_AS_CONTACT, 0, R.string.context_menu_contact);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_NOTIFICATION))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_notification);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CMD_EDIT:
startRingdroidEditor();
return true;
case CMD_DELETE:
confirmDelete();
return true;
case CMD_SET_AS_DEFAULT:
setAsDefaultRingtoneOrNotification();
return true;
case CMD_SET_AS_CONTACT:
return chooseContactForRingtone(item);
default:
return super.onContextItemSelected(item);
}
}
private void setAsDefaultRingtoneOrNotification() {
Cursor c = mAdapter.getCursor();
// If the item is a ringtone then set the default ringtone,
// otherwise it has to be a notification so set the default notification sound
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_RINGTONE,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_ringtone_success_message,
Toast.LENGTH_SHORT)
.show();
} else {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_NOTIFICATION,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_notification_success_message,
Toast.LENGTH_SHORT)
.show();
}
}
private int getUriIndex(Cursor c) {
int uriIndex;
String[] columnNames = {
MediaStore.Audio.Media.INTERNAL_CONTENT_URI.toString(),
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString()
};
for (String columnName : Arrays.asList(columnNames)) {
uriIndex = c.getColumnIndex(columnName);
if (uriIndex >= 0) {
return uriIndex;
}
// On some phones and/or Android versions, the column name includes the double quotes.
uriIndex = c.getColumnIndex("\"" + columnName + "\"");
if (uriIndex >= 0) {
return uriIndex;
}
}
return -1;
}
private Uri getUri() {
//Get the uri of the item that is in the row
Cursor c = mAdapter.getCursor();
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
return null;
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
return (Uri.parse(itemUri));
}
private boolean chooseContactForRingtone(MenuItem item) {
try {
//Go to the choose contact activity
Intent intent = new Intent(Intent.ACTION_EDIT, getUri());
intent.setClassName(
"unnion.neelay.beatbox.ringdroid",
"unnion.neelay.beatbox.ringdroid.ChooseContactActivity");
startActivityForResult(intent, REQUEST_CODE_CHOOSE_CONTACT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't open Choose Contact window");
}
return true;
}
private void confirmDelete() {
// See if the selected list item was created by Ringdroid to
// determine which alert message to show
Cursor c = mAdapter.getCursor();
String artist = c.getString(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.ARTIST));
CharSequence ringdroidArtist =
getResources().getText(R.string.artist_name);
CharSequence message;
if (artist.equals(ringdroidArtist)) {
message = getResources().getText(
R.string.confirm_delete_ringdroid);
} else {
message = getResources().getText(
R.string.confirm_delete_non_ringdroid);
}
CharSequence title;
if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_RINGTONE))) {
title = getResources().getText(R.string.delete_ringtone);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_ALARM))) {
title = getResources().getText(R.string.delete_alarm);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_NOTIFICATION))) {
title = getResources().getText(R.string.delete_notification);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
title = getResources().getText(R.string.delete_music);
} else {
title = getResources().getText(R.string.delete_audio);
}
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.delete_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
onDelete();
}
})
.setNegativeButton(
R.string.delete_cancel_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.setCancelable(true)
.show();
}
private void onDelete() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
showFinalAlert(getResources().getText(R.string.delete_failed));
return;
}
if (!new File(filename).delete()) {
showFinalAlert(getResources().getText(R.string.delete_failed));
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
getContentResolver().delete(Uri.parse(itemUri), null, null);
}
private void showFinalAlert(CharSequence message) {
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(getResources().getText(R.string.alert_title_failure))
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void onRecord() {
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse("record"));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void startRingdroidEditor() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse(filename));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void refreshListView() {
mExternalCursor = null;
Bundle args = new Bundle();
args.putString("filter", mFilter.getQuery().toString());
getLoaderManager().restartLoader(EXTERNAL_CURSOR_ID, args, this);
}
private static final String[] EXTERNAL_COLUMNS = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_NOTIFICATION,
MediaStore.Audio.Media.IS_MUSIC,
"\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\""
};
private static final int EXTERNAL_CURSOR_ID = 1;
/* Implementation of LoaderCallbacks.onCreateLoader */
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
ArrayList<String> selectionArgsList = new ArrayList<String>();
String selection;
Uri baseUri;
String[] projection;
switch (id) {
case EXTERNAL_CURSOR_ID:
baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
projection = EXTERNAL_COLUMNS;
break;
default:
return null;
}
if (mShowAll) {
selection = "(_DATA LIKE ?)";
selectionArgsList.add("%");
} else {
selection = "(";
for (String extension : SoundFile.getSupportedExtensions()) {
selectionArgsList.add("%." + extension);
if (selection.length() > 1) {
selection += " OR ";
}
selection += "(_DATA LIKE ?)";
}
selection += ")";
selection = "(" + selection + ") AND (_DATA NOT LIKE ?)";
selectionArgsList.add("%espeak-data/scratch%");
}
String filter = args != null ? args.getString("filter") : null;
if (filter != null && filter.length() > 0) {
filter = "%" + filter + "%";
selection =
"(" + selection + " AND " +
"((TITLE LIKE ?) OR (ARTIST LIKE ?) OR (ALBUM LIKE ?)))";
selectionArgsList.add(filter);
selectionArgsList.add(filter);
selectionArgsList.add(filter);
}
String[] selectionArgs =
selectionArgsList.toArray(new String[selectionArgsList.size()]);
return new CursorLoader(
this,
baseUri,
projection,
selection,
selectionArgs,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER
);
}
/* Implementation of LoaderCallbacks.onLoadFinished */
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case EXTERNAL_CURSOR_ID:
mExternalCursor = data;
break;
default:
return;
}
// TODO: should I use a mutex/synchronized block here?
if (mExternalCursor != null) {
Cursor mergeCursor = new MergeCursor(new Cursor[]{mExternalCursor});
mAdapter.swapCursor(mergeCursor);
}
}
/* Implementation of LoaderCallbacks.onLoaderReset */
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
#TargetApi(Build.VERSION_CODES.M)
private void checkReadStoragePermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, EXT_STORAGE_PERMISSION_REQ_CODE);
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
onPermissionsNotGranted();
}
dialog.dismiss();
finish();
startActivity(getIntent());
}
};
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.permissions_title)
.setMessage(R.string.read_ext_permissions_message)
.setPositiveButton(R.string.btn_continue, onClickListener)
.setNegativeButton(R.string.btn_cancel, onClickListener)
.setCancelable(false)
.show();
return;
}
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, EXT_STORAGE_PERMISSION_REQ_CODE);
return;
}
}
private void onPermissionsNotGranted() {
Toast.makeText(this, R.string.toast_permissions_not_granted, Toast.LENGTH_SHORT).show();
Log.v("tom", "JERRY");
}
}
Looking at your callstack it should really help you narrow down your problem.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
For example, in your callstack, you first have the exception that's being thrown, NullPointerException, and it's telling you what is causing it.
java.lang.String.equals(java.lang.Object)
So, you have a String that you're attempting to call .equals on, but the String is null.
Now, a bit lower, it shows the line number of where this issue is happening.
unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
So, you're calling .equals within your RingdroidSelectActivity's onCreate at line 123.
However, perhaps your code has changed since you posted your error, there isn't a .equals around that line, but I'm thinking it may be your getExternalStroage().
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
Perhaps you don't have the permission for this or something else. Add in some checks for null, and that will help you debug the problem.
Hopefully that helps!
Edit:
The issue was this
so the answer is
mWasGetContentIntent = Intent.ACTION_GET_CONTENT.equals(intent.getAction());
I have struggled to load more items on listview after calling notifyDataSetChanged() method
Here is the code block for setting user scroll action on listview
lv = (ListView) getActivity().findViewById(R.id.list);
adapter = new ItemListAdapter(getActivity(), getList(), 2);
progressDialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
lv.setAdapter(adapter);
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, SPLASH_TIME_OUT);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (userScrolled) {
userScrolled = false;
progressDialog.getWindow().setGravity(Gravity.BOTTOM);
progressDialog.show();
updateListView();
}
}
});
And here is my updateListView method:
private void updateListView() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (appPreference.getLoadStatus().equals("0")) {
for (int i = 0; i < getListMore().size(); i++) {
Log.i("MORE VALUES", "" + getListMore().get(i));
getList().add(getListMore().get(i));
}
appPreference.saveLoadStatus("1");
}
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, 100);
}
Here is my getList() method
public List<ItemList> getList() {
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}
My intention is to load more items using getListMore() method which load data from database, add them into getList() method which returns List<ItemList>
The problem comes when i scroll the listview there is no new data loaded onto it ,the logs shows the
Log.i("MORE VALUES", "" + getListMore().get(i)); returned the data from database but no data has been shown on listview.
Can anyone help with the issue as why the data is not loaded and how to fix it?
Thanks
Can you try changing:
new Handler().postDelayed(new Runnable() {
to:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
The method adapter.notifyDataSetChanged(); needs to be called from the main thread only.
You are actually fetching the data, adding it into list with getList() but not setting that list. you probably need to setlist() with new values.
Something like, setList(new updated list here) and then adapter.notifyDataSetChanged()
you need to make getList() more clear, see every time you get getList() and add new item in it, it reinstanitate the list, add the old items in it which you have added veru first time. better to make a change the method something like this.
public List<ItemList> getList() {
if(list != null || list.size() > 0) {
return list;
}
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}
I am not able to get edittext value from dynamic listview. When I am scrolling listview, entered values in edit text is going invisible
Below is My Activity file -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_servic_homepage);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
url = getResources().getString(R.string.webservice);
aq = new AQuery(ServicHomepage.this);
cd = new ConnectionDetector(ServicHomepage.this);
findviewbyId();
progressdialog();
if (cd.isConnectingToInternet()) {
getintentData();
} else {
Toast.makeText(ServicHomepage.this, "CheckIternet connection", Toast.LENGTH_SHORT).show();
}
}
private void progressdialog() {
pd = new ProgressDialog(ServicHomepage.this);
pd.setMessage("Loading...");
}
public void findviewbyId() {
recyclerview = (ListView) findViewById(R.id.service_recycler_view);
update_descrptn = (TextView) findViewById(R.id.update_descrptn);
uploadimages = (TextView) findViewById(R.id.uploadimages);
}
public void getintentData() {
SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
catid = prefs.getString(Constants.CATID, "");
subcatid = prefs.getString(Constants.SUBCATID, "");
user_id = prefs.getString(Constants.USERID, "");
isappointment = prefs.getString(Constants.IS_APPOINTMENT, "");
clicklistener();
}
public void clicklistener() {
uploadimages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), GalleryAlbumActivity.class);
startActivity(i);
}
});
update_descrptn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ServicHomepage.this, "" + serv_adapter.getItem(POSITION), Toast.LENGTH_SHORT).show();
for (int i = 0; i < serv_adapter.getCount(); i++) {
View view = serv_adapter.getView(i,null,null);
EditText edittext = (EditText)view.findViewById(R.id.et_amount);
EditText et_description = (EditText)view.findViewById(R.id.et_description);
String str = edittext.getText().toString();
String str1 = et_description.getText().toString();
Toast.makeText(ServicHomepage.this, str + "==" + str1, Toast.LENGTH_SHORT).show();
}
updateList();
}
});
}
private void updateList() {
String substring = null, msgString = "";
String MAIN_CART = null;
MAIN_CART = "{\"service\":[%s]}";
String temstring = "";
for (int i = 0; i < arrayList.size(); i++) {
substring = "{\"title\":\"" + arrayList.get(i).getTitle() + "\",\"subcatid\":\"" + arrayList.get(i).getSubcatid()
+ "\",\"amount\":\"" + "" + "\",\"description\":\"" + "" + "\"}" + ",";
temstring = temstring + substring;
}
temstring = temstring.substring(0, temstring.length() - 1);
msgString = msgString + String.format(MAIN_CART, temstring);
Log.e("msgString=============", msgString);
}
This is the method where all the items are adding in the list
public String parseanimcat(String object) {
try {
JSONObject json = new JSONObject(object);
JSONObject jsonobj = json.getJSONObject("data");
status1 = jsonobj.getString("status");
message = jsonobj.getString("message");
arrayList = new ArrayList<>();
JSONArray jarray = jsonobj.getJSONArray("dataFound");
for (int i = 0; i <= jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
String category = jobj.getString("category");
String subsubcat_id = jobj.getString("subsubcat_id");
Toast.makeText(ServicHomepage.this, category + "==" + subsubcat_id, Toast.LENGTH_SHORT).show();
model = new Data_Model();
model.setTitle(category);
model.setSubcatid(subsubcat_id);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
This is my adapter class-
private class service_list_adapter extends ArrayAdapter<Data_Model>{
private ArrayList<Data_Model> array_list;
Context context;
String[] etValArr;
ViewHolder holder;
String[] totalValue;
Data_Model model;
HashMap<String, String> hm = new HashMap<>();
ArrayList<HashMap<String, String>> list = new ArrayList<>();
public service_list_adapter(Context context,int resourceId,ArrayList<Data_Model> arrayList) {
super(context,resourceId,arrayList);
this.context = context;
this.array_list = arrayList;
etValArr = new String[array_list.size()];
totalValue = new String[array_list.size()];
}
private class ViewHolder {
public TextView serv_title;
public EditText serv_descrptn, serv_amount;
}
public View getView(int position, View convertView, ViewGroup parent) {
model = array_list.get(position);
POSITION = position;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.serv_cat_rowitem, null);
holder = new ViewHolder();
holder.serv_title = (TextView) convertView.findViewById(R.id.serv_txt);
holder.serv_descrptn = (EditText) convertView.findViewById(R.id.et_description);
holder.serv_amount = (EditText) convertView.findViewById(R.id.et_amount);
convertView.setTag(holder);
holder.serv_title.setTag(position);
holder.serv_descrptn.setTag(position);
holder.serv_amount.setTag(position);
} else
holder = (ViewHolder) convertView.getTag();
holder.serv_title.setText(model.getTitle());
holder.serv_descrptn.setText(model.getServdescription());
holder.serv_amount.setText(model.getServamount());
holder.serv_amount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServamount(s.toString());
}
});
holder.serv_descrptn.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServdescription(s.toString());
}
});
return convertView;
}
}
be more specific exactly which editText value you want.
you can implement onScrollListner on list and save the value of the editText on that event and later use it
Hi i'm still trying to make my wavPlayer. My apps has listitem that contain wav file. When I click a file, it should be played but it didn't. I've tried some way on OnListItemClick() to make it work (I marked it with double slash), but it still error. Most of error are nullpointer. Anybody can help me?
here's my code and log cat
public class PlayercobaActivity extends ListActivity implements View.OnClickListener {
private MediaCursorAdapter mediaAdapter = null;
PlayAudio playTask;
Button startRecordingButton, stopRecordingButton, startPlaybackButton,
stopPlaybackButton;
boolean isPlaying = false;
int frequency = 11025;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
//File item ;
String item;
// File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Datarekaman/recording5.wav");
//Cursor acursor;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playercoba);
startPlaybackButton = (Button) this .findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
startPlaybackButton.setEnabled(true);
stopPlaybackButton.setEnabled(false);
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null; // unordered
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("wav");
String[] selectionArgsPdf = new String[]{ mimeType };
Cursor cursor = cr.query(uri, projection , selectionMimeType, selectionArgsPdf, sortOrder );
if(null != cursor)
{
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
}
}
//#Override
public void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
//String name = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DISPLAY_NAME));
//item =(String) list.getItemAtPosition(position);
//File item = new File(name);
//item = new File();
//item = (String) view.getTag();
//item = (String) getListAdapter().getItem(position);
item = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DATA));
//playTask = new PlayAudio();
//playTask.execute();
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
if (v == startPlaybackButton) {
play();
} else if (v == stopPlaybackButton) {
stopPlaying();
}
}
public void play() {
startPlaybackButton.setEnabled(false);
playTask = new PlayAudio();
playTask.execute();
stopPlaybackButton.setEnabled(true);
}
public void stopPlaying() {
isPlaying = false;
stopPlaybackButton.setEnabled(false);
startPlaybackButton.setEnabled(true);
}
private class PlayAudio extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
isPlaying = true;
int bufferSize = AudioTrack.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
short[] audiodata = new short[bufferSize/4];
try {
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream(item)));
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC, frequency,
channelConfiguration, audioEncoding, bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
while (isPlaying && dis.available() > 0) {
int i = 0;
while (dis.available() > 0 && i < audiodata.length) {
audiodata[i] = dis.readShort();
i++;
}
audioTrack.write(audiodata, 0, audiodata.length);
}
dis.close();
startPlaybackButton.setEnabled(false);
stopPlaybackButton.setEnabled(true);
} catch (Throwable t) {
Log.e("AudioTrack", "Playback Failed");
}
return null;
}
protected void onPostExecute(Void result) {
startPlaybackButton.setEnabled(true);
stopPlaybackButton.setEnabled(false);
}
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[] { MediaStore.MediaColumns.DISPLAY_NAME},
new int[] { R.id.displayname});
}
}
}
LogCat
05-19 23:01:17.015 13752-13752/com.example.agita.playercoba E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.agita.playercoba.PlayercobaActivity.onListItemClick(PlayercobaActivity.java:93)
at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1287)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3078)
at android.widget.AbsListView$1.run(AbsListView.java:4159)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4947)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
if you are extending CursorAdapter, you can get the Cursor at position through the first argument of onListItemClick
Cursor cursor = (Cursor) list.getItemAtPosition(position);
item = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DATA));
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
I have a problem that I have tried several different failed solutions for.
I have a AutoCompleteTextView with a SimpleCursorAdaptor tied to my database to pull the names of products. When a user searches for a product, the name shows up fine. It is when they click on the product that a NullPointerException comes up and crashes the app. And the funny thing is, it only happens on HTC Devices. My Samsung works, my buddies Motorola works, the Emulator works. Just not a HTC.
Here is the stack trace from a User submitted from the Android Market.
java.lang.NullPointerException
at enders.pos.test.PointOfSale$8.onItemClick(PointOfSale.java:571)
at android.widget.AutoCompleteTextView.onCommitCompletion(AutoCompleteTextView.java:921)
at com.android.internal.widget.EditableInputConnection.commitCompletion(EditableInputConnection.java:78)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:309)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:75)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3835)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
at dalvik.system.NativeStart.main(Native Method)
Line 571 is:
Cursor c = shop.getProdByName(text.getText().toString());
I believe that it the TextView text is returning null. But I am unsure why.
Below is part of class PointOfsale:
final int[] to = new int[] { android.R.id.text1 };
final String[] from = new String[] { "name" };
SimpleCursorAdapter Autoadapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null,
from, to);
textView = (AutoCompleteTextView) findViewById(R.id.autoproduct);
textView.setAdapter(Autoadapter);
textView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
TextView text = (TextView) view;
Cursor c = shop.getProdByName(text.getText().toString());
if(c != null){
if(c.getColumnIndex("_id") >= 0){
Product product = new Product();
product.setId(c.getInt(c.getColumnIndex("_id")));
product.setBarcode(c.getString(c.getColumnIndex("barcode")));
product.setName(c.getString(c.getColumnIndex("name")));
product.setDesc(c.getString(c.getColumnIndex("desc")));
product.setPrice(c.getFloat(c.getColumnIndex("price")));
product.setCat(c.getInt(c.getColumnIndex("catid")));
cart.AddProduct(product);
c.close();
}else{
alertbox("Not Found", "Product not found");
}
}else{
alertbox("Not Found", "Product not found");
}
textView.setText("");
((ProductAdapter) inventoryList.getAdapter()).notifyDataSetChanged();
}
});
Autoadapter.setCursorToStringConverter(new CursorToStringConverter() {
public String convertToString(android.database.Cursor cursor) {
// Get the label for this row out of the "state" column
final int columnIndex = cursor.getColumnIndexOrThrow("name");
final String str = cursor.getString(columnIndex);
return str;
}
});
// Set the FilterQueryProvider, to run queries for choices
// that match the specified input.
Autoadapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
// Search for states whose names begin with the specified letters.
Cursor cursor = ProductDatabase.helper.fetchItemsByName(
(constraint != null ? constraint.toString() : null));
return cursor;
}
});
Add a log at your code where you are getting the error and see if it's returning a value from the HTC device's Logcat. It's probably that there's a difference in handling the text view for that device.Do some system out to check if they are null or not.
System.out.println(text,text.getText().toString());
If it is returning a null for the HTC device only then you need to find a workaround for it's either your view hierarchy logic is wrong ( which seems okay here) or there's a bug for HTC devices.If that's the case pretty tough to solve then have good luck.
I have found a great solution to my problem! I have gotten rid of the SimpleCursorAdaptor and implemented my own method. I have also determined that several devices handles the UI differently. So i implemented a brute force method to get the data from 4 different methods. If one fails, it moves on to the next one. But one method should always get the data. Here is the code:
Autoadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line);
Autoadapter.setNotifyOnChange(true);
textView = (AutoCompleteTextView) findViewById(R.id.autoproduct);
textView.setAdapter(Autoadapter);
textView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
boolean isAGo = false;
String item = null;
Cursor c = null;
if(listView != null){
item = listView.getItemAtPosition(position).toString();
c = shop.getProdByName(item);
isAGo = true;
}
if(isAGo == false){
if(view != null){
TextView text = (TextView) view;
c = shop.getProdByName(text.getText().toString());
isAGo = true;
}
}
if(isAGo == false){
if(textView.getText() != null){
item = textView.getText().toString();
c = shop.getProdByName(item);
isAGo = true;
}
}
if(isAGo == false){
if(prodList.length > 0){
item = prodList[0];
c = shop.getProdByName(item);
isAGo = true;
}
}
if(c != null){
if(c.getColumnIndex("_id") >= 0){
Product product = new Product();
product.setId(c.getInt(c.getColumnIndex("_id")));
product.setBarcode(c.getString(c.getColumnIndex("barcode")));
product.setName(c.getString(c.getColumnIndex("name")));
product.setDesc(c.getString(c.getColumnIndex("desc")));
product.setPrice(c.getFloat(c.getColumnIndex("price")));
product.setCat(c.getInt(c.getColumnIndex("catid")));
cart.AddProduct(product);
}else{
alertbox("Not Found", "Product not found");
}
}else{
alertbox("Error", "Unable to retrieve product.");
}
textView.setText("");
((ProductAdapter) inventoryList.getAdapter()).notifyDataSetChanged();
}
});
textView.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
prodList = ProductDatabase.helper.fetchItemsByName(s.toString());
if(prodList != null){
Autoadapter.clear();
for (int i = 0; i < prodList.length; i++)
{
Log.v("Items", "Item: " + prodList[i]);
Autoadapter.add(prodList[i]);
}
}else{
Autoadapter.clear();
}
}
});