Ive been trying to get my listview to update after removing an item. Here's what I have so far:
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String str = null;
public void onItemClick(AdapterView<?> arg0, final View view, int arg2, long arg3) {
//TextView txtview = (TextView)view.findViewById(R.id.txtview);
final String item = ((TextView) view.findViewById(R.id.txtview)).getText().toString();
str = item;
final long arr = arg3;
final String arg22 = longToString(arg3);
//Creating an Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(Home.this);
builder.setMessage("Are you sure you want to delete the hike " + str + " ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db1=openOrCreateDatabase("hikeManager", MODE_PRIVATE, null);
DatabaseHandler db = new DatabaseHandler(Home.this);
String table = "hikes";
Cursor c = db1.rawQuery("select id from "+ table + " where name='"+item+"'", null);
int dhike = c.getColumnIndex("name") + 1;
try {
Hike hike = db.getHike(arr + 1);
db.deleteHike(hike);
Log.d("DLT", "Deleted hike at index " + arr);
//db.updateList(adapter, myList, listItems);
adapter.remove(arg22);
adapter.notifyDataSetChanged();
//updateData();
db.close();
} catch (CursorIndexOutOfBoundsException e) {
Log.d("DLT", "Failed to delete: " + e.getMessage());
db.close();
}
//db.updateList(adapter, myList, listItems);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
I Have quite a bit of unused code in there, as I have tried a few different methods to get this to work, but have failed so far. Here is updateData:
private void updateData() {
// Get all of the notes from the database and create the item list
DatabaseHandler db = new DatabaseHandler(this);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtview, listItems);
final ListView myList = (ListView) findViewById(R.id.cardListView);
int num = db.getHikesCount();
for (int i=1; i<num+1; ++i){
Hike name = db.getHike(i);
String nam = name.getName();
listItems.add(nam);
}
myList.setAdapter(adapter);
db.close();
}
The updateData does have some unintended consequences when I use it to update the view after adding an item to a non-empty list, but it works for now. The item is successfully deleted, since I can close the app and reload it and the item will be gone. I just cant seem to get it to update properly for me.
Just use
adapter.notifyDataSetChanged();
Related
I am trying to update my listview with notifyDataSetChanged() this method, but listview is not getting updated, if i press back button and go to previous activity and then again if i come in this activity then it is getting updated, i don't know why. I tried all possible solution but not getting proper solution. Please help Below is my code.
Here is a link which i tried
ListView not getting updated on calling notifyDataSetChanged()
notifyDataSetChanged() not working
notifyDataSetChanged Android ListView
notifyDataSetChanged not updating ListView
The event of notifyDataSetChanged()
public class Assignment extends Activity {
ListView mListView;
ImageView imageViewCrtAsnm;
String[] stg1;
List<String[]> names2 = null;
DataManipulator dataManipulator;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment);
imageViewCrtAsnm = (ImageView) findViewById(R.id.createassignment);
mListView = (ListView) findViewById(R.id.displaydata);
imageViewCrtAsnm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Assignment.this,
Assignment_Create.class);
startActivity(intent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Assignment.this);
alertDialogBuilder.setTitle("Delete Data");
alertDialogBuilder
.setMessage("Click yes to Delete Record!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
String[] delete = names2.get(position);
String idString = delete[0];
long idLong = Long.valueOf(idString);
Log.d("Deleting...", idLong + "");
dataManipulator.delete(idLong);
names2.remove(position);
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n"
+ "Descr : " + name[2]
+ "\n" + "Day's Left : "
+ name[3];
stg1[x] = stg;
x++;
}
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
dataManipulator = new DataManipulator(this);
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n" + "Descr : " + name[2] + "\n"
+ "Day's Left : " + name[3];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stg1);
mListView.setAdapter(new ArrayAdapter<String>(this, R.layout.check,
stg1));
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
ArrayAdapter makes a copy of your items that you pass to it in the constructor and uses that internally.
ArrayAdapter Source
So simply manipulating your original array means nothing to the adapter. You are notifying it that the data has changed when it has not changed at all, it still holds the original list you populated it with.
You need to either recreate the entire adpater again or use the clear, addAll, remove or insert methods to manipulate the data.
http://developer.android.com/reference/android/widget/ArrayAdapter.html
You are recreating your array when you remove data. Have you tried also recreating your adapter to use the new array?
I found solution for this.
Just use onResume method to call adapter class...
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n" + "Descr : " + name[2] + "\n"
+ "Day's Left : " + name[3];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this, R.layout.assignment_custom,
stg1);
mListView.setAdapter(adapter);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setBackgroundResource(R.drawable.assignment_icon);
adapter.notifyDataSetChanged();
adapter.setNotifyOnChange(false);
mListView.invalidateViews();
}
Just call this part of code in onResume method and you are done. But anyway thanks to all who have helped me. i am posting this answer here so may be other's can take benefit and not waste time like i did.
I'm showing data from a database in a list view and I want to delete one entry when the user do a longclick in one row and then selects "yes" in a Dialog. I have all the code and it compiles but it isn't deleting anything. Any suggestion? Thanks
That's the code of the listview:
public class Consult extends FragmentActivity {
private ListView list;
private SQLiteDatabase db;
private int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.consult);
list = (ListView)findViewById(R.id.list);
this.getIntent();
ApeironsSQLiteHelper apeironsdb = new ApeironsSQLiteHelper(this, "DBApeirons.DB", null, 1);
db = apeironsdb.getWritableDatabase();
String[] campos = new String[]{"_id", "name", "kind_place", "score"};
Cursor c = db.query("Apeirons", campos, null, null, null, null, null);
c.moveToFirst();
String[] from = new String[]{"name", "kind_place", "score"};
int [] to = new int[] {R.id.Titulo, R.id.SubTitulo};
//#SuppressWarnings("deprecation")
MyListAdapter myadapter = new MyListAdapter (this,
R.layout.entrys, c, from, to);
list.setAdapter(myadapter);
list.setLongClickable(true);
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
saveID(index);
//db.delete("Apeirons", "_id=" + String.valueOf(index), null);
Log.d("ONCLICK", String.valueOf(index));
Log.d("ONCLICK", String.valueOf(id));
callDialog();
return false;
}
});
}
public void callDialog(){
Log.d("DIALOG", String.valueOf(id));
FragmentManager fragmentmanager = getSupportFragmentManager();
SimpleDialog dialog = new SimpleDialog();
dialog.saveIndex(id);
//SimpleDialog.newInstance(id);
dialog.show(fragmentmanager, "tag");
Log.d("erase", "salgo del callDialog");
}
public void saveID(int ID){
id = ID;
}
And that's the code of the Dialog:
public class SimpleDialog extends DialogFragment {
private SQLiteDatabase dbs;
int ID;
#Override
public Dialog onCreateDialog (Bundle savedInstanceState){
//ID = getArguments().getInt("id");
ApeironsSQLiteHelper apeironsdbs = new ApeironsSQLiteHelper(getActivity(),
"DBApeirons.DB", null, 1);
dbs = apeironsdbs.getWritableDatabase();
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.EraseDialogMessage);
builder.setTitle(R.string.app_name);
builder.setPositiveButton(R.string.EraseDialogPButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String args = String.valueOf(ID);
Log.d("Yes BUTTON", args);
/*String sql = "DELETE FROM Apeirons WHERE _id=" + args;
dbs.execSQL(sql);*/
//int prueba = dbs.delete("Apeirons", " _id = ?" + args, null);
int prueba = dbs.delete("Apeirons", "_id = ?", new String[] { "" + args });
Log.d("RETORNO DELETE", String.valueOf(prueba));
}
});
builder.setNegativeButton(R.string.EraseDialogNButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
public void saveIndex(int index){
ID = index;
}
}
I fixed!!! The problem was that I was using the id of the listview and it isn't the same in the database. Now I recover first the _id of the database and works perfect. Thank you for all the answers. The code to recover the _id of database below (maybe is useful to someone):
list.setLongClickable(true);
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
c.moveToPosition(index);
int id = c.getInt(c.getColumnIndex("_id"));
saveID(id);
Log.d("ONCLICK", String.valueOf(index));
Log.d("ONCLICK", String.valueOf(id));
callDialog();
return false;
}
});
You can try
private SQLiteDatabase dbs;
String args = String.valueOf(ID);
Delete query:
Method 1:
dbs = apeironsdbs.getWritableDatabase();
String deleteQuery = "DELETE FROM Apeirons where _id='"+ args +"'";
dbs .execSQL(deleteQuery);
Or you can use
Method 2:
ApeironsSQLiteHelper apeironsdb = new ApeironsSQLiteHelper(this, "DBApeirons.DB", null, 1);
apeironsdb .delete(Apeirons, _id+"="+ID, null); // ID is int value
Try change this line:
int prueba = dbs.delete("Apeirons", " _id = ?" + args, null);
into
int prueba = dbs.delete("Apeirons", " _id = \"" + args + "\"", null);
As I searched whole net still in problem with ListView From Sqlite. After searching so much i am trying my project on android hive example Link here. So in this in Database Handler class they have given that a function i.e List getAllContacts() to get all sqlite data in List format.
I have implemented this in my project my using above function in ViewContact.class.
The PROBLEM is that I am not understanding how to get all data in ListView by using this type of method or by any other method.
See my code (ViewContact.class) :
public class ViewContact extends Activity {
DatabaseHandler helper = new DatabaseHandler(this);
String a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row);
ListView listContent = (ListView)findViewById(R.id.listView1);
}
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contacts";
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}// return contact list
return contactList;}}
EDIT:
See After #GrIsHu answer the output is :
Try to bind the data into the listview as below:
List<Contact> contact = new ArrayList<Contact>();
contact=getAllContacts();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, contact);
listContent.setAdapter(adapter);
Below is a code using which i suppose you can meet your requirements. In the below code i would fetch contacts saved in my database and display it in a listView. If the user wants to delete a contact from the database, then he shall long press on the item, and using the dialog that appears, he can delete the contact. Below is the code:
public class viewContacts extends ListActivity {
private static final String TAG = "MYRECORDER";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showcontacts);
//Creating a List View
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
ListView mylist=(ListView) findViewById(android.R.id.list);
mylist.setAdapter(adapter);
//Creating or opening an eisting database
SQLiteDatabase db=openOrCreateDatabase("MYDB", Context.MODE_PRIVATE, null);
//Getting a cursor to fetch data from the database
Cursor c=db.rawQuery("SELECT Number,Name FROM myTbl", null);
Log.d(TAG, "Cursor reference obtained...");
c.moveToFirst();
Log.d(TAG, "Cursor Moved to First Number....");
if(c!=null){
//If there are contents in the database, then c!=null, so using do-while loop access data // in database
do{
String num=c.getString(c.getColumnIndex("Number"));
String name=c.getString(c.getColumnIndex("Name"));
String Name_num=name+" : "+num;
listItems.add(Name_num);
c.moveToNext();
}while(!c.isAfterLast());
//update the list
adapter.notifyDataSetChanged();
//closing the database after use
db.close();
//Below is the code to delete items in data base
mylist.setOnItemClickListener(new OnItemClickListener() {
String str=null;
public void onItemClick(AdapterView<?> arg0, View view,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item = ((TextView)view).getText().toString();
str=item.substring(item.lastIndexOf('+'));
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
//Creating an Alert Dialog
AlertDialog .Builder builder=new AlertDialog.Builder(viewContacts.this);
builder.setMessage("Are you sure you want to delete the contact "+str+" ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
SQLiteDatabase db=openOrCreateDatabase("MYDB", MODE_PRIVATE, null);
Toast.makeText(getBaseContext(), "The contact: "+str+" was successfully deleted", Toast.LENGTH_LONG).show();
String table="myTbl";
String whereClause = "Number = ?";
String[] whereArgs = new String[] { str };
db.delete(table, whereClause, whereArgs);
db.close();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
} );
AlertDialog alert=builder.create();
alert.show();
}
});
}
}
}
Just use SimpleCursorAdapter in this case: http://www.java2s.com/Code/Android/UI/UsingSimpleCursorAdapter.htm
I solve that adding the function toString to my class object.
In your case, add that function to the class contact
public String toString(){
return name;
}
I've converted a list project from a BaseAdapter to an ArrayAdapter ListActivity because I was told in another question that ArrayAdapter was more dynamic and better at, specifically, allowing an item to be removed from the list and then updating to reflect that removal. I'm still running into the same issue with my ArrayAdapter, though, as follows:
I get my list data as so:
public void loadAdapter(){
DatabaseHelper helper = new DatabaseHelper(ActivityMain.this);
database = helper.getReadableDatabase();
Cursor data = database.query("list_data", fields, null, null, null,
null, null);
Integer tindex = data.getColumnIndex("listTitle");
Integer iindex = data.getColumnIndex("listType");
itemCount = 0;
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
m_parts.add(new Item(data.getString(tindex), data.getString(iindex)));
itemCount++;
}
data.close();
for (int j = 0; j < 10; j++) {
m_parts.add(new Item("", "R"));
}
m_adapter = new ItemAdapter(ActivityMain.this, R.layout.listview, m_parts);
setListAdapter(m_adapter);
}
with this custom adapter:
public class ItemAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> objects;
public ItemAdapter(Context context, int textViewResourceId,
ArrayList<Item> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.listview, null);
}
Item i = objects.get(position);
if (i != null) {
TextView textview = (TextView) v.findViewById(R.id.tv_main);
ImageView imageview = (ImageView) v.findViewById(R.id.iv_main);
TextView textview2 = (TextView) v.findViewById(R.id.tv_main2);
textview.setText(i.getText());
textview2.setText(i.getText());
imageview.setScaleType(ScaleType.FIT_XY);
Integer theDrawable;
if (i.getImage() != "L") {
theDrawable = R.drawable.listview_regular;
} else {
theDrawable = R.drawable.listview_location;
}
imageview.setImageResource(theDrawable);
}
v.setOnClickListener(new OnItemClickListener(position));
v.setOnLongClickListener(new OnItemLongClickListener(position));
return v;
}
}
The context menu from longclicklistener offers a delete option, which uses this
private void showDialogOnLongClick(final int position) {
Builder alert = new AlertDialog.Builder(this);
ArrayList<String> listInfo = getListInfo(position);
String content = listInfo.get(1);
String numItems = "";
if (content != null && content.indexOf("|~|") > -1) {
String[] contentSplit = content.split("\\|\\~\\|");
numItems = contentSplit.length + " items in list";
} else {
numItems = "No items in list";
}
String listTitle = listInfo.get(0);
String created = "Created: " + listInfo.get(2);
String modified = "Modified: " + listInfo.get(3);
String delete = "Delete";
String edit = "Edit";
final String[] items = new String[] { created, modified, numItems,
delete, edit };
alert.setTitle(listTitle);
alert.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 3:
if (deleteList(position)) {
//listview.invalidate();
//Item itemToRemove = m_parts.remove(position);
//m_adapter.remove(itemToRemove);
//m_adapter.remove(toRemove);
//m_adapter.notifyDataSetInvalidated(); <-- These are all things I've tried
//m_adapter.clear(); in various combinations
//m_adapter.remove(position);
Item toRemove = m_adapter.getItem(position);
m_parts.remove(toRemove); //or, m_parts.remove(position);<-This is what should work
m_adapter.notifyDataSetChanged();
loadAdapter();
// runOnUiThread(new Runnable() {
// public void run() {
// m_adapter.notifyDataSetChanged(); <--I've tried a thread approach
// }
// });
}
break;
case 4:
Intent i = new Intent(ActivityMain.this,
ShowARegularList.class);
i.putExtra("list_id", (position + 1) + "");
startActivity(i);
break;
}
}
});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
which, in case 3 changes the database with
// Delete single list item data
public boolean deleteList(int id) {
id++;
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put("_id", id);
database.delete("list_data", "_id =" + id, null);
database.close();
// text = text.removeElementStr();
// itemCount--;
return true;
}
The above works to remove an item from the list, and closes the gap visually. But, when clicking on the "old" spot from which the item was removed (which raises a new intent to edit the selected item), an exception is raised in the new activity on querying the db (last line, 97 in logcat):
final Integer thisListID = Integer.parseInt(listIDstr);
final DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getReadableDatabase();
Cursor cursor = database.query("list_data", new String[] { "listTitle",
"listContent", "dateCreated", "dateModified" }, "_id = " + thisListID
+ "", null, null, null, null);
ArrayList<String> listInfo = new ArrayList<String>();
if (cursor != null && cursor.moveToFirst()) {
listInfo.add(cursor.getString(cursor.getColumnIndex("listTitle")));
listInfo.add(cursor.getString(cursor.getColumnIndex("listContent")));
listInfo.add(cursor.getString(cursor.getColumnIndex("dateCreated")));
listInfo.add(cursor.getString(cursor.getColumnIndex("dateModified")));
}
cursor.close();
strListContent = listInfo.get(1).trim();
with logcat
java.lang.RuntimeException: Unable to start activity...
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2083)
at android.app.ActivityThread.access$600(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1233)
...
at com.baked.listanywhere.ShowARegularList.onCreate(ShowARegularList.java:97)
The list items with index less than the deleted one are fine; those with greater index are one off in their contents. I suspect an error in logic on my part in the query, querying an index that is no longer there...but it seems I should be able to redraw the list and have an index list that mirrors the database. What I would truly like to do is extinguish any memory of the list and then refill it, but I can't seem to do this...any help would be much appreciated!
Well, as no one is chiming in, I've resolved the issue by querying
Cursor cursor = database.rawQuery("SELECT * FROM list_data ORDER BY _id LIMIT 1 OFFSET '"+ thisListID +"'", null);
thanks to Wojtek at this question. And, yes,
case 3:
if (deleteList(position)) {
Item toRemove = m_adapter.getItem(position);
m_parts.remove(toRemove);
m_adapter.notifyDataSetInvalidated();
loadAdapter();
break;
}
was working fine, even though I could have sworn that was the issue!
hey i have created a listview and using custom ArrayListAdapter and overridding the getView() method. i have a save button to save data from listview items which are checked . as they contain checkbox. Now the problem is when i save data using getchildCount method to loop each item(Row,Child) it only traverse to the visible items. if i use getCount() method it gives NullPointerexception as it is not considering the items which are not visible . i know i have to use my adapter to do all this but how???????????
this is my class using adapter adapter--------------
package com.bmi.cal.hitesh;
public class BreakFast extends Activity {
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
db.close();
}
float cal_needed=0;
public int counter =0,listItemCount=0,flag=1;
TextView tv_cal_count;
CheckBox check;
public ListView list;
ContentValues values = new ContentValues();
SQLiteDatabase db;
List<Employer> data = new ArrayList<Employer>();
Cursor cur,cur2;
String type, title,form,descr,tv_cal_str;
int calories;
private Button done;
private TextView tv_cal_needed;
private String cust;
int temp_diet_id[]= new int[234];
//final String CREATE_TABLE= "CREATE TABLE IF NOT EXISTS Bfast_table (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "diet TEXT,calories INTEGER,type INTEGER);";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String MYPREFS = "mySharedPreferences";
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,0);
list= (ListView)findViewById(R.id.list);
done = (Button)findViewById(R.id.button1);
tv_cal_count = (TextView)findViewById(R.id.tv_cal_count);
tv_cal_needed = (TextView)findViewById(R.id.tv_calories);
check = (CheckBox)findViewById(R.id.checkBox1);
db = openOrCreateDatabase("bmi.db",SQLiteDatabase.CREATE_IF_NECESSARY , null );
db.setVersion(1);
db.setLocale(Locale.getDefault());
cust = mySharedPreferences.getString("txt_cust", null);
db.setLockingEnabled(false);
db.execSQL("CREATE TABLE IF NOT EXISTS cust_diet(" + "cd_id INTEGER PRIMARY KEY AUTOINCREMENT," + "cust_id Integer,diet_id INTEGER,cd_validity DATE);");
try {
cur = db.query("tbl_diet",null,"type=?",new String[] {"Breakfast"}, null,null, null);
cur.moveToFirst();
while(!cur.isAfterLast())
{
title = cur.getString(1);
descr = cur.getString(2);
form = cur.getString(6);
type = cur.getString(5);
calories = cur.getInt(3);
data.add(new Employer(title,"Calories : " + calories,"("+descr+")",form));
cur.moveToNext();
}
list.setAdapter(new EmployerArrayAdapter(this, data));
cur.close();
} catch (Exception u) {
u.printStackTrace();
}
done.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int flag = 1;
listItemCount = list.getCount();
// TODO Auto-generated method stub
System.out.println(cust+"aaaaaaaaaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaaaaaaa"+list.getCount());
cur = db.query("user_bmi",null,"cust_id=?",new String[]{cust}, null,null, null);
System.out.println(cur.getCount()+"aaaaaaaaaaaaaaaa");
cur.moveToFirst();
cal_needed = (Float.parseFloat(cur.getString(9)))*(0.25f);
cur.close();
System.out.println(cust+"bbbbbbb");
tv_cal_needed.setText("you must not exceed "+ cal_needed +" calories");
tv_cal_count.setText("calories of your selected diets are as follows : ");
for(int i=0; i<listItemCount; i++)
{ TextView tv_name= (TextView) ((View)list.getChildAt(i)).findViewById(R.id.textViewName);
TextView tv_calorie= (TextView) ((View)list.getChildAt(i)).findViewById(R.id.textViewAddress);
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
{ tv_cal_str = tv_name.getText().toString();
cur = db.query("tbl_diet",null,"diet_title=?",new String[] {tv_cal_str}, null,null, null);
cur.moveToFirst();
temp_diet_id[counter]= cur.getInt(0);;
counter++;
tv_cal_count.append(tv_calorie.getText()+".");
System.out.println(cust+"cccccccc"+temp_diet_id[counter-1]);
System.out.println("not saved sill"+counter+"11111111111111111111111");
String temp_cal= tv_calorie.getText().toString().substring(11);
System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee11111111111111111111111");
float temp_calorie = Float.parseFloat(temp_cal);
System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee222222222222222222222222");
if(temp_calorie>cal_needed)
{ System.out.println("eeeeeeeeeeeeeeeeeeeeeee3333333333333333333333333");
System.out.println(cust+"dddddddddd");
flag=0;
}
}
cur.close();
}
System.out.println("not saved sill"+counter+"22222222222222222222");
if(counter<=3 && counter>=1)
{
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
final int temp_count = counter;
System.out.println("not saved sill"+counter+"3333333333333333333333");
if(flag==1){
AlertDialog.Builder builder = new AlertDialog.Builder(BreakFast.this);
builder.setMessage("Do you want to save your BreakFast?")
.setCancelable(false)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.out.println("not saved sill"+temp_count+"3333333333333333333333");
for(int i=0; i<temp_count; i++)
{
cur2 = db.query("user_bmi",null,"cust_id=? and bmi_active=?",new String[]{cust,"1"}, null,null, null);
cur2.moveToFirst();
System.out.println("not saved sill");
values.put("diet_id",temp_diet_id[i]);
values.put("cd_validity",cur2.getString(5));
values.put("cust_id",cust); System.out.println("saved");
db.insert("cust_diet", null, values);
cur.close();
cur2.close();
}
tv_cal_count.setText("Your BreakFast has been saved");
tv_cal_needed.setText(null);
done.setVisibility(View.INVISIBLE); }
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
dialog.cancel();
tv_cal_count.setText(null);
}
});
AlertDialog alert = builder.create();
alert.show();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(BreakFast.this);
builder.setMessage("please select diet which do not exceed "+cal_needed+" calories!!!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
tv_cal_count.setText(null);
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
counter=0;
}
else
{
tv_cal_count.setText(null);
Dialog mesg = new Dialog(BreakFast.this);
TextView text = new TextView(BreakFast.this);
if(counter==0)
text.setText("plzz select some items but not more then three!!!");
else
text.setText("can't select more then three");
mesg.setContentView(text);
mesg.show();
counter=0;
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
}
}
});
}
Use try catch block and post the stack trace.