deleting sqlite row using listview - android

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().

Related

customize listview can't show all data, android studio

I'm thinking how to show data at the customize listview page. can you guys help me to find out where is the mistakes?
here is the assignment
Model txn;
public SQLiteHelper mSQLiteHelper;
ListView mListView;
ArrayList<Model> mList;
RecordListAdapter mAdapter = null;
this is the initialization
mListView = findViewById(R.id.listView);
mList = new ArrayList<>();
mAdapter = new RecordListAdapter(this, R.layout.row, mList);
mListView.setAdapter(mAdapter);
mSQLiteHelper = new SQLiteHelper(this);
mList = new ArrayList<>();
This is my page which showing all data, I put a debugger to debug. It can get my all data which have 15 columns, But it can't show at the listview page. is there any mistake at this code?
try {
SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from Table1", null);
mList.clear();
while (cursor.moveToNext()) {
txn = new Model();
txn.setId(cursor.getInt(cursor.getColumnIndex("id")));
txn.setName(cursor.getString(cursor.getColumnIndex("name")));
txn.setAddress(cursor.getString(cursor.getColumnIndex("address")));
txn.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
mList.add(new Model());
}
mAdapter.notifyDataSetChanged();
if (mList.size() == 0) {
Toast.makeText(this, "No record found...", Toast.LENGTH_SHORT).show();
}
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
Please check below code
mListView = findViewById(R.id.listView);
mSQLiteHelper = new SQLiteHelper(this);
mList = new ArrayList<>();
mAdapter = new RecordListAdapter(this, R.layout.row, mList);
mListView.setAdapter(mAdapter);
Data binding function code
try {
SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from Table1", null);
mList.clear();
while (cursor.moveToNext()) {
txn = new Model();
txn.setId(cursor.getInt(cursor.getColumnIndex("id")));
txn.setName(cursor.getString(cursor.getColumnIndex("name")));
txn.setAddress(cursor.getString(cursor.getColumnIndex("address")));
txn.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
mList.add(txn);
}
mAdapter.notifyDataSetChanged();
if (mList.size() == 0) {
Toast.makeText(this, "No record found...", Toast.LENGTH_SHORT).show();
}
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
and I have one more suggestion, do not add listview click listener inside of your data binding function.

How to reset spinner list when fragment resume?

I have two spinner in my application which populating list from sqlite and it is working fine. When I select State in first spinner then second spinner list populate depend on first spinner. Now what I want that when I select item in both spinner and then I press back and again launch the activity then the list of second spinner still there. I want to clear list of second spinner when I press back button and Populate list in second spinner when user select value in first spinner.
public void fillStateData() {
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst()) {
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
stateCodeId = cursor.getString(0);
}
cursor.close();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void fillDistrictData(String stateCodeId) {
try {
district_array = new ArrayList<String>();
district_array.clear();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '" + stateCodeId + "'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
fillTalukaData(districtCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
add this method to activity.Hope this will work .
#Override
public void onBackPressed() {
spnDistrict.getAdapter().clear();
spnDistrict.getAdapter().notifyDataSetChanged();
finish();
}
Try using
adapter.clear();
spinner.setAdapter(new ArrayAdapter<String>(YourActivity.this,android.R.layout.simple_dropdown_item_1line,adapter));
Use Onresume for clear the array list you want
#Override
public void onResume() {
Log.e("DEBUG", "onResume of LoginFragment");
state_array.clear();
district_array.clear();
super.onResume();
}
or in onCreate view After Inttilizing array clean both arrayList.

Index 2 requested with size of 2

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.

delete row of listview and sqlite

my following codes show the data of sqlite in listview. now i want to write long click to delete row in listview and sqlite. please help me. how can i do that?
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();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
R.layout.cartformat,results));
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");
}}}
The best way would be to develop a custom adapter. But if you don't want, this should work :
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList(){
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
String currentString = results.get(position);
String resultRegexString = "Title\\: ([^,]+), Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(resultRegexString);
if(resultRegexMatcher){
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3));
database.delete("CART", whereClause, null);
}
}
results.remove(position);
displayResultList();
});
}

display data from sqlite

i have a problem in showing data coming from database sqlite, i looked for a solution
here i did found plenty but i couldn't make it work, the error i get is : Error occured:
java.lang.IllegalArgumentException: column '_id' does not exist !!
my code is :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
private ArrayList<String> arr;
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();
Button suivant = (Button)findViewById(R.id.com_quest);
suivant.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent l = new Intent(MainActivity.this,ActivityUn.class);
startActivity(l);
}
});
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
Log.i("MyApp", "Total users: " + cursor.getCount());
Toast.makeText(getApplicationContext(),
"Number of rows: " + cursor.getCount(), Toast.LENGTH_LONG)
.show();
String[] databaseColumnNames = new String[] { DBAdapter._id };
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);
list.setAdapter(myCursordapter);
} }
and in 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
}, null, null, null,
null, null);
}
All CursorAdapters require that the Cursor includes a column called _id. Your Cursor contains just one column called Num_du_Questionnaire.

Categories

Resources