Retrieving all of data from sqlite - android

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.

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.

fetch data from a dbHandler.java file but not able to show it in listview?

I did some changes in my code and it runs but I didn't get appropriate output. I create a method.
public void fetchData() {
dbHandler = new CourseDbHandler(this,null,null,1);
List<CreateCourse> course_data = dbHandler.getdata();
String[] data = new String[course_data.size()];
int i=0;
for(CreateCourse co : course_data)
{
data[i] = co.getCourseSelected();
i++;
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
in this method i used dbHandler.getdata method, which is as follows
public List<CreateCourse> getdata() throws NullPointerException {
String dbString = "";
String course;
String sec;
List<CreateCourse> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
course = c.getString(1);
sec = c.getString(2);
dbString = course+" "+sec;
CreateCourse co = new CreateCourse();
co.setCourseSelected(dbString);
list.add(new CreateCourse(c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
These are the getter and setter method
public void setCourseSelected(String courSelected) {
courseSelected = courSelected;
}
public String getCourseSelected() {
System.out.println(courseSelected);
return courseSelected;
}
It gives an error unfortunately app has stopped.
Create a class with your data:
public class Course {
public String id;
public String course;
public String sec;
public Course (String id, String course, String sec) {
this.id = id;
this.course = course;
this.sec = sec;
}
Then modify your method to return List of your data:
public List<Course> getdata() throws NullPointerException {
List<Course> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
list.add(new Course(c.getString(0), c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
Then you can use this List with ArrayAdapter to show your data in ListView.
I changed all the code and solve my problem in above code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_course);
dbHandler = new CourseDbHandler(this, null, null, 1);
Cursor c = dbHandler.getData();
c.moveToFirst();
// System.out.println("Select");
if(c.equals(null)){
System.out.println("NO DATA");
}
else {
if(c.moveToFirst()) {
do {
dbString=null;
course = c.getString(1);
sec = c.getString(2);
dbString = course + " " + sec;
courseItem.add(dbString);
} while (c.moveToNext());
}
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, courseItem);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
Thank you for your help..

Listview from DB

I'm trying to get some data from a DB and display in a listview, but they logcat say Make sure the Cursor is initialized correctly before accessing data from it. This is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cotizacionescolumna);
lvCotizacion = (ListView)findViewById(R.id.lista_cotizaciones);
list_cotizaciones = new ArrayList<String>();
llenarLista();
eventos();
}
public void llenarLista(){
CotiCadSqlite db = new CotiCadSqlite(CotizacionesColumnnaActivity.this);
Cursor c = db.obtenerNombresColumna();
if(c.moveToFirst()){
do{
columna = c.getString(1);
list_cotizaciones.add(columna);
}while (c.moveToNext());
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_cotizaciones);
lvCotizacion.setAdapter(adapter);
}
columna = c.getString(1);
to
c.getString(c.getColumnIndex(1))
as well
if (null != c) {
if (c.moveToFirst()) {
do {
//your code goes here
} while (c.moveToNext());
}
c.close();
try like this,
Cursor c = helper.DatabaseMethod();// retrive data
c.moveToFirst();
while (c.isAfterLast() == false)
{
String dataSaved = c.getString(c.getColumnIndex(DataBaseHelper.KEY_EMAIL));//your column index name
list_cotizaciones.add(dataSaved );
c.moveToNext();
}
c.close();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_cotizaciones);
lvCotizacion.setAdapter(adapter);

Return String[] From database

I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}

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.

Categories

Resources