Listview from DB - android

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

Related

List items not showing when reading data from SQLite db

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

Insert and retrieval from database in android (Stucked in infinite loop)

The problem is i inserted only two rows but on execution it enters into infinite loop and repeatedily showing the same data..Any kind of help would be appreciated
Here is my code.
This is my databse class (i.e DbAdapter)
public Cursor getAllRows() {
String[]columns = new String[]{ KEY_MODEL,KEY_BRAND, KEY_PRICE};
Cursor c = db.query(TABLE_LAPTOPS, columns, null, null, null, null, null);
if (c != null) {
c.moveToLast();
}
return c;
}
This is my main class (i.e Laptops)
DbAdapter obj = new DbAdapter(this);
obj.open();
obj.insertRow("Dell1", "Dell", 345);
obj.insertRow("Hp1", "HP", 546);
obj.close();
obj.open();
Cursor c1 = obj.getAllRows();
try{
if(c1 != null){
ListView empListView = (ListView)findViewById(R.id.listView1);
ArrayList<String> data1 = new ArrayList<String>();
for(c1.moveToFirst();!c1.isAfterLast();c1.moveToNext())
{
Toast.makeText(getApplicationContext(), c1.getString(0), Toast.LENGTH_LONG).show();
}
//empListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1));
}}catch(SQLException e){
e.printStackTrace();
}
obj.close();
c.moveToLast();
here is the issue
c.moveToFirst();
try this..
Try with Like This
listView = (ListView) rootView.findViewById(R.id.Assignment_VM_List);
AssignmentDatabaseConnector dao = new AssignmentDatabaseConnector(getActivity());
List<AssignmentPojo> assignments = dao.getAllAssignmentList();
AssignmentCustomAdapter assignmentCustomAdapter = new AssignmentCustomAdapter(getActivity(),
assignments, this);
listView.setAdapter(assignmentCustomAdapter);
AssignmentDatabaseConnector :
public List<AssignmentPojo> getAllAssignmentList() {
open();
List<AssignmentPojo> assignmentList = new ArrayList<AssignmentPojo>();
// Select All Query
String selectQuery = "SELECT * FROM Assignment";
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) { // ##Your Main Issue is Here ##
do {
AssignmentPojo assignment = new AssignmentPojo();
assignment.setAssign_Id(cursor.getString(0));
assignment.setAssign_Course(cursor.getString(1));
// Adding contact to list
assignmentList.add(assignment);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
// return contact list
return assignmentList;
}
This is just a sample code you can utilize this code according to your requirements

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.

SQLite read all data operation

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

List View Array from Database

I have retrieved data and successfully shown it in text view.
What do I have to modify in my code to make it look like a list view?
And also how do modify my listview programatically(adding size and padding)?
Here is a part of my DBclass in selecting the items that I've displayed
getFAData() {
// TODO Auto-generated method stub
String [] columns = new String[]{Row_Name};
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
String res = "";
int iRow = c.getColumnIndex(Row_Name);
//int iDesc = c.getColumnIndex(Row_Desc);
//int iID = c.getColumnIndex(Row_id);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
res = res + c.getString(iRow) + "\n";
}
return res;
}
And here is the class file:
public class FirstAid extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.firstaid);
displayresult();
}
public void displayresult (){
TextView tvFa = (TextView) findViewById(R.id.tvFA);
tvFa.setMovementMethod(new ScrollingMovementMethod());
DbHelper tblFa = new DbHelper(this);
tblFa.open();
String result = tblFa.getFAData();
tblFa.close();
tvFa.setText(result);
}
}
Create ArrayList int the get data function of database
public ArrayList<String> getFAData() {
ArrayList<String> comments = new ArrayList<String>();
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
int iRow = c.getColumnIndex(Row_Name);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
comments.add(c.getString(iRow ));
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
in your activity retrieve data like this.
ArrayList<String> array = new ArrayList<String>();
array = tblFa.getFAData();
you need to implement a method in your dbhelper class like this
public List<String> selectAll_data() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME_2, new String[] { "str" },
null , null, null, null, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Now in your activity
List<String> events = dh.selectAll_data();
String[] arr = new String[events.size()];
arr = events.toArray(arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
If you want to see a real time example check this url

Categories

Resources