how to showing data to arraylist based on column value - java

I want to show data based on column values, is that possible?
My adapter
public Cursor getDisease() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_GEJALA, new String[]{
KEY_ID,
KEY_GEJALA,
KEY_PENYAKIT,
KEY_AREA,
KEY_KODE_PENYAKIT
},
null,
null,
null,
null,
KEY_GEJALA,
null);
}
My activity then
private void loadListView(View view) {
ListView listView = view.findViewById(R.id.list_view);
arrayList = new ArrayList<>();
Cursor c = sqliteHelper.getDisease();
if (c.moveToFirst()) {
do {
arrayList.add(c.getString(1));
} while (c.moveToNext());
}
adapter = new ListViewAdapter(getActivity(), arrayList, true);
listView.setAdapter(adapter);
}
I am expecting to show code based on category

Related

How to to insert and retrieve data in SQLite?

I have written an app where i have to insert its data into sqlite database and show it on one activity. But my code is showing "No record Found" even if i have inserted it.
I have tried using different options like moving cursor first to the first record and then using loop iterate over the record.
Inserting data into database
private void saveToDB() {
SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ChildMonitoringAppDBHelper.CHILD_NAME, name.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_AGE, age.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_DOB, dob.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_HEIGHT, height.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_WEIGHT, weight.getText().toString());
database.insert(ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null, values);
database.close();
}
Retrieving data from database
public ArrayList<Child> readFromDB()
{
ArrayList<Child> List = new ArrayList<>();
SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getReadableDatabase();
Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), cursor.getString(cursor.getColumnIndex("CHILD_AGE")), cursor.getString(cursor.getColumnIndex("CHILD_DOB")), cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
List.add(child);
cursor.moveToNext();
}
cursor.close();
return List;
}
It should display the record entered but it is making the toast "No Record found".
Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
if (cursor.moveToFirst())
{
do {
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), cursor.getString(cursor.getColumnIndex("CHILD_AGE")), cursor.getString(cursor.getColumnIndex("CHILD_DOB")), cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
List.add(child);
} while (cursor.moveToNext());
}
cursor.close();
return List;
Can you try this code and see it if it works for you?
public ArrayList<Child> readFromDB()
{
List list = new ArrayList<Child>();
Cursor cursor = database.rawQuery("select * from " +
ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
{
do
{
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")),
cursor.getString(cursor.getColumnIndex("CHILD_AGE")),
cursor.getString(cursor.getColumnIndex("CHILD_DOB")),
cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")),
cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
list.add(child);
}
while (cursor.moveToNext());
}
cursor.close();
// return list of inserted values
return list;
}

SimpleCursorAdapter showing all rows even when specifying cursor in constructor

Cursor cursor = coursesOpenHelper.getCoursesByTerm(db, TERM);
adapter = new SimpleCursorAdapter(getBaseContext(),
android.R.layout.simple_list_item_1,
cursor,
new String[]
{
"course",
},
new int[]
{
android.R.id.text1,
},
0);
// test the cursor to see that it has the correct number of records
int x = cursor.getCount();
Toast.makeText(this, x+"", Toast.LENGTH_LONG).show();
listView.setAdapter(adapter);
Here is the getCoursesByTerm method:
public Cursor getCoursesByTerm(final SQLiteDatabase db, int term){
final Cursor cursor;
cursor = db.query(COURSE_TABLE_NAME,
null,
"term = "+term,
null,
null,
null,
null,
null);
cursor.setNotificationUri(context.getContentResolver(), CourseContentProvider.CONTENT_URI);
return (cursor);
}
I know that this method is returning the correct Cursor with the correct number of rows, but the ListView is showing all of the rows. Let me know if you need to see any of my other code. Thanks!
EDIT: I've discovered my problem... this is a subclass of all my TermActivity classes. Commenting out the one line of code solves my problem, but I'm sure this is a very incorrect way of doing it.
private class CourseLoaderCallbacks implements LoaderCallbacks<Cursor>
{
#Override
public Loader<Cursor> onCreateLoader(final int id,
final Bundle args)
{
Log.v(TAG, "onCreateLoader");
final Uri uri;
final CursorLoader loader;
uri = CourseContentProvider.CONTENT_URI;
loader = new CursorLoader(Term1Activity.this, uri, null, null, null, null);
return (loader);
}
#Override
public void onLoadFinished(final Loader<Cursor> loader,
final Cursor data)
{
//adapter.swapCursor(data); // was swapping cursor for null, resulting in all courses showing
}
#Override
public void onLoaderReset(final Loader<Cursor> loader)
{
adapter.swapCursor(null);
}
}

Display db items in listview android studio

i am making app with db and i have created db and all things but i cant recive db column items to display it in listview?
here is my dbadapret.java code for displaying only one column from db
public Cursor listallbarcodes() {
Cursor mCursor = db.query(DATABASE_TABLE, new String[] {KEY_CONTAINERBARCODE},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
and here is the code in myactivity for loading this items in list view
private void displayListView() {
Cursor cursor = myDb.listallbarcodes();
String[] columns = new String[]{
DBAdapter.KEY_CONTAINERBARCODE
};
int[] to = new int[]{
R.id.product_name,
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.mylist, cursor, columns, to, 0);
ListView listView_ladung = (ListView) findViewById(R.id.listview_ladung);
// Assign adapter to ListView
listView_ladung.setAdapter(dataAdapter);
}
what do i wrong?
Thanks

Android cannot resolve constructor ArrayAdapter

I am aware that this question has been asked multiple times before but none of the solutions have worked for me. This is my code:
public class reminderDAO extends dbManager{
public reminderDAO(Context context) {
super(context);
}
// Adding new reminder
public void addReminder(Reminder reminder) {
//dbm.gettingWritable(values);
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(getKEY_DATE(), reminder.getReminderDate());
values.put(getKEY_TITLE(), reminder.getReminderTitle());
values.put(getKEY_DESC(), reminder.getReminderDescription());
values.put(getKEY_TIME(), reminder.getReminderTime());
// Inserting Row
db.insert(getDATABASE_TABLE(), null, values);
db.close(); // Closing database connection
}
public List<Reminder> getAllReminders(ListView lv) {
ArrayList<Reminder> reminderList = new ArrayList<Reminder>();
// Select All Query
String selectQuery = "SELECT * FROM " + getDATABASE_TABLE();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
MainActivity ma = new MainActivity();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Reminder r = new Reminder();
r.setReminderDate(cursor.getString(0));
r.setReminderTitle(cursor.getString(1));
r.setReminderDescription(cursor.getString(2));
r.setReminderTime(cursor.getString(3));
// Adding reminder to list
reminderList.add(r);
} while (cursor.moveToNext());
}
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this,
android.R.layout.simple_list_item_1,
reminderList );
lv.setAdapter(arrayAdapter);
// return reminder list
return reminderList;
}
}
I've got a feeling it is to do with 'this' inside the arrayAdapter. I have tried getActivity(), this.getActivity(), reminderDAO.this.getActivity(), MainActivity.this and reminderDAO.this.
Anyone have a solution?
Create a Context variable in your class. and assign it from the constructor parameter.
private Context context;
public reminderDAO(Context context) {
this.context = context;
super(context);
}
Then use this variable to pass to the ArrayAdapter
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this.context,
android.R.layout.simple_list_item_1,
reminderList );

