How to get a single SQLite row data with its id? - android

I have successfully retrieved SQLite data to ListView. Now I am trying to implement OnItemClickListener to show the data in Dialog but I am getting this error
2019-04-08 18:42:53.020 20591-20591/com.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app, PID: 20591
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:292)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:262)
at com.app.SQLiteAdaptor.GetUserByUserId(SQLiteAdaptor.java:99)
at com.app.OrderHistory$1.onItemClick(OrderHistory.java:64)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1181)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3165)
at android.widget.AbsListView$3.run(AbsListView.java:4147)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:173)
at android.app.ActivityThread.main(ActivityThread.java:6634)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:822)
This is where I need to retrieve row
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Dialog fullscreenDialog = new Dialog(getApplicationContext(), R.style.Dialog);
fullscreenDialog.setContentView(R.layout.dialog_oh);
SQLiteAdaptor db = new SQLiteAdaptor(c);
ArrayList<HashMap<String, String>> userList = db.GetUserByUserId(i); //Line 64
HashMap<String, String> hashDetails = userList.get(0);
//Use this index accordingly
tvit.setText(hashDetails.get("item"));
tvpr.setText(hashDetails.get("price"));
tvqu.setText(hashDetails.get("quantity"));
tvad.setText(hashDetails.get("address"));
tvna.setText(hashDetails.get("name"));
tvem.setText(hashDetails.get("email"));
tvtim.setText(hashDetails.get("time"));
fullscreenDialog.show();
}
});
Here is the SQLiteAdaptor get row data by id method snippet
public ArrayList<HashMap<String, String>> GetUserByUserId(int userid ){
SQLiteDatabase db = this.getReadableDatabase(); \\Line 99
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
String query = "SELECT item, price, quantity, name, address, email, orderid FROM "+ Table_Name;
Cursor cursor = db.query(Table_Name, new String[]{COL_2, COL_3, COL_4, COL_5, COL_6, COL_7, COL_8, COL_9}, COL_1+ "=?",new String[]{String.valueOf(userid)},null, null, null, null);
if (cursor.moveToNext()){
HashMap<String,String> user = new HashMap<>();
user.put("item",cursor.getString(cursor.getColumnIndex(COL_2)));
user.put("price",cursor.getString(cursor.getColumnIndex(COL_3)));
user.put("quantity",cursor.getString(cursor.getColumnIndex(COL_4)));
user.put("name",cursor.getString(cursor.getColumnIndex(COL_5)));
user.put("address",cursor.getString(cursor.getColumnIndex(COL_6)));
user.put("email",cursor.getString(cursor.getColumnIndex(COL_7)));
user.put("orderid",cursor.getString(cursor.getColumnIndex(COL_8)));
user.put("time",cursor.getString(cursor.getColumnIndex(COL_9)));
userList.add(user);
}
return userList;
}
And it is not null pointer exception because I am nit getting any error while retrieving data in Listview
Or any other way to how to retrieve row with its id
Any help and solutions are appreciated
Thanks in advance

Try this
SQLiteAdaptor db = new SQLiteAdaptor(view.getContext());

Related

Database query on a specific row

