Please check what problem with this .I am trying to retrive all records in my table (contains 11 records with 3 columns "name","address","city") but my code showing only one i.e last inserted record on my screen. but i need to display all records.
public void readData(View v)
{
DatabaseClass mydb = new DatabaseClass(this);
SQLiteDatabase readdata = mydb.getReadableDatabase();
TextView tv = (TextView)findViewById(R.id.readtext);
Cursor c = readdata.rawQuery("select * from mylistdata", null);
int[] elementId = {R.id.textView1, R.id.textView2, R.id.textView3};
if(c !=null)
{
c.moveToFirst();
while(c.isAfterLast() == false)
{
listData = new ArrayList<GenericListItem>();
String name = c.getString(c.getColumnIndex(DatabaseClass.NAME));
String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS));
String city = c.getString(c.getColumnIndex(DatabaseClass.CITY));
listData.add(new GenericListItem(new String[]{name,address,city}));
listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId);
result.setAdapter(listAdapter);
c.moveToNext();
}
}
Initialize listData ArrayList outside from While loop as:
c.moveToFirst();
listData = new ArrayList<GenericListItem>();
while(c.isAfterLast() == false)
{
// add value here to listData
c.moveToNext();
}
// set listData datasource to GenericListAdapter here
listAdapter = new GenericListAdapter(getApplicationContext(),
R.layout.list_layout, listData, elementId);
result.setAdapter(listAdapter);
It looks like the problem is that you are re-creating your list each time through the loop. Try this:
listData = new ArrayList<GenericListItem>(); //moved out of loop
while(c.isAfterLast() == false)
{
String name = c.getString(c.getColumnIndex(DatabaseClass.NAME));
String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS));
String city = c.getString(c.getColumnIndex(DatabaseClass.CITY));
listData.add(new GenericListItem(new String[]{name,address,city}));
listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId);
c.moveToNext();
}
result.setAdapter(listAdapter); // moved out of loop
Related
I have a little issue that I don't know how to address.
I have a Cursor that gets data from my data base it looks like this:
public Cursor getAllData(){
int id;
SQLiteDatabase DB = this.getWritableDatabase();
String dateTime = Helper.getCurrentDate();
String date = dateTime.substring(0, 10);
String date_to_look = date.substring(0, 10);
String sql = "SELECT h.product_id, h.qty, h.date_time, p.product " +
" FROM product_history h " +
" LEFT JOIN products p ON (p.rowid = h.product_id) ";
Cursor res = DB.rawQuery(sql, null);
return res;
}
Then on my activity I'm using the following method:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
String productname = cursordata.getString(cursordata.getColumnIndex("product"));
String [] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
}
Execute it with onclick:
public void shine(View v){
Button shine = (Button)findViewById(R.id.shine);
populateListView();
}
What am I doing wrong?
Edit:
Shows last row from the table only.
public void populateListView() {
Cursor cursordata = myDb.getAllData();
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
String [] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
} while (cursordata.moveToNext());
}
Sahil here is the updated version of your suggestion which i use, it's not working:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
List<String> li_records=new ArrayList<String>;
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
String[] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView) findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
li_records.add(productname);
} while (cursordata.moveToNext());
}
String[] products=li_records.toArray();
}
try this it will work fine:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
ArrayList<String> products = new ArrayList<>();
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
products.add(productname);
} while (cursordata.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
}
Try to put
cursordata.moveToFirst()
after
List<String> li_records=new ArrayList<String>;
Cursor cursordata = myDb.getAllData();
use do while loop like this,
// looping through all rows and adding to list
if (cursordata.moveToFirst()) {
do {
String productname = c.getString((c.getColumnIndex("product")));
li_records.add(productname);
} while (cursordata.moveToNext());
}
String[] products=li_records.toArray();
use this array in your adapter
I need to get all of records from TABLE_NOTES, Here is my method for calling all of records:
public List<NotesFragmentCreate> getAllNotes() {
List<NotesFragmentCreate> notes = new ArrayList<NotesFragmentCreate>();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
NotesFragmentCreate n = new NotesFragmentCreate();
n.setId(c.getInt(c.getColumnIndex(KEY_ID_NOTES)));
n.setTitle(c.getString(c.getColumnIndex(KEY_TITLE)));
n.setCreated(c.getString(c.getColumnIndex(KEY_CREATED)));
n.setContent(c.getString(c.getColumnIndex(KEY_CONTENT)));
// adding to note list
notes.add(n);
} while (c.moveToNext());
}
return notes;
}
Then I create arrays in other class:
String[] title,created,content;
db = new DatabaseHelper(getActivity());
List<NotesFragmentCreate> allNotes = db.getAllNotes();
for (NotesFragmentCreate note : allNotes) {
//how can I get each of record to store in this array?
title[?] = note.getTitle();
created[?] = note.getCreated();
content[?] = note.getContent();
}
Because I want to impement those arrays in a listView
adapter = new ListNotesAdapter(getActivity(), title, created);
Its simple do as have variable inside loop shown as below.
Replace
String[] title,created,content;
List<NotesFragmentCreate> allNotes = db.getAllNotes();
for (NotesFragmentCreate note : allNotes) {
//how can I get each of record to store in this array?
title[?] = note.getTitle();
created[?] = note.getCreated();
content[?] = note.getContent();
}
with
List<NotesFragmentCreate> allNotes = db.getAllNotes();
String[] title=new String[allNotes.size()];
String[] created=new String[allNotes.size()];
String[] content=new String[allNotes.size()];
int i=0;
for (NotesFragmentCreate note : allNotes) {
//how can I get each of record to store in this array?
title[i] = note.getTitle();
created[i] = note.getCreated();
content[i] = note.getContent();
i++
}
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);
In my android app, i m trying show a list through list adapter and the data comes from SQLite db. However the list items are not showing up , though everything is fine , i think! .
This is my code for showing list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_list_activity);
float storeId = 1;
//Storedb is my data adapter class of SQLite
StoreDb storelist = new StoreDb(this);
storelist.open();
ArrayList arraylist= storelist.getStoreName(storeId);
adapter= new ArrayAdapter<String>(this, R.layout.store_list_style, arraylist);
medicine_List= (ListView) findViewById (R.id.list);
medicine_List.setAdapter(adapter);
medicine_List.setOnItemClickListener(this);
}
And this is the method for reading data from SQLite!
public ArrayList getStoreName(long storeId) {
ArrayList<String> array_list = new ArrayList<String>();
String[] column2 = new String[] { AREA_PREV_ID, STORE_NAME };
Cursor res = ourDatabase.query(DATABASE_TABLE2, column2, AREA_PREV_ID + "=" + storeId, null, null, null, null);
int istore = res.getColumnIndex(STORE_NAME);
if (res != null) {
res.moveToFirst();
while(res.isAfterLast() == false){
String s = res.getString(istore);
array_list.add(s);
res.moveToNext();
}
}
return array_list;
}
Can anyone help what m i doing wrong here!Thanks in advance
I have an External Database into assets folder. I have been successful into loading it on my Emulator and performing operations on it.
I also know how to fill data using queries in Spinner and ListView.
The main issue: I am running a query which gives me all data from the table. I store them in a Bean class. Now i have successfully filled one of the column data into a spinner.
BUT, when i open the spinner, i don't get Database values but object name into spinner
FOR e.g -- com.mypackageName.BeanPackage.BeanClass#411da123
I get the whole spinner full of this, not the Data which is in Database( e.g 13, 13/1) .
My Code :
Query in DBHelper Class :
public Cursor getBusNumbers() {
// date="21-10-2013";
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
return db.rawQuery("select * from table", null);
}
In My Main Activity :
Adapter code :
adapter = new Adapter(MainActivity.this,android.R.layout.simple_spinner_item, array);
route.setAdapter(adapter);
adapter.notifyDataSetChanged();
My GetView method:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(layout, null);
}
final Bean item = items.get(position);
final TextView km = (TextView) convertView
.findViewById(android.R.id.text1);
km.setText(item.getRouteNumber());
km.setTextSize(22);
return convertView;
}
}
Method which fills the Array :
private void loadFieldDatabase() {
Cursor c = dbhelper.getBusNumbers();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Bean detail = new Bean();
detail.setRouteNumber(c.getString(c
.getColumnIndex("route_number")));
array.add(detail);
c.moveToNext();
}
c.close();
//dbhelper.close();
}
Here in your code your setting the Bean object into the Text view insted of which item you need to set that.
Try this code this may help you.
private void loadSpinnerCourse() {
// TODO Auto-generated method stub
List<String> lables = getAllCourse();
// Creating adapter for spinner
dataAdapterCourse = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapterCourse
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
mLesson_course.setAdapter(dataAdapterCourse);
}
private List<String> getAllCourse() {
// TODO Auto-generated method stub
List<String> labels = new ArrayList<String>();
mCoureseIdList = new ArrayList<String>();
ExamDatabaseConnector dbConnector = new ExamDatabaseConnector(
getActivity());
dbConnector.open();
String selectQuery = "SELECT * FROM courses_stud";
Cursor cursor = dbConnector.database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
mCoureseIdList.add(cursor.getString(0));
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
dbConnector.database.close();
// returning lables
return labels;
}
Cursor cursor = db.getAllBhashat();
SpinnerArr = new String[cursor.getCount()+1];
SpinnerArr[0] = "<-SELECT->";
if(cursor.moveToNext()){
int i = 1;
do {
SpinnerArr[i] = cursor.getString(cursor
.getColumnIndex("LocalityTitle_E"));
i++;
} while (cursor.moveToNext());
}if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
ArrayAdapter<String> adapter_sorCat = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, SpinnerArr);
Spinner.setAdapter(adapter_sorCat);
adapter_sorCat
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}