display data from sqlite according to value - android

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);

Related

How to fetch data for a specific category in listview?

My MainActivity have a listview with some categories,If I click a particular category in my listview,it's need to redirect to another activity,which need to have the details of that particular category.
Eg: IF I select FOOD in Mainactivity,I want to redirect to another activity where the activity want to have the budget amount of food.
public class addbudget extends ActionBarActivity implements View.OnClickListener{
SimpleCursorAdapter adapter;
DBhelper helper;
SQLiteDatabase db;
EditText txtBudget;
TextView txr;
ListView rldlist,list;
Button btn66;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addbudget);
btn66=(Button)findViewById(R.id.btn_addBudget);
btn66.setOnClickListener(this);
helper=new DBhelper(addbudget.this);
txr=(TextView)findViewById(R.id.addbud);
txtBudget=(EditText)findViewById(R.id.etBudget);
rldlist = (ListView) findViewById(R.id.rldlist);
list = (ListView) findViewById(R.id.list);
Bundle data_from_list= getIntent().getExtras();
String value_in_tv= data_from_list.getString("passed data key");
txr.setText(value_in_tv);
fetchData2();
}
private void clearfield(){
txtBudget.setText("");
}
public void onClick(View v) {
if (btn66 == v) {
ContentValues value = new ContentValues();
value.put(DBhelper.Amount, txtBudget.getText().toString());
value.put(DBhelper.Description,txr.getText().toString());
if (txtBudget.length() == 0) {
txtBudget.requestFocus();
txtBudget.setError("Field Cannot Be Empty");
} else {
db = helper.getWritableDatabase();
db.insert(DBhelper.TABLE2, null, value);
db.close();
clearfield();
Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show();
fetchData2();
}
}
}
private void fetchData2() {
db = helper.getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE2, null, null, null, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}
}
This is how ,I'm fetching data to a listview from database.Here I'm fetching Amount from database.
How can I change the fetchdata method to get the BudgetAmount of a specific category ?(I'm using bundle to get the name of the category from the listview of MainActivity)
You can use sql syntax:
String sql = "select * from DBhelper.TABLE2 where category_name_column = " + category";
Cursor c = db.rawQuery(sql.toString(), null);
Or if you want to use params:
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {
"category_name"
};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
So your method can be as such:
private void fetchData2(String category) {
db = helper.getReadableDatabase();
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {"category"};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}

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.

update the listview after inserting a new record with simpleCursorAdapter - requery()

I understand the requery() mechanic, but i do not understand the implementation:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getAllCategorie();
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_NOME // Contract class constant containing the word column name
};
int[] mWordListItems = { R.id.categoria_label };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
}
public void onClick(View view) {
categorie categoria = null;
switch (view.getId()) {
case R.id.add:
categoria = datasource.createCategoria("pluto") ;
break;
case R.id.categoria_label:
break;
}
}
after the categoria = datasource.createCategoria("pluto"); i have to define another:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
PollDataSource:
public class pollDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };
private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_CATID, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID, MySQLiteHelper.COLUMN_RISPOSTA,
MySQLiteHelper.COLUMN_SELEZIONATA };
public pollDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
public void deleteCategoria(categorie categoria) {
long id = categoria.getId();
System.out.println("Categoria cancellata, id: " + id);
database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public sondaggi createSondaggio(String domanda, int catid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
sondaggi newSondaggio = cursorToSondaggi(cursor);
cursor.close();
return newSondaggio;
}
public void deleteSondaggio(sondaggi sondaggio) {
long id = sondaggio.getId();
System.out.println("Sondaggio cancellato, id: " + id);
database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public Cursor getAllCategorie() {
List<categorie> categorie = new ArrayList<categorie>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
categorie categoria = cursorToCategorie(cursor);
categorie.add(categoria);
cursor.moveToNext();
}
// Make sure to close the cursor
// cursor.close();
return cursor;
}
private categorie cursorToCategorie(Cursor cursor) {
categorie categorie = new categorie();
categorie.setId(cursor.getLong(0));
categorie.setPreferita(cursor.getLong(1));
categorie.setNome(cursor.getString(2));
return categorie;
}
private sondaggi cursorToSondaggi(Cursor cursor) {
sondaggi sondaggi = new sondaggi();
sondaggi.setId(cursor.getLong(0));
sondaggi.setDomanda(cursor.getString(1));
sondaggi.setCatid(cursor.getLong(2));
return sondaggi;
}
}
with the same inputs?? so basically I will have the same exact code in two different places of the same class... May I define a... "procedure" or a class? I'm sorry if I'm too naive, I'm a real noob at this :D
the requery cursor method is deprecated. but you're right you have to reload the cursor and then make sure that your new cursor is being presented to your ListView. for a quick 'n dirty solution, I suggest you make your adapter a field. and then use the following method:
private void requery() {
Cursor values = datasource.getAllCategorie();
adapter.changeCursor(values);
}
What it does is remake a cursor. then by calling changeCursor you swap the old cursor for the new one and the old one is closed automatically. at the very least, you save yourself from making a new adapter. The more sophicated approach with all the trim and fixes i suppose would be to implement a CursorLoader which would perform the process automatically when the database content has been changed.

