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
Related
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());
Experts,
Below code is to get data for ExpandableListAdapter. I have problem about the List temp.
Let say I have below data in db:
Header A, Child 123,111
Header B, child 456,444
Header C, child 789,777
The result I expect is:
expListChild.put(A, 123,111); //(actual result: expListChild.put(A, 123,111,456,444,789,777)
expListChild.put(B, 456,444); //(actual result: expListChild.put(B, 123,111,456,444,789,777)
expListChild.put(C, 789,777); //(actual result: expListChild.put(C, 123,111,456,444,789,777)
I don't know how to do, I've been thought of use temp1, temp2, but I don't know how many rows in Cursor cHeader .
Could you help me please? Thanks.
I guess the problem is I don't know how to create a series of variables.
List<String> expListHeader = new ArrayList<>();
HashMap<String, List<String>> expListChild = new HashMap<>();
List<String> temp = new ArrayList<>();
void xxx() {
Cursor cHeader = db.rawQuery("XXX", null);
cHeader.moveToFirst();
while (cHeader.moveToNext())
{
String headerStr = cHeader.getString(0);
expListHeader.add(headerStr);
Cursor cChild = db.rawQuery("XXX", null);
cChild.moveToFirst();
while (cChild.moveToNext()) {
String childStr = cChild.getString(0);
temp.add(childStr);
}
cChild.close();
expListChild.put(headerStr, temp);
}
}
Put temp.clear() before Cursor cChild = db.rawQuery("XXX", null); to release all objects in your temp list.
Updated (since I was stupid)
List expListHeader = new ArrayList<>();
HashMap> expListChild = new HashMap<>();
void xxx() {
Cursor cHeader = db.rawQuery("XXX", null);
cHeader.moveToFirst();
while (cHeader.moveToNext()) {
String headerStr = cHeader.getString(0);
expListHeader.add(headerStr);
List<String> temp = new ArrayList<>();
Cursor cChild = db.rawQuery("XXX", null);
cChild.moveToFirst();
while (cChild.moveToNext()) {
String childStr = cChild.getString(0);
temp.add(childStr);
}
cChild.close();
expListChild.put(headerStr, temp);
}
}
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(...)
I want to create a quiz app which contains 1 question and 4options for that I created a database from which the questions and options are fetched to 5 textviews using ListView. I surfed many tutorials and using a page from stackoverflow created it using ArrayList and Cursor but i am getting a
error.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.shark.shopapp.merge.getData(merge.java:26)
at com.example.shark.shopapp.MainActivity.onCreate(MainActivity.java:68)
It is showing in a Cursor.query() line. MainActivity:
setContentView(R.layout.ques_layout); db=openOrCreateDatabase("check1.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.execSQL("CREATE TABLE que(ques TEXT,optn1 TEXT,optn2 TEXT,optn3 TEXT,optn4 TEXT)");
ListView l1=(ListView)findViewById(R.id.listView2);
merge mer=new merge(this);
ArrayList<String> data=mer.getData();
l1.setAdapter(new ArrayAdapter<String>(this,R.layout.ques_layout,data));
db.close();
Merge.java:
public merge(Context c){ourContext=c;}
public ArrayList<String> getData() {
String[] columns = new String[]{ques, optn1, optn2, optn3, optn4};
Cursor c2=db.query(DATABASE_TABLE,columns,null,null,null,null,null);
ArrayList<String> result = new ArrayList<String>();
int ques = c2.getColumnIndex("_id");
int optn1 = c2.getColumnIndex("optn1");
int optn2 = c2.getColumnIndex("optn2");
int optn3 = c2.getColumnIndex("optn3");
int optn4 = c2.getColumnIndex("optn4");
for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
result.add(c2.getString(ques) + c2.getString(optn1) + c2.getString(optn2) + c2.getString(optn3) + c2.getString(optn4));
}
db.close();
return result;
}
}
try this :
String strQuery="select option from (select option1 as option from table
union all
select option2 as option from table
union all
select option3 as option from table
union all
select option4 as option from table) as result";
Cursor c2 = db.SelectQuery(strQuery);
String[] from ={"option"};//you can add as many as you need.
in[] to to = {"R.id.TextViewID"};//you can add as many as you need.
SimpleCursorAdapter sca = new SimpleCursorAdapter(youractivityname.this,R.layout.listviewlayout,c2,from,to);
yourlistview.setAdapter(sca);
You can do something like this.
_cursor = _database.rawQuery("select * from "+YOUR_TABLE_NAME, null);
_cursor.moveToFirst();
while(_cursor.isAfterLast() == false){
_idDB = _cursor.getInt(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_ID));
_ivrsDB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_IVRS_NUM));
_readingDB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_METER_READING));
_imageDB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_IMAGE));
_userIdDB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_USER_ID));
_latDB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_LAT));
_longDB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_LONG));
_dateDB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_DATE_TIME));
_mob1DB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_MOB_FIRST));
_mob2DB = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_MOB_SECOND));
_reasonSelected = _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_REASON));
//need to call UPDATE WS
updateDataFromDB(context, _idDB , _ivrsDB , _readingDB, _imageDB, _userIdDB , _latDB , _longDB, _dateDB , _mob1DB , _mob2DB
,_reasonSelected);
System.out.println("Id from DB=" + _idDB);
System.out.println("IVRS NUMBER="+ _ivrsDB);
System.out.println("Reading="+ _readingDB);
//System.out.println("Image Path="+_cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_IMAGE)));
System.out.println("USer ID="+_userIdDB);
System.out.println("LAT="+_latDB);
System.out.println("LONG="+_longDB);
System.out.println("DATE="+ _dateDB);
System.out.println("MOb 1="+_mob1DB);
System.out.println("Mob 2="+_mob2DB);
System.out.println("Reason from db =" + _reasonSelected);
_cursor.moveToNext();
}
_cursor.close();
Your db variable is not initialized in merge.
Assuming you're using SQLiteOpenHelper, call e.g. getWritableDatabase() on the helper object to get an SQLiteDatabase object you can assign to db.
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());
}