I am building a blood bank database app. Where I will take some info along with blood type. I store the blood type as "INTEGER NOT NULL" with 1, 2,....,7 which indicate A+,.....,AB- blood types. But when I try to query a listview according to the user select the blood group from a spinner, I get errors(stack trace is given below). Inserting data in the database doing great without giving an error.
MainActivity relevant code -
private void displayDatabaseInfo(){
String[] projection = {
DonorEntry.COLUMN_DONOR_NAME,
DonorEntry.COLUMN_DONOR_MOBILE,
DonorEntry.COLUMN_BLOOD_GROUP,
DonorEntry.COLUMN_DONATE_DATE };
String selection = DonorEntry.COLUMN_BLOOD_GROUP + "=?";
String [] selectionArgs = new String[] {getString(mBloodType)};
Cursor cursor = getContentResolver().query(DonorEntry.CONTENT_URI,
projection, selection, selectionArgs,null);
ListView listView = (ListView) findViewById(R.id.list);
DonorCursorAdapter adapter = new DonorCursorAdapter(this, cursor);
listView.setAdapter(adapter);
}
DonorCursorAdapter relevant code -
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView mobileTextView = (TextView) view.findViewById(R.id.mobileNo);
TextView bloodTypeTextView = (TextView) view.findViewById(R.id.bloodType);
TextView lastDonateTextView = (TextView) view.findViewById(R.id.donateDate);
// Find the columns of donor's attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(DonorEntry.COLUMN_DONOR_NAME);
int mobileColumnIndex = cursor.getColumnIndex(DonorEntry.COLUMN_DONOR_MOBILE);
int bloodTypeColumnIndex = cursor.getColumnIndex(DonorEntry.COLUMN_BLOOD_GROUP);
int lastDonateColumnIndex = cursor.getColumnIndex(DonorEntry.COLUMN_DONATE_DATE);
// Read the donor attributes from the Cursor for the current pet
String donorName = cursor.getString(nameColumnIndex);
String donorMobileNo = cursor.getString(mobileColumnIndex);
String donorBloodType = cursor.getString(bloodTypeColumnIndex);
String donorLastDonate = cursor.getString(lastDonateColumnIndex);
// Update the TextViews with the attributes for the current pet
nameTextView.setText(donorName);
mobileTextView.setText(donorMobileNo);
bloodTypeTextView.setText(donorBloodType);
lastDonateTextView.setText(donorLastDonate);
}
Stack trace
<code>
2019-03-02 17:25:37.140 28705-28705/com.sarkerjr.greenBlood E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sarkerjr.greenBlood, PID: 28705
android.content.res.Resources$NotFoundException: String resource ID #0x2
at android.content.res.Resources.getText(Resources.java:339)
at android.content.res.Resources.getString(Resources.java:433)
at android.content.Context.getString(Context.java:556)
at com.sarkerjr.greenBlood.MainActivity.displayDatabaseInfo(MainActivity.java:121)
at com.sarkerjr.greenBlood.MainActivity.access$000(MainActivity.java:21)
at com.sarkerjr.greenBlood.MainActivity$2.onClick(MainActivity.java:56)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>
Here fixed everything for you. There were a few problems.
getString was crashing. This is not the method you want to use to parse any integer, it is used to get a resource and you pass an id of that resource.
CursorAdapter needs _id column inside the cursor and when you passed projection array without _id column, your adapter was crashing. So I removed the projection and now you will get all the columns.
Although this was working somehow but you should not use getString when column value type is INTEGER, so I changed it to getInt.
You were directly assigning the column value to the TextView which was showing integers, so I created a method in MainActivity to get the actual values of blood types.
MainActivity changes -
private void displayDatabaseInfo() {
String selection = DonorEntry.COLUMN_BLOOD_GROUP + "=?";
String[] selectionArgs = new String[]{String.valueOf(mBloodType)};
Cursor cursor = getContentResolver().query(DonorEntry.CONTENT_URI,
null, selection, selectionArgs, null);
ListView listView = findViewById(R.id.list);
DonorCursorAdapter adapter = new DonorCursorAdapter(this, cursor);
listView.setAdapter(adapter);
}
// Get value of readable blood type
public String getBloodTypeString(int bloodType) {
switch (bloodType) {
case A_Positive:
return getResources().getString(R.string.a_positive);
case A_Negative:
return getResources().getString(R.string.a_negative);
case B_Positive:
return getResources().getString(R.string.b_positive);
case B_Negative:
return getResources().getString(R.string.b_negative);
case O_Positive:
return getResources().getString(R.string.o_positive);
case O_Negative:
return getResources().getString(R.string.o_negative);
case AB_Positive:
return getResources().getString(R.string.ab_positive);
case AB_Negative:
return getResources().getString(R.string.ab_negative);
default:
return "UNKNOWN";
}
}
DonorCursorAdapter changes -
int donorBloodType = cursor.getInt(bloodTypeColumnIndex);
String donorBloodTypeString;
try {
donorBloodTypeString = ((MainActivity) context).getBloodTypeString(donorBloodType);
} catch (ClassCastException e) {
throw new ClassCastException("Trying to access MainActivity method from different context");
}
bloodTypeTextView.setText(donorBloodTypeString);
Call
String [] selectionArgs = new String[] {String.valueOf(mBloodType)};
instead of
String [] selectionArgs = new String[] {getString(mBloodType)};

Getting data from sqlite to recycler view

