I am trying to put the values of two columns created in the database to two text views of simple list item 2 using simple cursor adapter but I am getting NPE.
Please help.
Regards
My code is:
class NotesList extends ListActivity{
private DataSource datasource;
ArrayAdapter<Message> adapter;
Cursor cursors = null;
private SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
datasource = new DataSource(this);
datasource.open();
// List<Message> values = datasource.getAllMessages();
// adapter = new ArrayAdapter<Message>(this, android.R.layout.simple_list_item_1, values);
// setListAdapter(adapter);
String queryz = "SELECT " + MySQLiteHelper.COLUMN_ID + "," + MySQLiteHelper.COLUMN_MESSAGE+ " FROM " + MySQLiteHelper.TABLE_NAME ;
cursors = database.rawQuery(queryz, null);
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
cursors, // Pass in the cursor to bind to.
new String[] {MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_MESSAGE}, // Array of cursor columns to bind to.
new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
setListAdapter(adapter);
}
#Override
public void onResume() {
datasource.open();
super.onResume();
}
#Override
public void onPause() {
datasource.close();
super.onPause();
}
Datasource and Mysqlitehelper are the names of my classes.MySqliteHelper class creates the two columns of id and notes.
Logcat is:
03-19 01:15:32.557: E/AndroidRuntime(10579): FATAL EXCEPTION: main
03-19 01:15:32.557: E/AndroidRuntime(10579): java.lang.RuntimeException: Unable to start activity ComponentInfo{soft.b.notes/soft.b.notes.NotesList}: java.lang.NullPointerException
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.access$600(ActivityThread.java:122)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.os.Looper.loop(Looper.java:137)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.main(ActivityThread.java:4340)
Your database is not initialized.
Also, it's useful to examine the full stack trace. There's a "caused by" exception nested in the RuntimeException. Double-clicking a stacktrace row in your IDE would show exactly the line of code where the problem occurs.
You're running a rawQuery on a database that's null. I don't see anywhere that you actually get a SQLiteDatabase for your database variable.
Related
I have update from database using set status method when click button to getting error i have send to array list to next activity while getting error
I'm new in android programming
ImageButton ibAddMore = (ImageButton) findViewById(R.id.ibAddMore);
ibAddMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
for (People people : alertList) {//In this Line getting error
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
alertList.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
Intent intent = new Intent(AlertList.this, AlertListAll.class);
startActivity(intent);
}
}
);
Set Status Method
public int setStatus(String peopleId, String status) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STATUS, status);
return sqLiteDatabase.update(TABLE_PEOPLE, values, ID + "=?",
new String[]{peopleId});
}
Exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:62)
at com.Jaydeep.alertme.activity.AlertList$1.onClick(AlertList.java:67)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
you can't modify the same collection you are looping on directly. But you can do it using a ListIterator. E.g.
for (ListIterator<People> iterator = alertList.listIterator(); iterator.hasNext(); ) {//In this Line getting error
People people = iterator.next();
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
iterator.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
You are adding elements to the same list while you are iterating. It's more java than android.
Btw why you want to add the same element again to the list you are iterating thru ?
I am having an issue with my college project. I am trying to delete a row from my one of my tables using the following query.
//---deletes a particular match---
public boolean deleteMatch(String name) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
return sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = " + name, null) > 0;
}
Here I am trying to delete a record based upon the match_opponent and passing the String value name.
I am then calling this method in my EditSchedule activity below:
public class EditSchedule extends AppCompatActivity {
public Button fixtureSearch;
public EditText opponentName;
public String searchTerm;
ListView editMatch;
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase sqLiteDatabase;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editfixture);
editMatch = (ListView) findViewById(R.id.listViewEditMatch);
opponentName = (EditText) findViewById(R.id.fixtureOpponentDelete);
searchTerm = opponentName.getText().toString();
fixtureSearch = (Button) findViewById(R.id.fixtureSearchButton);
fixtureSearch.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteMatch(searchTerm);
}
}
);
}
}
So when I test my application by typing in a name of an opponent that I have in the fixture table and clicking on the delete button, I get the following error:
01-06 07:49:42.476 25778-25778/com.example.myacer.clubhub E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: DELETE FROM fixtures WHERE match_opponent =
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.delete(SQLiteDatabase.java:1494)
at com.example.myacer.clubhub.database.DBHelper.deleteMatch(DBHelper.java:243)
at com.example.myacer.clubhub.manager.EditSchedule$1.onClick(EditSchedule.java:47)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Can anyone see where I am going wrong? All help greatly appreciated.
You are passing blank value in deleteMatch(), put searchTerm = opponentName.getText().toString(); inside onClick()
fixtureSearch.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
searchTerm = opponentName.getText().toString();
dbHelper.deleteMatch(searchTerm);
}
}
);
As well as change your deleteMatch() method
sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = ?",new String[]{name});
try this:
sqLiteDatabase.delete(TABLE_FIXTURES, MATCH_OPPONENT + " = ?", new String[]{name})
I want to refresh data in ListFragment from my custom adapter class, but got the error NullPointerException.
This is Adaper class method:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BasketFragment basketFragment = new BasketFragment();
basketFragment.getBsketList();
}
});
And when I call it in my Fragment class I get java.lang.NullPointerException at mDataBase = dbHelper.getWritableDatabase();
getBasketList():
public void refreshList() {
dbAdaper.setArrayMyData(selectAll());
dbAdaper.notifyDataSetChanged();
}
And here is the part where I got the error:
public ArrayList<BasketData> selectAll() {
Cursor mCursor = null;
dbHelper = new DBHelper(getActivity());
mDataBase = dbHelper.getWritableDatabase();//NullPointerException
mCursor = mDataBase.query("orderTable", null, null, null, null, null, null);
LogCat:
java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.epon.fragments.BasketFragment.selectAll(BasketFragment.java:100)
at com.epon.fragments.BasketFragment.getBsketList(BasketFragment.java:142)
at com.epon.adapters.DBBasketAdapter$2.onClick(DBBasketAdapter.java:177)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Have you set the context right?
Android: NullPointerException on getWritableDatabase()
NullPointerException on getWritableDatabase()
I think that his is your problem a problem.
Maybe if this is not helping posting the content of getActivity() might be helpful?
edit
Your logcat makes me keep thinking that its a context error!
I'm getting a force close issue after attempting to implement a splash screen into my app.
The issue occurs on line 76 lv.setAdapter(adapter); however I'm unsure as to why.
Any input is greatly appreciated.
09-19 15:20:53.687: E/AndroidRuntime(25177): FATAL EXCEPTION: main
09-19 15:20:53.687: E/AndroidRuntime(25177): java.lang.NullPointerException
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:76)
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:1)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.AsyncTask.finish(AsyncTask.java:631)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.Looper.loop(Looper.java:137)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.app.ActivityThread.main(ActivityThread.java:4931)
09-19 15:20:53.687: E/AndroidRuntime(25177): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 15:20:53.687: E/AndroidRuntime(25177): at java.lang.reflect.Method.invoke(Method.java:511)
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
09-19 15:20:53.687: E/AndroidRuntime(25177): at dalvik.system.NativeStart.main(Native Method)
SOURCE:
public class MainActivity extends Activity {
Context context;
ArrayList<String> aa = new ArrayList<String>();
ListView lv;
final String URL = "http://news.google.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(R.layout.splash);
lv= (ListView) findViewById(R.id.listView1);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
aa.add(element.text().toString());
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aa);
lv.setAdapter(adapter);
}
}
}
Not to beat a dead horse but lv is null since you changed the layout with setContentView(). Maybe I can explain a little better why this is because I'm not sure you quite understand how Views work in the Activity.
When you call setContentView() it inflates the xml layout file that you set in this function. Initializing any View that is not in that layout file will return null which will give a NPE when you try to set a method on it such as setAdapter().
It appears that you are under the assumption that you can still initialize the ListView which is in another layout file...you cannot. You can only use Views inflated with setContentView() or by inflating the layout file which holds that View and adding it to the currently inflated `layout.
One way around this is to call setContentView() again in onPostExecute() then initialize your ListView and set the Adapter. I wouldn't normally recommend calling setContentView() more than once in a single Activity but in your case it may be the easiest for what you currently have.
So it might look like this
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aa);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
Is there a View named R.id.listView1 in splash.xml? It looks like you changed your setContentView() call to the splash screen, but your listview is on a more "main" page.
lv is likely null here. Have you verified in the debugger that it is getting set correctly when you set it to (ListView) findViewById(R.id.listView1);?
Null Pointer Exception suggest that there might be problem with lv.
You have changed the name of xml.so verify whether R.id.listview1 is present in splash.xml
New to Android here. I've made a new Fragments app, and I'm having trouble accessing the database from the Fragment.
Here's the class:
public class ShopListActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoplist);
db = new DatabaseHelper(this); // tried getApplicationContext(), and getBaseContext() as well
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public void onClickAddProduct(View view) {
TextView productName = (TextView) findViewById(R.id.add_product_text);
SQLiteDatabase dbWritable = db.getWritableDatabase(); // <-- crashes here
ContentValues values = new ContentValues();
values.put("Name", (String) productName.getText());
dbWritable.insert("Lists", "Name", values);
}
All the other solutions I found on SO didn't help.
DatabaseHelper is a very basic DB Helper class:
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_TABLES);
db.execSQL("INSERT INTO Lists (Name) VALUES('Test')");
}
Here's the Logcat:
07-07 21:03:24.351 9641-9641/com.chas.shopforme E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3606)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17362)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3601)
... 11 more
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.chas.shopforme.ShopListActivity.onClickAddProduct(ShopListActivity.java:69)
... 14 more
Note: I know there are more questions like this, but their solutions didn't work for me.
try this
db = new DatabaseHelper(this.getApplicationContext());
I tried adding this as a comment to your question, but nasty things happen to code in comments.
Assuming you've tried a) in the comment above, and it didn't work, an example of b) follows:
protected void onCreate(Bundle savedInstanceState) {
...
Handler hand = new Handler();
hand.post(new Runnable() {
public void run() {
dbInit();
}
});
}
public void dbInit() {
db = new DatabaseHelper(this);
}
This allows the fragment manager to finish setting up the fragment before you try to use it. What it is doing is sending a message to itself which is processed when the fragment's message handler loop is running.