NullPointerException when I run this code - android

So in this code, I am trying to retrieve a cursor based on the query passed through my showResults() and then create an adapter and loadermanager. I feel like the problem is being caused with the layout and id within my SimpleCursorAdapter constructor because the error started when I created the layout and id. I used Log and if statement to see whether it was the cursor that was null and nothing showed up on the logcat, so that must mean by cursor is fine.
public class SearchResultsActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private ListView list;
private DatabaseTable db;
private SimpleCursorAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
db = new DatabaseTable(this);
handleIntent(getIntent());
}
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
db = new DatabaseTable(this);
Cursor cursor = db.getContactMatches(query, null);
list = (ListView)findViewById(android.R.id.list);
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
getLoaderManager().initLoader(0, null, this);
list.setAdapter(mAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent contactIntent = new Intent(getApplicationContext(), ContactActivity.class);
contactIntent.setData(getIntent().getData());
startActivity(contactIntent);
}
});
}

Since your code is crashing on the line list.setAdapter(mAdapter);, list is the only object that it makes sense to give you a null pointer.
Upon further examination, it is clear you are not assigning list after it is initially declared. You need to add something like this in onCreate(), after setContentView():
list = (ListView) findViewById(android.R.id.list);
(This is how you'd access it if your object had android:id="#android:id/list"; if you assigned your own ID, use R.id.your_id_here instead.)

this is probably your error here:
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
that adapter requires a Cursor passed into the constructor at the spot where you passed null in for the parameter, like this:
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
cursor, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);

Try getting a readable database first before you query it:
db = new DatabaseTable(this);
Cursor cursor = db.getReadableDatabase().getContactMatches(query, null);

Related

Android onListItemClick exception: "java.lang.String cannot be cast to android.database.Cursor"

As title says, it get this exception from the code I pasted below. I tried to make it work both with the uncommented code and also with the commented part insted of the IF block just before it.
The error I get is: java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor which I don't understand, since the item in the listview should exactly be a String! Any idea?
public class ListScoutActivity extends ListActivity {
private DBHelper database;
private ListView listav;
private Cursor cursor;
ArrayList<String> stringlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_scout);
database = new DBHelper(getApplicationContext());
SQLiteDatabase db = database.getWritableDatabase();
listav = this.getListView();
listav.setVisibility(View.VISIBLE);
int codpartita;
String team;
cursor = db.rawQuery("SELECT _codpartita as _id, team, FROM partita ORDER BY _codpartita DESC", null);
cursor.moveToFirst();
while ( !cursor.isAfterLast() ) {
team = cursor.getString(cursor.getColumnIndex("team"));
stringlist.add(team);
cursor.moveToNext();
}
cursor.moveToFirst();
if (cursor.getCount()>0) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(ListScoutActivity.this,
android.R.layout.simple_list_item_1, cursor, new String[]{"team"},
new int[]{android.R.id.text1}, 0);
listav.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListScoutActivity.this,
// android.R.layout.simple_list_item_1, android.R.id.text1, stringlist);
// listav.setAdapter(adapter);
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor)l.getItemAtPosition(position);
//.. other things..
}

Loading dialog while loading listview from database

i have a problem..
Here is the code:
private final class AsyncSenderAll extends AsyncTask<SimpleCursorAdapter, Void, SimpleCursorAdapter>{
#Override
protected void onPreExecute(){
super.onPreExecute();
pd = new ProgressDialog(PilotLogbook_viewdrafts.this);
pd.setTitle("Drafts");
pd.setMessage("Please wait, refreshing drafts...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
#Override
protected SimpleCursorAdapter doInBackground(SimpleCursorAdapter... params) {
DBAdapter DBHelper = new DBAdapter(PilotLogbook_viewdrafts.this);
DBHelper.open();
Cursor cursor = DBHelper.getAllDrafts();
// The desired columns to be bound
#SuppressWarnings("static-access")
String[] columns = new String[] {
DBHelper.KEY_DATE,
DBHelper.KEY_PIC_NAME,
DBHelper.KEY_AIRCRAFT_REGISTRATION,
DBHelper.KEY_DEPARTURE_PLACE,
DBHelper.KEY_ARRIVAL_PLACE
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.lblLayout_Draft_Date,
R.id.lblLayout_Draft_PIC_Name,
R.id.lblLayout_Draft_Aircraft_Registration,
R.id.lblLayout_Draft_Departure_Place,
R.id.lblLayout_Draft_Arrival_Place
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.layout_pilotlogbook_viewdrafts,
cursor,
columns,
to,
0);
return dataAdapter;
}
#Override
protected void onPostExecute(SimpleCursorAdapter dataAdapter){
super.onPostExecute(dataAdapter);
ListView listView = (ListView) findViewById(R.id.listAllDrafts);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
int RowID = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
Bundle bundle = new Bundle();
bundle.putInt("RowID",RowID);
Intent newIntent = new Intent(getApplicationContext(), PilotLogbook_draftdetails.class);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
finish();
}
});
pd.dismiss();
}
}
I wanna to use a loading dialog while the listview is loading data from database. The problem is that i get
The constructor SimpleCursorAdapter(PilotLogbook_viewdrafts.AsyncSenderAll, int, Cursor, String[], int[], int)
is undefined
at
dataAdapter = new SimpleCursorAdapter(
this, R.layout.layout_pilotlogbook_viewdrafts,
cursor,
columns,
to,
0);
And i don't know how to fix it. Can you guys help me with this part of the code? Thanks in advance! :D
Try this
dataAdapter = new SimpleCursorAdapter(
PilotLogbook_viewdrafts.this, R.layout.layout_pilotlogbook_viewdrafts,
cursor,
columns,
to,
0);
You are using this in the wrong place, in this case this means AsyncSenderAll class, but the adapter requires a context so try to put your Activity class there. For example MainActivity.this:
dataAdapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.layout_pilotlogbook_viewdrafts,
cursor,
columns,
to,
0);
Hope this helps.