Display data from SQLite database into ListView in Android

Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.
Here's my code getClientNames in DatabaseHelper class:
public Cursor getSitesByClientname(String id) {
String[] args={id};
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
String results = "";
/*int count = myCursor.getCount();
String[] results = new String[count + 1];
int i = 0;*/
if (myCursor != null) {
if(myCursor.getCount() > 0)
{
for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
{
results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename"));
}
}
}
return results;
}
One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.
Here's the ClientSites class where I want to display the data:
public class ClientSites extends Activity {
//public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
private Cursor ourCursor = null;
private Adapter adapter=null;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
//dbHelper.createDatabase();
dbHelper.openDataBase();
ourCursor = dbHelper.getSitesByClientname(uID);
Log.e("ALERT", uID.toString());
startManagingCursor(ourCursor);
Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
{
Intent i=new Intent(ClientSites.this, InspectionPoints.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class Adapter extends CursorAdapter {
#SuppressWarnings("deprecation")
Adapter(Cursor c) {
super(ClientSites.this, c);
}
//#Override
public void bindView(View row, Context ctxt,
Cursor c) {
Holder holder=(Holder)row.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Holder holder=new Holder(row);
row.setTag(holder);
return(row);
}
}
static class Holder {
private TextView name=null;
Holder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, DBUserAdapter r) {
name.setText(r.getName(c));
}
}
}
Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
dbHelper.openDataBase();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//ourCursor = dbHelper.getSitesByClientname(uID);
//Log.e("ALERT", uID.toString());
//startManagingCursor(ourCursor);
//Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!!
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
I Created a Listview from a database. Here is the code I used for my app
Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.
public List<Category> getAllCategorys() {
ArrayList<Category> categoryList = new ArrayList<Category>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
try{
if (cursor.moveToFirst()) {
do {
Category category = new Category();
category.setID(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
// Adding category to list
categoryList.add(category);
} while (cursor.moveToNext());
}
}finally{
cursor.close();
}
db.close();
// return category list
return categoryList;
Here is how I fill the ListView by calling the database.
int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();
category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{
category_data[i] = cn.getCategory(); // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);
EDIT: Here is something that should work for you
public List<String> getSitesByClientname(String id) {
String[] args={id};
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
try{
if (myCursor.moveToFirst()){
do{
result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
}while(myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
return result;
}
Use it like this
List<String> sites_data = dbHelper.getSitesByClientname(uID);
result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{
result_data[i] = s; // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);
If you want to return the Cursor from dbHelper you can do something like this...
public Cursor getSitesByClientname(String id) {
String[] args={id};
return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}
I'd also take some time to read the listview tutorial

Categories

Resources