I have used this code with json object. Now I'm with sqlite, and it has NPE error.
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
EDIT
07-13 09:05:29.763 13314-13351/com.example.arlene.capsmobile E/libdataflow_monitor: open error=Operation not permitted
07-13 09:05:31.542 13314-13314/com.example.arlene.capsmobile E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.arlene.capsmobile, PID: 13314
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.example.arlene.capsmobile.translistTab.loadTransList(translistTab.java:135)
at com.example.arlene.capsmobile.translistTab.onCreate(translistTab.java:72)
Error at the line of productTransList.add(product);
Initialize the productTransList first and then add objects to the list.
productTransList = new ArrayList<>();
This will fix the issue.
In your SQLiteHelper Class you need to initialize the List:
public List<Product> getAllProducts() {
try {
List<Product > listProducts = new ArrayList<>();
String selectQuery = "SELECT * FROM " + dbSchema.table_name;
SQLiteDatabase mDb = this.getWritableDatabase();
Cursor cursor = mDb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Product product = new
Product(Integer.parseInt(cursor.getString(0).toString()),
Integer.parseInt(cursor.getString(1).toString()),
cursor.getString(2).toString(),
cursor.getString(3).toString(),
cursor.getString(4).toString(),
cursor.getString(5).toString(),
Double.parseDouble(cursor.getString(6).toString()),
cursor.getString(7).toString());
listProducts.add(mRecord);
} while (cursor.moveToNext());
}
return listProducts;
} catch (Exception ex) {
return null;
}
}
Here is a reference for SQLite:
SQLite Demo
From your activity, use the helper method getAllProducts asynchronously and pass an empty list to it as an input param.
First Initialize a ArrayList
productTransList = new ArrayList<>();
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
Hope this may help you

NullPointerException due to large sized array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
The listview sends an intent to musicplayer Activity. The intent contains integer values used to address songs and it works fine for small number of elements in say a Playlist (a listview) but for large number of songs it crashes (shown in Log below):
Listview:
final int size = lv.getAdapter().getCount();
final String[] F= new String[size];
final int Q[] = new int[size];
// listening to single listitem click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
TextView textView = (TextView) view.findViewById(android.R.id.text1);
String songName = textView.getText().toString();//lv.getItemAtPosition(position).toString();
Queuer(F,Q,size);
//songIndex = manager.getSongIndex(songName, getApplicationContext());
// Starting new intent
Intent i = new Intent(getApplicationContext(), MusicPlayerActivity.class);
Log.d("TAG", "onItemClick");
//// Sending songIndex to PlayerActivity
i.putExtra("size",size);
i.putExtra("queue",Q);
i.putExtra("filtered",true);
// Toast.makeText(getApplicationContext(), "Qi:" + Q[0], Toast.LENGTH_LONG).show();
i.putExtra("start", position);
startActivityForResult(i, 7);
}
});
Queuer method to store the names and indices of songs in arrays
void Queuer(String[] F,int[] Q, int size){
for(int i=0;i<size;i++){
View v = getListView().getChildAt(i);
TextView tv= (TextView) v.findViewById(android.R.id.text1);
F[i] = tv.getText().toString();
Q[i] = manager.getSongIndex(F[i],getApplicationContext());
Toast.makeText(getApplicationContext(), "SongName:" + F[i] , Toast.LENGTH_LONG).show();
}
}
Log:
01-07 00:03:50.293 27292-27292/com.imhotep.musicplayer
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.imhotep.musicplayer, PID: 27292
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.View.findViewById(int)' on a null
object reference
at
com.imhotep.musicplayer.FilteredTracksActivity.Queuer(FilteredTracksActivity.java:307)
at
com.imhotep.musicplayer.FilteredTracksActivity$4.onItemClick(FilteredTracksActivity.java:285)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1213)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3256)
at android.widget.AbsListView$3.run(AbsListView.java:4190)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5706)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1033)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
Need help with this.
Adapter code:
String[] columns = {MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.MIME_TYPE};
String where = android.provider.MediaStore.Audio.Media.ARTIST + "=?";
String whereVal[] = { s };
String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
columns, where, whereVal, orderBy);
//Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
// new String[]{MediaStore.Audio.Media._ID,MediaStore.Audio.Media.TITLE}, where, whereVal, orderBy);
String[] displayFields = new String[]{MediaStore.Audio.Media.TITLE};
int[] displayViews = new int[]{android.R.id.text1};
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor, displayFields,
displayViews, 0);
setListAdapter(adapter);
It happens because ListView recycles item views to save memory.
So you can access null views still present. For this reason if you want to print all songs in your playlist (that should coincide with your ListView right?) you should get data objects from adapter. From there you can access object data directly, not from views objects.

