I have build an app that take data with different attribute, adds them in the database and then shows it through a ListView.
I have done the part where data are added, but I Can't figure out how to fetch it(for now I just want the name) from the database and populate it in the ListView.
Here is the part in the database class.
public Cursor getCursor() {
Cursor c = null;
sqLiteDatabase = this.getReadableDatabase();
String query = "SELECT * FROM tbl_customer";
String where = null;
c = sqLiteDatabase.query("tbl_customer", new String[]{"Name"}, where, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
here is the part of code in activity which I want to show the ListView in.
private void populateListView(){
Cursor cursor = db.getCursor();
String []From = new String[]{"Name"};
int [] to = new int[R.id.textView];
SimpleCursorAdapter adapter;
adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,From,to,0);
ListView listView = (ListView)findViewById(R.id.ShowDataListView);
listView.setAdapter(adapter);
}
Please guide me, where I have gone wrong, and correct me.
you are using R.id.textView as a size of array
int [] to = new int[R.id.textView];
it should be like this
int [] to = new int[]{R.id.textView};
You've to specify the From and To params of the SimpleCursorAdapter.
adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,
new String[] { "Name" },to,0);
As for to, you need to put the id of your textview from R.layout.listview_items. Let's assume the id of your TextView is R.id.text1 then the adapter will look like following,
adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,
new String[] { "Name" },
new int[] { android.R.id.text1 },
0);
Here, have a look at the documentation to grasp it more clearly.
Related
I have serveral objects in my DB with three Strings attributes. One of the shows a date information, eg. 1.4.2016, 20.10.2017. I list these objects in a ListView, but before I want to sort them by their dates.
//
//Show all Data on ListView
//
private void displayListView() {
Cursor cursor = datasource.fetchAllData();
// The desired columns to be bound
String[] columns = {
DatabaseHelper.COLUMN_TITLE,
DatabaseHelper.COLUMN_DESCRIPTION,
DatabaseHelper.COLUMN_DEADLINE,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.processobject_title,
R.id.processobject_description,
R.id.processobject_deadline,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.listview_viewlayout,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listview);
ArrayList <ProcessObject> arrayList = new ArrayList<>();
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
activateAddButton();
OnItemClickListener();
};
I see two oppurtinities: sorting the cursor, or sorting the Array to[]. But I don't know how.
public Cursor fetchAllData(){
Cursor cursor = database.query(DatabaseHelper.TABLE_DATABASE, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Solved it:
String orderBy = DatabaseHelper.COLUMN_DEADLINE + " ASC";;
Cursor cursor = database.query(DatabaseHelper.TABLE_DATABASE, columns, null, null, null, null, orderBy);
How to retrieve rows from external database and display them in text view??
i have tried some codes but the application stopped.
In my database helper i added that code :
public String[] getData(String l) {
// TODO Auto-generated method stub
String[] columns = new String[] { DB_ID, DB_name, DB_desc };
// FILTERS DEPENDING ON THE CATEGORY TYPE PASSED IN THE PARAMETER
Cursor c = mDataBase.rawQuery("SELECT _id,name,description FROM facilities WHERE name='" + l + "'", null);
String[] result = new String[] { null, null, null, null, null };
int iId = c.getColumnIndex(DB_ID);
int iName = c.getColumnIndex(DB_name);
int iDesc = c.getColumnIndex(DB_desc);
c.moveToFirst();
result[0] = c.getString(iId);
result[1] = c.getString(iName);
result[2] = c.getString(iDesc);
return result;
}
And this code in my activity which i wish to display the string in textview:
for(int i=0;i<4;i++){
// dbhelper.open();
String[] data =dbhelper.getData(namee);
// dbhelper.close();
txt.append("\n"+data[3]+"\n");}
}
This is another code i tried it, from this url :
Return all data from a SQLite DB into two columns in Android
Can you post the LogCat entries?
What does this line do?
String[] result=new String[]{null,null,null,null,null};
Try
String[] result = new String[5];
instead;
I used this in one of my app.... This may help.
I declared the following in the main activity itself
DatabaseHelper myDbHelper = new DatabaseHelper(this);
.
.
try {
myDbHelper.createDataBase();
}
.
.
.
db = myDbHelper.getWritableDatabase();// or db = myDbHelper.getReadableDatabase();
.
.
.
//In another function
Cursor c = db.rawQuery("Whatever you want to query");
String[] s=new String[]{"The fields(columns) you want queried and used in textbox"};
This question already has an answer here:
attempt to re-open an already-closed object: SQLiteDatabase
(1 answer)
Closed 8 years ago.
I know there are several questions like this one, but all of them seem to have a different approach to solve the problem and none have solved mine.
I have my main activity working just fine, loading the db and populating the listview. Then I call a second activity and the problem shows up when I try to load the listview.
I have tried using start/stop managingcursor(cursor) even though it is deprecated, but it didn't fix the problem. Also I tried cloasing the cursor and db in my main activity before firing the next one but that didn't help either.
Both classes extend from ListActivity and follow the same sequence:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Open db in writing mode
MySQLiteHelper.init(this);
MySQLiteHelper tpdbh =
new MySQLiteHelper(this, "DB", null, 1);
SQLiteDatabase db = tpdbh.getWritableDatabase();
checkLocationAndDownloadData(); //this fires a Asynctask that calls method parseNearbyBranches shown bellow
//I load the data to the ListView in the postExecute method of the asynctask by calling:
/*
Cursor cursor = MysSQLiteHelper.getBranchesNames();
adapter = new SimpleCursorAdapter(this,
R.layout.row, cursor, fields, new int[] { R.id.item_text },0);
setListAdapter(adapter);
*/
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String branch_id = cursor.getString(cursor.getColumnIndexOrThrow("branch_id"));
cursor.close();
openNextActivity(Integer.parseInt(branch_id));
}
});
}
//In another file:
private void parseNearbyBranches(JSONObject jo) throws JSONException
{
if ( jo.has(jsonTitle) &&
jo.has("company_id") &&
jo.has("id")
) {
String branch = jo.getString(jsonTitle);
MySQLiteHelper tpdbh = MySQLiteHelper.instance;
SQLiteDatabase db = tpdbh.getWritableDatabase();
db.execSQL("INSERT INTO Branches (branch_id, name, company_id) " +
"VALUES ('" +jo.getInt("id")+"', '" + branch +"', '" +jo.getInt("company_id")+"' )");
db.close(); //no difference is I comment or uncomment this line
}
}
In MySQLiteHelper.java:
public static Cursor getBranchesNames() {
// TODO Auto-generated method stub
String[] columns = new String[] { "_id", "branch_id", "name", "company_id" };
Cursor c = getReadDb().query(branchesTable, columns, null, null, null, null,
null);
return c;
}
My other activity does basically the same:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_branch_surveys);
//Read branch data from DB
int companyID = -1;
MySQLiteHelper.init(this);
String [] columns = new String [] {"company_id"};
String [] args = {Integer.toString(branchID)};
Cursor c = MySQLiteHelper.getReadDb().query(MySQLiteHelper.branchesTable, columns, "branch_id=?", args, null, null, null); //THIS QUERY WORKS JUST FINE
if (c.moveToFirst())
companyID = Integer.parseInt(c.getString(0));
c.close();
if( companyID != -1)
{
new DownloadTask().execute(Integer.toString(companyID) );
//where the Async task calls something just like NearByBranches shown above(but with different objects of course)
//And the postExecute sets the listView:
/* cursor = MySQLiteHelper.getAll();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.row, cursor, fields, new int[] { R.id.item_text },0);
setListAdapter(adapter);
*/
}
}
}
In MySQLiteHelper.java:
public static Cursor getAll() {
// TODO Auto-generated method stub
String[] columns = new String[] { "_id","title", "points" };
//********IT IS IN THIS LINE WHERE I GET THE ERROR:********************
Cursor c = getReadDb().query(theTable, columns, null, null, null, null,
null);
return c;
}
public static SQLiteDatabase getReadDb() {
if (null == db) {
db = instance.getReadableDatabase();
}
return db;
}
I hope you can help me out. Thanks!
I just tried commenting the db.close in the similar method of parseNeabyBranches and the problem was solved. Yet I dont get the same error having db.close() in parseNearbyBranches(), can you explain me why?
In parseNearbyBranches() you create a separate SQLiteDatabase object with:
SQLiteDatabase db = tpdbh.getWritableDatabase();
Since this is a different object than the one returned by getReadDb(), you can (and should) close it. The basic rule is each time you call getWritableDatabase() and getReadableDatable() you must have a matching close() statement.
How can I realize that in Android Java ?
So I mean how can I read out mark and weight, multiplize them and add the next row with the same system?:
That is what I have now for list those marks in a ListView:
private void fillData() {
Bundle extras = getIntent().getExtras();
String txt_sub_id = extras.getString("IDFach");
int test = Integer.parseInt(txt_sub_id);
Cursor mCursor = db.rawQuery("SELECT _id, subid, name, mark, gewicht, datum FROM tbl_marks WHERE subid = '"+test+"';", null);
startManagingCursor(mCursor);
if (mCursor != null && mCursor.moveToFirst()) {
int intName = mCursor.getColumnIndexOrThrow("subid");
do {
teststring = mCursor.getString(intName);
String[] from = new String[] { dbHelper.KEY_NAME_MARKS, dbHelper.KEY_MARK_MARKS, dbHelper.KEY_GEWICHT_MARKS, dbHelper.KEY_DATUM_MARKS};
int[] to = new int[] {R.id.txt_marks_row, R.id.txt_note, R.id.txt_gewicht, R.id.txt_datum};
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.show_marks, mCursor, from, to);
setListAdapter(notes);
} while (mCursor.moveToNext());
}
}
This looks like that:
What I like to have:
Thanks in advance!
You need to do something like below inside do/while loop. Here 4 is index of column name in your query.
int mark=mCursor.getInt(4);
int wght=mCursor.getInt(5);
i have searched for a awnser for this for a while today. It all looks so easy but i never get it to work. I want to fill a spinner with my cursor. I have been trying to use SimpleCursorAdapter for this as a lot of sites say i shall but i never get it to work. Show me just how easy it is :)
Thanks for your time!
My cursor
Cursor cursor = db.query(DATABASE_TABLE_Clients, new String[] {"_id", "C_Name"}, null, null, null, null, "C_Name");
My spinner
(Spinner) findViewById(R.id.spnClients);
My Code
Cursor cursor_Names = SQLData.getClientNames();
startManagingCursor(cursor_Names);
String[] columns = new String[] { "C_Name" };
int[] to = new int[] { R.id.txt_Address };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_dropdown_item, cursor_Names, columns, to);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
The following code solved my problem. I was missing .setDropDownViewResource. After that i used simple_spinner_dropdown_item so i don't have to make my own layout.
Cursor cursor_Names = SQLData.getClientNames();
startManagingCursor(cursor_Names);
String[] columns = new String[] { "C_Name" };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_Names, columns, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
I don't see a View for your dropdown in your code. Something like:
mAdapter.setDropDownViewResource(R.layout.spinner_view_dropdown);
Of course you need to have a spinner_view_dropdown.xml file in your res/layout directory.
I have done it
empresasSpinner = (Spinner) findViewById(R.id.empresasSpinner);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, empresasAll.toArray(new EntidadObject[0]));
empresasSpinner.setAdapter(spinnerArrayAdapter);
A simple DTO
public class EntidadObject {
private int id;
private String nombre;
//GETTES and SETTERS
}
The part DAO
public class EntidadDao {
//...
public List<EntidadObject> getEmpresas() {
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM empresas", null);
List<EntidadObject> entidadObjects = new ArrayList<EntidadObject>();
cursor.moveToFirst();
do {
EntidadObject entidadObject = new EntidadObject();
entidadObject.setId(cursor.getInt(0));
entidadObject.setNombre(cursor.getString(1));
entidadObjects.add(entidadObject);
} while (cursor.moveToNext());
return entidadObjects;
}
}
So then I can catch the ID of the select item with
EntidadObject eo = (EntidadObject)empresasSpinner.getSelectedItem();
eo.getId();