I want to Load my database data to the arraylist and then from arraylist to listview on button click but when I clicked the button it loads Garbage data to the listview. This is my code. What am I doing wrong?
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(Bookmarks.this, android.R.layout.simple_list_item_1, list);
String query = "Insert into WEB values('" + title.getText().toString() + "','" + address.getText().toString() + "')";
db.execSQL(query);
Toast.makeText(getApplicationContext(), "Bookmark Inserted", Toast.LENGTH_LONG);
try {
Cursor c = db.rawQuery("SELECT Title FROM WEB", null);
c.moveToFirst();
do {
String check = c.getString(c.getColumnIndex("Title"));
list.add(check);
}
while (c.moveToNext());
lv.setAdapter(adapter);
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG);
}
}
});
This is the screenshot of Layout...
Related
I am trying to delete a row in sqlite database from recyclerview adapter. Based on the position of the adapter, I am deleting my row in sqlite like this :
helper = new DBHelper(v.getContext());
database = helper.getWritableDatabase();
//statement = database.compileStatement("update result set ANS =? where SNO ='" + pos + "'");
// statement = database.compileStatement("delete result where SNO ='" + pos + "'");
//statement.bindString(1, ANS);
// statement.executeInsert();
database.delete("result",
"SNO = ? ",
new String[]{Integer.toString(pos)});
Log.d("pos", "" + pos);
// helper.Delete(pos);
database.close();
but it is not deleting in my table, and I am not getting any error. What am I doing wrong?
db = this.getWritableDatabase();
int l;
l = db.delete("result", SNO = ? " , new String[]{pos+1});
if (l > 0) {
Toast.makeText(context, "Removed "+(pos+1), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
db.close();
Here you have pass "pos" so you have not passed right SNO(pos).
Please check SNO is passes on delete query
Try this method ,
public int deleteItem(String id) {
open();
int b = 0;
try {
b = db.delete(DATABASE_TABLE_POST_ITEMS, TAG_PLUS + " = '" + id + "'", null);
} catch (Exception e) {
e.printStackTrace();
}
close();
return b;
}
call this by using this sentence,
holder.img_plus.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbhelper.deleteItem((chatMessageList.get((int) v.getTag()).getListid()));
chatMessageList.remove(position);
notifyDataSetChanged();
}
});
These are the methods of spinners
mSpinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedModel = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected Model: " + selectedModel, Toast.LENGTH_LONG).show();
String sp1 = String.valueOf(mSpinnerModel.getSelectedItem());
if (sp1.contentEquals("College1")) {
List<String> list = new ArrayList<String>();
list.add("MAHARANI UNIVERSITY ");
//list.add("MANIPAL ");
// list.add("ITM UNIVERSITY ");
// list.add("UNIVERSITY1");
// list.add("MAHARANI UNIVERSTY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
// selectedMake = parent.getItemAtPosition(position).toString();
mSpinnerMake.setAdapter(dataAdapter);
}
if (sp1.contentEquals("College2")) {
List<String> list1 = new ArrayList<String>();
list1.add("ITM UNIVERSITY");
//list1.add("UNIVERSITY2");
// list1.add("UNIVERSITY3");
// selectedMake = parent.getItemAtPosition(position).toString();
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, list1);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter2.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter2);
}
if (sp1.contentEquals("College3")) {
List<String> list = new ArrayList<String>();
list.add("MANIPAL ");
//list.add("UNIVERSITY4");
//list.add("UNIVERSITY5");
ArrayAdapter<String> dataAdapter3 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, list);
dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter3.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter3);
// selectedMake = parent.getItemAtPosition(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mSpinnerMake.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedMake = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
mSpinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedYear = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected Year: " + selectedYear, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mButtonShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String eligibleBattery=fetchEligibleBattery(mSqLiteDatabase);
mTextViewResult.setText(eligibleBattery);
}
});
}
And this is method for data and query for fetching data but it is not working. when i select data in spinners it shows in logcat but it is not fetching data the query right below is not working please help.
private String fetchEligibleBattery(SQLiteDatabase db) {
String battery="";
String SELECT_BATTERY_QUERY = "SELECT "+ DatabaseConstants.KEY_BATTERY+" FROM " + DatabaseConstants.TABLE_CAR_DETAILS + " WHERE " + DatabaseConstants.KEY_CAR_MAKE + " ='" +selectedMake +
"' AND "+ DatabaseConstants.KEY_CAR_MODEL +" = '"+ selectedModel+ "' AND "+ DatabaseConstants.KEY_CAR_YEAR+"= '"+selectedYear +"' ;";
Log.d("Database", "Battery Select Query : " + SELECT_BATTERY_QUERY);
Cursor cursor = db.rawQuery(SELECT_BATTERY_QUERY, null);
try {
if (cursor.moveToFirst()) {
battery=cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_BATTERY));
}
} catch (Exception e) {
Log.d("Database", "Error while trying to get icons from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return battery;
}
public void fetchDataFromDBForSpinners(SQLiteDatabase db) {
String SELECT_MODELS_QUERY = "SELECT * FROM " + DatabaseConstants.TABLE_CAR_DETAILS + ";";
String model, make, year;
Cursor cursor = db.rawQuery(SELECT_MODELS_QUERY, null);
try {
if (cursor.moveToFirst()) {
do {
model = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_MODEL));
make = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_MAKE));
year = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_YEAR));
models.add(model);
makes.add(make);
years.add(year);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d("DATABASE", "Error while trying to get events from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
This query wrong
Please check carefully my fixed code
String SELECT_BATTERY_QUERY = "SELECT "+ DatabaseConstants.KEY_BATTERY+" FROM " + DatabaseConstants.TABLE_CAR_DETAILS + " WHERE " + DatabaseConstants.KEY_CAR_MAKE + " = " +selectedMake +" AND "+ DatabaseConstants.KEY_CAR_MODEL +" = "+ selectedModel+ " AND "+ DatabaseConstants.KEY_CAR_YEAR+"= "+selectedYear ";
I am creating a database within my android application that allows users to enter assignment information. At the moment the information is stored but not listed as I would like. I am looking to add function to the View Assignments button so that it returns to the AssignmentsManager page and lists the entered assignments.
I believe I will have to use something like;
listView=(ListView)findViewById(R.id.listView1); //initialise the listview
listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0); //initialise an ArrayAdapter
listView.setAdapter(listAdapter); //set the adapter to the listview
And to add assignments to list;
listAdapter.add(c.getString(0)+c.getString(1)+c.getString(2)+c.getString(3)+c.getString(4));
I am unsure how to implement this though. Below is my class to add the assignments;
public class addassignment extends Activity {
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
}
public void addAssignment(View v) {
Log.d("test", "adding");
// get data from form
EditText nameTxt = (EditText) findViewById(R.id.editTitle);
EditText dateTxt = (EditText) findViewById(R.id.editDuedate);
EditText courseTxt = (EditText) findViewById(R.id.editCourse);
EditText notesTxt = (EditText) findViewById(R.id.editNotes);
db.open();
long id = db.insertRecord(nameTxt.getText().toString(), dateTxt
.getText().toString(), courseTxt.getText().toString(), notesTxt
.getText().toString());
db.close();
nameTxt.setText("");
dateTxt.setText("");
courseTxt.setText("");
notesTxt.setText("");
Toast.makeText(addassignment.this, "Assignment Added",
Toast.LENGTH_LONG).show();
}
public void viewAssignments(View v) {
Intent i = new Intent(this, AssignmentManager.class);
startActivity(i);
}
}
Here is the Assignments Class where the list should be displayed;
public class AssignmentManager extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignmentmanager);
Button addBtn = (Button) findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AssignmentManager.this,
addassignment.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DBAdapter db = new DBAdapter(this);
// ---add an assignment---
db.open();
long id = db.insertRecord("Android App", "14/02/2015", "Networks",
"First Android Project");
id = db.insertRecord("Java Development", "5/02/2015", "Java",
"Complete Assignment");
db.close();
// ---get all Records---
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
/*
* //---get a Record--- db.open(); Cursor c = db.getRecord(2); if
* (c.moveToFirst()) DisplayRecord(c); else Toast.makeText(this,
* "No Assignments found", Toast.LENGTH_LONG).show(); db.close();
*/
// ---update Record---
/*
* db.open(); if (db.updateRecord(1, "Android App", "29/02/2015",
* "Networks", "First Android Project")) Toast.makeText(this,
* "Update successful.", Toast.LENGTH_LONG).show(); else
* Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
* db.close();
*/
/*
* //---delete a Record--- db.open(); if (db.deleteRecord(1))
* Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
* else Toast.makeText(this, "Delete failed.",
* Toast.LENGTH_LONG).show(); db.close();
*/
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
public void DisplayRecord(Cursor c) {
Toast.makeText(
this,
"id: " + c.getString(0) + "\n" + "Title: " + c.getString(1)
+ "\n" + "Due Date: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
public void addAssignment(View view) {
Intent i = new Intent("addassignment");
startActivity(i);
Log.d("TAG", "Clicked");
}
}
Can anyone show me where I should implement the lists to add the functionality?
You're on the right track. I'd simplify the process if I were you, instead of initially adding assignments individually, add an ArrayList of assignments when you're creating your adapter:
listAdapter= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, assignmentArrayList);
// now set the adapter to the ListView
listView.setAdapter(listAdapter); //set the adapter to the listview
Once your adapter is set and you make any changes to it (add, remove, etc) make sure you call .notifyDataSetChanged() so it knows to refresh the list.
listAdapter.notifyDataSetChanged(); // notify the list adapter
I am newbie to android development and here is my first project of gridview database.
it show error "index 2 requested with size of 2"
I am using sqlite database db file
here is my code
Please help me!!!!!
public class MainActivity extends Activity {
SQLiteDatabase mydb;
GridView data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = (GridView) findViewById(R.id.gridView1);
List<String> li = new ArrayList<String>();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,
li);
dataAdapter.setDropDownViewResource(R.layout.activity_main);
try {
mydb = openOrCreateDatabase(getString(R.string._sdcard_sales_db), MODE_PRIVATE, null);
Cursor cr = mydb.rawQuery("SELECT * FROM users", null);
if (cr != null) {
if (cr.moveToFirst()) {
do {
String desc = cr.getString(cr.getColumnIndex("user"));
li.add(desc);
} while (cr.moveToNext());
Toast.makeText(getApplicationContext(), cr.getString(cr.getColumnIndex("user")),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "no data",
Toast.LENGTH_LONG).show();
}
}
cr.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "ERROR" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}}
thanks in advance
do {
String desc = cr.getString(cr.getColumnIndex("user"));
li.add(desc);
} while (cr.moveToNext());
Toast.makeText(getApplicationContext(), cr.getString(cr.getColumnIndex("user")),
Toast.LENGTH_LONG).show();
After the do-while loop, the cursor cr points to a row after the last valid row.
Remove the Toast where you call getString() with an invalid cursor index, or change it to toast the information you actually want.
I have a listview which connect to an sqlite database. at first it shows my sqlite fields. but my problem is,I can't delete row by setOnLongClickDelete().
error:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1510)
codes:
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList() {
// setListAdapter(new ArrayAdapter<String>(this,R.layout.cartformat,results));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " +title+ ",Quantity: "+qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
try{ String currentString = results.get(position);
String resultRegexString = "Title\\:([^,]+),Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(currentString);
if(resultRegexMatcher.find()){
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3)));
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
database.delete("CART", whereClause, null);
database.close();
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
results.remove(position);
}
return true;
} catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;
}
}
} );
displayResultList();
}
}
following Toast works:
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
If you are able to successfully remove the data from the SQLite database then you simply make your listAdapter global and then adding the code
listAdapter.notifyDataSetChanged();
after
results.remove(position);
in your onItemLongClick. After this you can remove calling displayResultList(); in setOnLongClickDelete().