Save JSON to SQLite

I am making an android app and have to save JSON to an SQLite database.
The app already has a function to get JSON and display this in a listview and a function to save data to a database. Now I want to combine those, but I am a little lost.
public void get_data(String data) {
try {
JSONArray data_array=new JSONArray(data);
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
Courses add=new Courses();
add.name = obj.getString("name");
add.ects = obj.getString("ects");
add.grade = obj.getString("grade");
add.period = obj.getString("period");
courses.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
This loops through the JSON so I think this is where is should save to the database.
public boolean insertCourse(String course, int ects, int period, int grade) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COURSE_COLUMN_COURSE, course);
contentValues.put(COURSE_COLUMN_ECTS, ects);
contentValues.put(COURSE_COLUMN_PERIOD, period);
contentValues.put(COURSE_COLUMN_GRADE, grade);
db.insert(COURSE_TABLE_NAME, null, contentValues);
return true;
}
This is in a DBHelper.class should be able to use this I think.
I was hoping to reuse the code which i used to save input fields to the database but no luck so far.
else {
if(dbHelper.insertCourse(courseEditText.getText().toString(),
Integer.parseInt(ectsEditText.getText().toString()),
Integer.parseInt(periodEditText.getText().toString()),
Integer.parseInt(gradeEditText.getText().toString()))) {
Toast.makeText(getApplicationContext(), "Course Inserted", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Could not Insert course", Toast.LENGTH_SHORT).show();
}
Does anyone have a suggestion how to integrate both (if possible at all).
Thnx in advance
EDIT:
the logcat crash report:
04-09 17:45:37.204 12244-12244/com.stefspakman.progress2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.stefspakman.progress2, PID: 12244
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.stefspakman.progress2.ProgressDBHelper.insertCourse(java.lang.String, int, int, int)' on a null object reference
at com.stefspakman.progress2.gradingActivity.get_data(gradingActivity.java:60)
at com.stefspakman.progress2.Download_data$1.handleMessage(Download_data.java:58)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
You need to instantiate your DBHelper class before using the insertCourse Method .
DBHelper helper = new DBHelper(this);
helper.insertCourse(Course course);
Also , its better if you use your Model class object as paramater for database queries .
public boolean insertCourse(Courses courses) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COURSE_COLUMN_COURSE, courses.getCourse());
contentValues.put(COURSE_COLUMN_ECTS, courses.getEcts());
contentValues.put(COURSE_COLUMN_PERIOD, courses.getPeriod());
contentValues.put(COURSE_COLUMN_GRADE, courses.getGrade());
db.insert(COURSE_TABLE_NAME, null, contentValues);
return true;
}
In this way you can save your data from JSON as
db.insert(courses);
The exception says that your ProgressDBHelper is null, please make sure that you are creating an instance of ProgressDBHelper before calling its methods. Creating an instance is just calling ProgressDBHelper dbHelper = new ProgressDBHelper() and you have to call it before calling dbHelper.insertCourse(...)

Cursror into string error cursor.getcolumnIndex Key_titles and therefore cant fill my arraylist

Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
ArrayList<String> mArrayList = new ArrayList<String>();
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
for(curz.moveToFirst(); curz.moveToNext(); curz.isAfterLast())
{ mArrayList.add(name); }
name_Val = (String[]) mArrayList.toArray(new String[mArrayList.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,name_Val);
txtPhoneName.setAdapter(adapter);
I am filling a autocompletetextview and i get an error at String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
it just can't get the correct column index it forcecloses ive tried to wirte mdbHelper.KEY_TITLE or just KEY_TITLE but it was the same error
curz.moveToFirst()
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
do {
mArrayList.add(name);
}while(curz.moveToNext());
First you need to move to first row, then you can get something from it. Because when cursor is created, the pointer points to the -1 index or you can say it points to beforeFirst.
Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
// setTheme(android.R.style.Theme_Light);
curz.moveToFirst();
ArrayList<String> mArrayList = new ArrayList<String>();
if (curz.getCount() > 0)
{
do
{
String name = curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
if(name!=null)
{
mArrayList.add(name);
}
}while (curz.moveToNext());
}

Categories

Resources