ListView with CursorLoader and SimpleCursorAdapter isn't displaying data

I'm trying to populate a ListView with data from a query using a CursorLoader. I'm new to CursorLoaders and I'm using code I purloined from Beginning Android 4 Application Development. As you can see, I'm getting data from an Intent. The data in the Intent is what I want; I've verified that in the debugger. However, when I query my database, nothing displays in the ListView. Can anyone help?
public class MyList extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TABLE_BASEPATH = "tbl";
private static final String AUTHORITY = "SQLData";
public static final Uri MY_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_BASEPATH);
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent myData = getIntent();
Bundle info = myData.getExtras();
if (info != null){
Cursor c;
String[] dataColumns = { "mycolumn" };
String selection = "level = '" + info.getString("Level") + "'";
if (android.os.Build.VERSION.SDK_INT < 11)
c = managedQuery(MY_URI, dataColumns, selection, null, "ORDER BY mycolumn");
else
{
CursorLoader cursorloader = new CursorLoader(this, MY_URI, dataColumns, selection, null, "ORDER BY mycolumn");
c = cursorloader.loadInBackground();
}
int[] viewIDs = { R.id.mylist1 };
SimpleCursorAdapter adapter;
if (android.os.Build.VERSION.SDK_INT < 11)
adapter = new SimpleCursorAdapter(this, R.layout.mylist, c, dataColumns, viewIDs);
else
adapter = new SimpleCursorAdapter(this, R.layout.mylist, c, dataColumns, viewIDs, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
this.setListAdapter(adapter);
}
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, MY_URI,
PROJECTION, null, null, null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
switch (loader.getId()) {
case LOADER_ID:
mAdapter.swapCursor(cursor);
break;
}
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
It doesn't matter if I'm using the cursor or the CursorLoader. If my version is < 11 (cursor), I get no data; if it's > 11 (CursorLoader) I still get no data.
You need to put in the id column in the projection when working with ContentProviders, otherwise they "won't work". Which I think you are doing > api level 11...
String[] dataColumns = { "mycolumn" };
The above code should include the id field. If the id field is "_id" (like Sams answer):
String[] dataColumns = { "mycolumn", "_id" };

Null Pointer Exception while Retriving Data from Sqlite

I am retrieving data from sqlite to base adapter by cursor.
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
String[] v0 = new String[] { tes0 };
String[] v01 = new String[] { tes1 };
String[] v02 = new String[] { tes2 };
String[] v03 = new String[] { tes3 };
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}
Then, Adapter_listView.java
public class Adapter_ListView extends BaseAdapter {
private int count;
private Context context;
private String[] string1;
private String[] string2;
private String[] string3;
private String con1;
private String con2;
private String con3;
public Adapter_ListView(Context baseContext, String[] v01, String[] v02, String[] v03, int theTotal) {
this.count = theTotal;
this.context = baseContext;
this.string1 = v01;
this.string2 = v02;
this.string3 = v03;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup arg2) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
contentView = inflater.inflate(R.layout.layout_inflate_list2, null);
TextView title = (TextView)contentView.findViewById(R.id.inflate_title);
TextView body = (TextView)contentView.findViewById(R.id.inflate_body);
TextView sub = (TextView)contentView.findViewById(R.id.inflate_sub);
title.setText(string1[position]);
body.setText(string2[position]);
sub.setText(string3[position]);
return contentView;
}
}
from this code always error --> ArrayOuOfBound if execute this code
title.setText(string1[position]);
how i can solve it?
You need to open your database in the activity you retrieve or insert data into your SQLite database. Also make sure you close it when your finished.
final DatabaseHelper m = new DatabaseHelper(this);
m.open();
In your onDestroy or pause. Call
m.close();
This may be the issue, because i dont see where you open your database in the code.
EDIT :
In your DatabaseHelper class. Create a method.
public void open(){
db.open();
}
public void close(){
db.close()
}
Then you will have the method to close and open the database in your activities where you need to insert and retrieve information.
To retrive data from cursor, first you must go to first row data in cursor.
Some code like this:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
...
}
good luck!! :D
It seems you want to load resultset into list, if so please change your code to set adapter outside of loop:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
int theTotal=c.getCount();
String[] v0 = new String[theTotal];
String[] v01 = new String[theTotal];
String[] v02 = new String[theTotal];
String[] v03 = new String[theTotal];
int i=0;
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i] =tes0 ;
v01[i] = tes1 ;
v02[i] = tes2 ;
v03[i] = tes3 ;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
Try this:
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if(c.getCount()>0)
{
int i=0;
int clength=c.getCount();
String[] v0=new String[clength];
String[] v1=new String[clength];
String[] v2=new String[clength];
String[] v3=new String[clength];
while (c.moveToNext())
{
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i]=tes0;
v01[i]=tes1;
v01[i]=tes2;
v01[i]=tes3;
i++;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}

Categories

Resources