display data from sqlite - android

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.

Related

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

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.

How can I select values from a column in sqlite database which will starts with a particular letter inserted by user

I want the following sql code in sqlite terms:
"SELECT * FROM babynames WHERE name like '$id%'"
I get the following erreor
SQLiteLog: (1) near "like": syntax error
My code:
public class Datalist extends ListActivity{
public String id1;
RegistrationAdapter adapter_ob;
DBhandler helper_ob;
SQLiteDatabase db_ob;
ListView nameList;
Cursor cursor;
public ListView listView;
ArrayList<HashMap<String, String>> list = new ArrayList();
private ArrayList<String> results = new ArrayList<String>();
String tableName = DBhandler.TABLE_NAME;
String n=DBhandler.KEY_NAME;
String m=DBhandler.KEY_MEAN;
private SQLiteDatabase newDB;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.list);
id1 = getIntent().getStringExtra(config.TAG_ID);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
// TODO Auto-generated method stub
//TextView tView = new TextView(this);
//tView.setText("This data is retrieved from the database and only 4 " +
//"of the results are displayed");
//getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
// TODO Auto-generated method stub
try {
DBhandler dbHelper = new DBhandler(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT _name, _mean FROM " +
tableName + "where _name like'" +id1+ "%'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
//Integer id=c.getInt(c.getColumnIndex("_id"));
String Name = c.getString(c.getColumnIndex("_name"));
String mean= c.getString(c.getColumnIndex("_mean"));
/* HashMap<String, String> baby = new HashMap();
//baby.put(config.TAG_ID, id);
baby.put(config.TAG_NAME, Name);
baby.put(config.TAG_MEAN1, mean);
list.add(baby);*/
results.add("" + Name + ""
+ "" + mean);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
//listView.setAdapter(new SpecialAdapter(this, list, R.layout.list_item, new String[]{config.TAG_NAME, config.TAG_MEAN1}, new int[]{R.id.name, R.id.mean1}));
}
//listView.setAdapter(new SpecialAdapter(this, list, R.layout.list_item, new String[]{config.TAG_NAME, config.TAG_MEAN1}, new int[]{R.id.name, R.id.mean1}));
}
}
Anybody please help me.Thanks in advance..
Try this...
public Cursor getBabyName(String query) {
return db.query(DbHelper.NAME_TABLE, NAME_FIELDS,
DbHelper.BABY_NAME+ " like '" + query + "%'", null,
null, null, null, null);
}

delete row of listview and sqlite

my following codes show the data of sqlite in listview. now i want to write long click to delete row in listview and sqlite. please help me. how can i do that?
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
R.layout.cartformat,results));
getListView().setTextFilterEnabled(true); }
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " + title + ", Quantity: " + qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}}}
The best way would be to develop a custom adapter. But if you don't want, this should work :
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList(){
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
String currentString = results.get(position);
String resultRegexString = "Title\\: ([^,]+), Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(resultRegexString);
if(resultRegexMatcher){
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3));
database.delete("CART", whereClause, null);
}
}
results.remove(position);
displayResultList();
});
}

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

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