Android - How can I put database rows into a ListView? - android

I am trying to view the content of my database by listing it in a ListView. What am i doing wrong? The goal is to load a list of the database data when the page loads after a button click on the homepage.
The XML page simply has a ListView, named "studentList", inside a ScrollView
Java code:
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
This is openReadable() Function:
public dbasemanager openReadable() throws android.database.SQLException {
helper = new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
}
This is the retrieveRows() Function:
public ArrayList<String> retrieveRows() {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"sid", "first_name", "last_name"};
Cursor cursor = db.query(Table_Name, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
studentRows.add(cursor.getString(0) + ", " + cursor.getString(1)
+ ", " + cursor.getString(2));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}
Logcat:

There is a null pointer in line 17.
You need to construct databasemanager object before call it
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
// construct databasemanager
dBase = new dbasemanager(...);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
BTW, I recommend you to use java code conventions to name classes.
For example: edit_student should be editStudent and dbasemanager should be DBManager or DbManager.

Related

Show all database contents in a ListView

I want to Show all database contents in a List View in Android Studio, I expect to see 3 rows that each row contains "name, family and ID" , but I see a comlex of package name and some other characters as follws:
com.google.www.hmdbtest01.Person#529e71b4
com.google.www.hmdbtest01.Person#529e7238
com.google.www.hmdbtest01.Person#529e7298
if I have more rows in my database, I will see more lines like above in the output.
my codes are as follow:
public class ListOfData extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_data);
ListView list = findViewById(R.id.list1);
HmDbManager01 db= new HmDbManager01(this);
ArrayList personList = db.getAll();
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, personList);
list.setAdapter(arrayList);
}
}
db.getAll() is as follows:
public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Person p1 = new Person();
p1.pID=cursor.getString(0);
p1.pName=cursor.getString(1);
p1.pFamily=cursor.getString(2);
allData.add(p1);
cursor.moveToNext();
}
}
cursor.close();
sqLiteDatabase.close();
return allData;
}
and, this is Person:
package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}
Let me know your comments on this problem.
arrayListAdapter will convert your personList to list of string
change like it:
ArrayList<String> persons = new ArrayList<String>();
personList.forEach(personModel -> {
persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
});
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, persons);

display data from sqlite according to value

i need your help, i did display data in a list view but the problem is that i
want the data to be according to a specific value, that means if the id = 1, only the rows
concerned will be displayed, if you have any suggestions i would be very thankful :
here the code of :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
String[] databaseColumnNames = new String[] { DBAdapter.col_region, };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
And my DBAdapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id, col_region,
}, null, null, null,
null, null);
}
list.setAdapter(myCursordapter);
} }
As you may check in query documentation, function accepts a selection and selectionArgs parameters, corresponding to SQL WHERE clause.
So, to make a query limited to a specific id, just use:
db.query(MENAGE, new String[] { _id, col_region}, "id = ?", new String[] {_id}, null, null, null);

display data from sqlite

i have a problem in showing data coming from database sqlite, i looked for a solution
here i did found plenty but i couldn't make it work, the error i get is : Error occured:
java.lang.IllegalArgumentException: column '_id' does not exist !!
my code is :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
private ArrayList<String> arr;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
Button suivant = (Button)findViewById(R.id.com_quest);
suivant.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent l = new Intent(MainActivity.this,ActivityUn.class);
startActivity(l);
}
});
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
Log.i("MyApp", "Total users: " + cursor.getCount());
Toast.makeText(getApplicationContext(),
"Number of rows: " + cursor.getCount(), Toast.LENGTH_LONG)
.show();
String[] databaseColumnNames = new String[] { DBAdapter._id };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(myCursordapter);
} }
and in dbadapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id
}, null, null, null,
null, null);
}
All CursorAdapters require that the Cursor includes a column called _id. Your Cursor contains just one column called Num_du_Questionnaire.

ListView updates only when activity restarts - Android