Unable to access query

I get db cannot be resloved error in this class. At the displayListView() function. Can anyone please help me solve it. Thanks
got code from here http://kdehairy.com/2012/08/19/using-a-preloaded-sqlite-database-with-sqliteopenhelper/
public class PrepopSqliteDbActivity extends Activity {
// private static final String DB_NAME = "hymnals";
//A good practice is to define database field names as constants
private SimpleCursorAdapter dataAdapter;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Our key helper
ExternalDbOpenHelper repo = ExternalDbOpenHelper.getInstance( context );
SQLiteDatabase db = repo.getWritableDatabase();
displayListView();
}
private void displayListView() {
//all hymns are fetched
*final Cursor cursor = db.fetchAllHymns();*
// The desired columns to be bound
String[] columns = new String[] {
ExternalDbOpenHelper.HYMN_ID,
ExternalDbOpenHelper.HYMN_NAME,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.tVid,
R.id.name,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_main,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
}
});
}
}
The variable db is a local variable within the onCreate method. Use an instance variable instead:
class /* ... */ {
private SQLiteDatabase db;
/* ... */
#Override
public void onCreate(Bundle savedInstanceState) {
/* ... */
db = repo.getWritableDatabase();
/* ... */
}
/* ... */
}

How can i convert this code so i can get the row from list view

I want to be able to fetch a row from a list view and populate textViews in a different activity. I want to be able to do this onclick of an item with the list view..
public class CBFilter extends Activity {
ListView RecipeNames;
Cursor cursor;
SimpleCursorAdapter adapter;
CBDataBaseHelper data;
SQLiteDatabase data2;
TextView RecipeText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecipeNames = (ListView) findViewById(R.id.List1);
RecipeNames.setTextFilterEnabled(true);
RecipeText = (TextView) findViewById(R.id.recipeText);
adapter = new SimpleCursorAdapter (this, 0, cursor, null, null);
data = new CBDataBaseHelper(this);
data.open();
cursor = data.query();
startManagingCursor(cursor);
String[] from = {CBDataBaseHelper.KEY_NAME};
int[] to = { R.id.recipeText};
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
RecipeNames.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void CreateNew(View view){
Intent myIntent = new Intent(this, CBCreate.class);
startActivity(myIntent);
}
}
How can i convert this code in order to achieve the required functionality.. thanks Stefan
try like this
public void onListItemClick(ListView parent, View v, int position, long id) {
String string = from[position]); // this depends on your Adapter ...
Intent i = new Intent(CheckData.this,ShowData.class);
i.putExtra("SELECTED", string);
startActivity(i);
i got it from this link , it will be use full for you :
Use of SQLite

How to click a ListView item in Android

I'm trying to have another activity launch when a list item gets clicked. Below is my code:
public class AvoidForeclosure extends CustomListTitle {
/** Called when the activity is first created. */
private DbAdapter db;
private SimpleCursorAdapter clients;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = getListView();
setContentView(R.layout.main);
this.title.setText("Avoid Foreclosure");
db = new DbAdapter(this);
db.open();
fillData();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
int viewId = view.getId();
TextView theView = (TextView) findViewById(viewId);
String name = theView.getText().toString();
Cursor clientData = db.getClientByName(name);
Intent intent = new Intent();
intent.setClass(view.getContext(), CurrentMarketValue.class);
intent.putExtra("clientId", clientData.getInt(0));
startActivity(intent);
}
});
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = db.fetchAllClients();
startManagingCursor(c);
String[] from = new String[] { DbAdapter.KEY_NAME };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
clients = new SimpleCursorAdapter(this, R.layout.clientsrow, c, from, to);
setListAdapter(clients);
}
}
Yet when I click it, nothing happens at all. Any ideas?
Try switching this line:
ListView list = getListView();
to be after this one:
setContentView(R.layout.main);
Otherwise you'll be getting a handle to the ListActivity's default layout's ListView, rather than R.layout.main's listview (which is the one you really want).

Categories

Resources