App gets force closed when going to this activity. I actually noticed that if i remove the cursor part the activity doesn't crash. Help would be appreciated.
public class SearchResults extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresults);
Database myDbHelper = new Database(null);
myDbHelper = new Database(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
}catch(SQLException sqle){
throw sqle;
}
// Get the intent, verify the action and get the query
Intent intent = getIntent();
String query = intent.getStringExtra(SearchManager.QUERY);
SQLiteDatabase myDb = myDbHelper.getReadableDatabase();
String q = "SELECT BookTitle, _ISBN FROM Books WHERE BookTitle LIKE" + query;
Cursor c = myDb.rawQuery(q, null);
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] { "Books._ISBN", "Books.BookTitle" };
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.ISBN_entry, R.id.Title_entry };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.listlayout, c, columns, to);
this.setListAdapter(mAdapter);
}
}
The Cursor requires a column called '_id' - change your query to alias your ISBN column as follows...
String q = "SELECT _ISBN as _id, BookTile FROM Books WHERE BookTitle LIKE" + query;
See my answer and explanation here column '_id' does not exist problem
Related
My MainActivity have a listview with some categories,If I click a particular category in my listview,it's need to redirect to another activity,which need to have the details of that particular category.
Eg: IF I select FOOD in Mainactivity,I want to redirect to another activity where the activity want to have the budget amount of food.
public class addbudget extends ActionBarActivity implements View.OnClickListener{
SimpleCursorAdapter adapter;
DBhelper helper;
SQLiteDatabase db;
EditText txtBudget;
TextView txr;
ListView rldlist,list;
Button btn66;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addbudget);
btn66=(Button)findViewById(R.id.btn_addBudget);
btn66.setOnClickListener(this);
helper=new DBhelper(addbudget.this);
txr=(TextView)findViewById(R.id.addbud);
txtBudget=(EditText)findViewById(R.id.etBudget);
rldlist = (ListView) findViewById(R.id.rldlist);
list = (ListView) findViewById(R.id.list);
Bundle data_from_list= getIntent().getExtras();
String value_in_tv= data_from_list.getString("passed data key");
txr.setText(value_in_tv);
fetchData2();
}
private void clearfield(){
txtBudget.setText("");
}
public void onClick(View v) {
if (btn66 == v) {
ContentValues value = new ContentValues();
value.put(DBhelper.Amount, txtBudget.getText().toString());
value.put(DBhelper.Description,txr.getText().toString());
if (txtBudget.length() == 0) {
txtBudget.requestFocus();
txtBudget.setError("Field Cannot Be Empty");
} else {
db = helper.getWritableDatabase();
db.insert(DBhelper.TABLE2, null, value);
db.close();
clearfield();
Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show();
fetchData2();
}
}
}
private void fetchData2() {
db = helper.getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE2, null, null, null, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}
}
This is how ,I'm fetching data to a listview from database.Here I'm fetching Amount from database.
How can I change the fetchdata method to get the BudgetAmount of a specific category ?(I'm using bundle to get the name of the category from the listview of MainActivity)
You can use sql syntax:
String sql = "select * from DBhelper.TABLE2 where category_name_column = " + category";
Cursor c = db.rawQuery(sql.toString(), null);
Or if you want to use params:
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {
"category_name"
};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
So your method can be as such:
private void fetchData2(String category) {
db = helper.getReadableDatabase();
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {"category"};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}
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);
This is our main class to get information from the database. We are trying to get the values of the "name" column in the "barcode" database that we have created. Right now, we are not able to get the desired value but values as "a, b, c, d, ..." (such as; it returns "a" when we ask for the 1st one, it return "b" when we ask for the second one in the "name" column) value with the cursor.getString method
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataBaseHelper myDbHelper = new DataBaseHelper(this);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDatabase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch(SQLException sqle){
throw sqle;
}
Cursor cursor = myDbHelper.getAllAccounts();
String[] values = new String[6];
int i=0;
//take into the array from the database
while(cursor.moveToNext()){
values[i]= cursor.getString(cursor.getColumnIndex("name"));
i++;
}
cursor.close();
//Write to textview
TextView youtextview = (TextView) findViewById(R.id.textView1);
youtextview .setText(values[2]);
}
}
You are not dealing with the cursor in the right way (also you should not do DB calls in the main UI thread which is what you are doing right now). See: http://developer.android.com/reference/android/database/Cursor.html
static final COL_NAME = "name";
Cursor cursor = myDbHelper.getAllAccounts();
cursor.moveToFirst();
int maxCursorIndex = cursor.getCount();
for(int cursorIndex=0;cursorIndex<maxCursorIndex;cursorIndex+=1){
values[cursorIndex] = cursor.getString(cursor.getColumnIndex(COL_NAME);
}
cursor.close();
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.
I'm trying to display the content of my SQLite table using SimpleAdapter and TableView.
It works just fine at first launch, but when i relaunch the Activity it adds the table one more time in the listView.
This happens everytime i launch the intent from my front menu.
It seems to me that the SimpleAdapter is stored from the last time, and added again when the intent is opend from the menu?
Maybe there is a way to reset the adapter everytime it is launched?
I'm new to programming and hope someone can help me:)
Some code:
static final ArrayList<HashMap<String,String>> results = new ArrayList<HashMap<String,String>>();
private String tableName = DBAdapter.tableName;
private SQLiteDatabase newDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
ListAdapter adapter = new SimpleAdapter(
this,
results,
R.layout.liste,
new String[] {"Name","LastName","Age"},
new int[] {R.id.item_id,R.id.item_name,R.id.item_tid}
);
setListAdapter(adapter);
}
private void openAndQueryDatabase() {
try {
DBAdapter dbHelper = new DBAdapter(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT Startnr, Navn, Tid FROM " +
tableName + " ORDER BY Startnr ASC" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
HashMap<String,String> list = new HashMap<String,String>();
String firstName = c.getString(c.getColumnIndex("Startnr"));
String lastName = c.getString(c.getColumnIndex("Navn"));
String age = c.getString(c.getColumnIndex("Tid"));
list.put("Name", "" + firstName);
list.put("LastName", "" + lastName);
list.put("Age", "" + age);
results.add(list);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.close();
}
}
Its because you have declared the "results" array list as a "static" variable.