Thursday 19 December 2019

listview - Sqlitedatabase throwing an error in android



When ever I click on the Button to save things in my database its crashes...



MainActivity.java class code:



public class MainActivity extends Activity {
private MyAdapter adapter;
private ListView list;
UserDbHelper userDbHelper;

SQLiteDatabase sqLiteDatabase;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

list = (ListView) findViewById(R.id.list);
List devices = new ArrayList<>();
devices.add(new BluetoothDevice("Hello","hahhahahha",null));

adapter = new MyAdapter(getApplicationContext(),0,devices);
list.setAdapter(adapter);


}


public void btnSaveClick(View view) {

userDbHelper = new UserDbHelper(context);

sqLiteDatabase=userDbHelper.getWritableDatabase();
userDbHelper.store(adapter.getAllItem(),sqLiteDatabase);
}


MyAdapter.java java class code



public class MyAdapter extends ArrayAdapter {



public MyAdapter(Context context, int resource, List devices) {
super(context, resource, devices);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// here we can define custom design of list item
TextView textView = new TextView(getContext());
BluetoothDevice item = getItem(position);
textView.setTextColor(Color.BLACK);

textView.setText(item.name + " : " + item.address + " date :" + item.getDateFormatted());
return textView;
}


//method to get all adapter objects
public List getAllItem() {

List result = new ArrayList<>();
for (int i = 0; i < getCount(); i++) {

Log.e("fef", "getAllItem: " );
result.add(getItem(i));
}
return result;
}
}


BluetoothDevice.java class code:




public class BluetoothDevice {
public String name;
public String address;
public Date date;

public BluetoothDevice(String name, String address, Date date) {
this.name = name;
this.address = address;
this.date = date;
}


private SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");

public String getDateFormatted() {
if (date == null) {
return " no date ";
}
return format.format(date);
}
}



UserDbHelper.java class code:



public class UserDbHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "DATABASENAME2";
public static final int DB_VERSION = 1;


public UserDbHelper(Context context)

{
super(context,DATABASENAME,null,DB_VERSION);


}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS BluetoothDevice ( Device VARCHAR , Address VARCHAR , Date VARCHAR);");

}

public Cursor getItemFromDatabase(SQLiteDatabase sqLiteDatabase) {
List result = new ArrayList<>();
// query database elements
Cursor c = sqLiteDatabase.rawQuery("Select * from BluetoothDevice ;", null);

while (c.moveToNext()) {
Date v = new Date();
v.setTime(c.getInt(c.getColumnIndex("Date")) * 1000);
Date date = new Date();
date.setTime(Long.valueOf(c.getString(c.getColumnIndex("Date"))));

result.add(
new BluetoothDevice(
c.getString(c.getColumnIndex("Device")),
c.getString(c.getColumnIndex("Address")),
date

)
);
}
c.close();

return c;
}

public void store(List data,SQLiteDatabase sqLiteDatabase) {
for (BluetoothDevice value : data) {
String s = String.valueOf(new Date().getTime());
//insert in database
sqLiteDatabase.execSQL("INSERT INTO BluetoothDevice VALUES(?,?,?);", new String[]{value.name, value.address, s});

}

}


@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}
}



And when I click that save button the application crashes and throws the next fatal exception:




  com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3591)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
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:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
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:3586)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
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:4745)
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:786)




How could I resolve the issue?


Answer




Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)




The context you're passing to UserDbHelper constructor is not initialized and therefore null. In an activity, just use this as a Context. Replace



userDbHelper = new UserDbHelper(context);


with



userDbHelper = new UserDbHelper(this);



and remove the context field as unnecessary.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...