Hi i have provided my code below. I have one Main UI thread and one manual thread. I am updating the listView inside the thread and using it in an adapter and list view to populate. But the problem is once the activity starts the list is empty and only when the configuration changed it gets updated with the adapter. whats the problem in it? My thread is starting only after the oncreate is complete? Kindly leave the cursor part as I am getting all the values very well. Kindly help me friends.
public class MediaActivity extends Activity {
private static final String TAG = null;
ExpandableListView expList ;
ExpandableListAdapter expListAdapter;
static ArrayAdapter<String> ap;
static List<String> albumHead = new ArrayList<String>();
static HashMap<String, List<String>> albumChild = new HashMap<String, List<String>>();
static Cursor albumCursor;
AlbumThread albumThread;
#Override
protected void onStart() {
super.onStart();
albumThread = new AlbumThread();
albumThread.start();
Log.d(TAG , "albumThread Started");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media);
ListView expList = (ListView)findViewById(R.id.mediaList);
ap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, albumHead);
if(!albumHead.isEmpty()){
expList.setAdapter(ap);
} else {
Toast makeToast = Toast.makeText(getApplicationContext(), "albumHead is empty" , Toast.LENGTH_LONG);
makeToast.show();
}
}
private static class AlbumThread extends Thread{
Context appContext = MediaApp.getAppContext();
List<String> songList = new ArrayList<String>();
public AlbumThread() {
super("myThread");
}
#Override
public void run() {
// Query Media Contents from MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
super.run();
ContentResolver albumResolver = appContext.getContentResolver();
Uri mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] mediaColumns = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
};
String mediaSort = " " + MediaStore.Audio.Media.ALBUM + " ASC" + "," + MediaStore.Audio.Media.DISPLAY_NAME + " ASC";
albumCursor = albumResolver.query(mediaContentUri, mediaColumns, null, null, mediaSort);
//Extract values from Cursor
if(albumCursor.moveToFirst()){
do{
int albumIdx = albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
int songIdx = albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
String albumString = albumCursor.getString(albumIdx);
String songString = albumCursor.getString(songIdx);
if(!albumHead.contains(albumString)){
albumHead.add(albumString);
ap.notifyDataSetChanged();
}
if(albumHead.contains(albumString)){
songList.add(songString);
albumChild.put(albumString, songList);
}
}while (albumCursor.moveToNext());
}
}
}
#Override
protected void onStop() {
super.onStop();
albumThread = null;
Log.d(TAG, "albumThread stopped yapee");
}
}

Retrieving all of data from sqlite

I will show data which is in sqlite db to spinner. Showing is easy but I can't retrieve the datas that I added to db.Here is my codes;
public class MainActivity extends Activity {
private Spinner spinner;
private SQLiteDBOlustur sqlnesne;
private SQLiteDatabase db;
private ContentValues cv;
private Cursor cursor;
private ArrayList<String> arr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinnerIller);
arr = new ArrayList<String>();
veriEkle();
db = sqlnesne.getReadableDatabase();
cursor = db.rawQuery("select * from iller", null);
if (cursor.moveToFirst()) {
do {
arr.add(cursor.getString(cursor.getColumnIndex("adsoyad")));
} while (cursor.moveToPrevious());
}
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
}
Only I can see the last added data.So how to get all of data in my sqlite db?
Also these are adding data method.
private void veriEkle() {
sqlnesne = new SQLiteDBOlustur(getApplicationContext());
db = sqlnesne.getWritableDatabase();
cv = new ContentValues();
cv.put("il_adi", "Yalova");
cv.put("il_adi", "Karabük");
cv.put("il_adi", "Kilis");
cv.put("il_adi", "Osmaniye");
cv.put("il_adi", "Düzce");
try {
db.insert("iller", null, cv);
Toast.makeText(getApplicationContext(), "Veriler eklendi!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Try replacing cursor.moveToPrevious() with cursor.moveToNext() so that you step forward through the cursor rather than back.
if (cursor != null && cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
arr.add(cursor.getString(cursor.getColumnIndex("adsoyad")));
cursor.moveToNext();
}
}
cursor.close();
Try this way!!
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinnerIller);
arr = new ArrayList<String>();
veriEkle();
String Table_Name="name of table";
String selectQuery = "SELECT * FROM " + Table_Name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
// get the data into array,or class variable
// process your data here.
} while (cursor.moveToNext());
}
}
Hope it will help you.

Categories

Resources