update delete listview items - android

I have a listview that when clicked opens up but doesnt display detailed information about that list view item. The data for the listview is entered in by a class into a sqlite datase and pulled from a sqlite database by another class. Not sure where I went wrong with the class the should pul the data when a list viewitem is clicked. I do not have enough pont to post imaged of the related xml files but the onClick methods are below
Listview:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "clicked on :" + arg2, Toast.LENGTH_SHORT).show();
Intent updateDeleteLoginInfo = new Intent (this, UpdateDeleteLoginList.class);
LoginDetails clickedObject = loginArrayList.get(arg2);
Bundle loginBundle = new Bundle();
loginBundle.putString("clickedwebSite",clickedObject.getsName());
loginBundle.putString("clickedwebAddress",clickedObject.getwUrl());
loginBundle.putString("clickeduserName",clickedObject.getuName());
loginBundle.putString("clickedpassWord",clickedObject.getpWord());
updateDeleteLoginInfo.putExtras(loginBundle);
startActivity(updateDeleteLoginInfo);
Update Class:
#Override
public void onClick(View v){
loginSitetext = sName.getText().toString();
loginAddresstext = wUrl.getText().toString();
loginUsertext = uName.getText().toString();
loginpassWordtext = pWord.getText().toString();
LoginDetails loginDetails = new LoginDetails();
loginDetails.setsName(bundledWebSite);
loginDetails.setwUrl(bundledWebAddress);
loginDetails.setuName(bundledUserName);
loginDetails.setpWord(bundledPassWord);
if(v.getId()==R.id.rucBttn){
finish();
}else if(v.getId()==R.id.ruuBttn){
updateLoginDetails(loginDetails);
}else if(v.getId()==R.id.rudBttn){
deleteLoginDetails(loginDetails);
}
}
private void updateLoginDetails(LoginDetails loginDetails){
dataStore androidOpenDbHelper = new dataStore(this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(dataStore.COLUMN_NAME_SITE, loginSitetext);
contentValues.put(dataStore.COLUMN_NAME_ADDRESS, loginAddresstext);
contentValues.put(dataStore.COLUMN_NAME_USERNAME, loginUsertext);
contentValues.put(dataStore.COLUMN_NAME_PASSWORD, loginpassWordtext);
String[] whereClauseArgument = new String[1];
whereClauseArgument[0]= loginDetails.getsName();
System.out.println("whereClauseArgument[0] is :" + whereClauseArgument[0]);
sqliteDatabase.update(dataStore.TABLE_NAME_INFOTABLE, contentValues, dataStore.COLUMN_NAME_SITE+"=?", whereClauseArgument);
sqliteDatabase.close();
finish();
}
private void deleteLoginDetails(LoginDetails deleteLoginDetails){
dataStore androidOpenDbHelper = new dataStore(this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelper.getWritableDatabase();
String[] whereClauseArgument = new String[1];
whereClauseArgument[0] = deleteLoginDetails.getsName();
sqliteDatabase.delete(dataStore.TABLE_NAME_INFOTABLE,dataStore.COLUMN_NAME_SITE+"=?", whereClauseArgument);
sqliteDatabase.close();
finish();

you can use notifyDataSetChanged() function to achive updating the listView.
or
assign a new adapter evrytime you update list that needs updating.

Found the 'C' in whereClauseArgument in another class was not capatalized. After capitalizing it every thing worked as it should.

Related

Error when deleting an item from listview in android

I wanted to learn how to use sqlite in android so I used the following code from a tutorials website but when I ran it , If I delete the first entry in the listview the next entry would give
android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 0 in the DisplayContact class.
So I wanted to know how to fix it, I don't know if the problem is in the listview or the arraylist.
Thanks in advance.
Here is the code which shows the error
Bundle extras = getIntent().getExtras();
if (extras != null)
{
int Value = extras.getInt("id");
if (Value > 0)
{
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
if (rs != null && rs.getCount() > 0)
{
rs.moveToFirst();
}
String dat = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_DATE));
String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
if (!rs.isClosed())
{
rs.close();
}
And here is the code to delete an entry
case R.id.Delete_Contact: AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
} )
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{ }
}
);
AlertDialog d =builder.create();
d.setTitle("Are you sure?");
d.show();
return true;
default:
This is the logcat output 05-20
12:59:33.953 E/AndroidRuntime(25513): Process: com.myelse.sqlcontacts, PID: 25513
05-20 12:59:33.953 E/AndroidRuntime(25513): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myelse.sqlcontacts/com.myelse.sqlcontacts.DisplayContact}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
05-20 12:59:33.953 E/AndroidRuntime(25513): at com.myelse.sqlcontacts.DisplayContact.onCreate(DisplayContact.java:51)
Edit: This is the code for the arraylist and arrayadapter in the mainactivity
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mydb = new DBHelper(this);
ArrayList arraylist = mydb.getAllContacts();
arrayadapter= new ArrayAdapter (this, android.R.layout.simple_list_item_1 ,arraylist);
arrayadapter.notifyDataSetChanged();
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayadapter);
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
int id_to_search=arg2+1;
Toast.makeText(getApplicationContext(), id_to_search + "" , Toast.LENGTH_SHORT).show();
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_to_search);
Intent intent = new Intent(getApplicationContext(), DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
arrayadapter.notifyDataSetChanged();
}
}
);
}
The problem is in the line:
Cursor rs = mydb.getData(Value);
mydb.getData(Value) will return only one row, where the "id" = Value
So, when you delete this single row, the cursor returns an IndexOutOfBoundsException.
One possible solution is to modify your getData function as follows:
public Cursor getData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts, null );
return res;
}
Thanks to #parth mehta for the responce , but the only solution that I found to preserve order after deleting an entry was to copy all records to a temporary table without the id column and then moving them back to the original table after each delete.
Using insert into table 1 () select from table2.
Thanks.
Please add Notifydatsetchange() after delete event

Android: arrayAdapter throwing null pointer exception?

I'm having some issues with an array adapter.
this is what is in my lessonNotesList class:
mydb = new DBHelper(this);
//Creating an ArrayList of contacts data
ArrayList array_list = mydb.getAllLessonNotes();
//Creating an Array Adapter to manipulate the contacts data into a ListView
ArrayAdapter arrayAdapter = new ArrayAdapter(this,R.layout.list_layout, array_list);
//Adding the contacts to the list view.
lessonNote = (ListView)findViewById(R.id.listView1);
lessonNote.setAdapter(arrayAdapter);
//Setting an onClickListener to process the user's actions
lessonNote.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
//Prepare the data from the ListView item to be passed to new activity
//arg2 is increased by one as its a zero based index but the contacts table in the database works of a base index of 1
int id_To_Search = VALUE;
//Bundle extras = getIntent().getExtras();
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Log.d("Id is ^&*: ", String.valueOf(id_To_Search));
//Create a new intent to open the DisplayContact activity
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.LessonNotes.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
DBHelper class:
public ArrayList getAllLessonNotes()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from "+TABLE_LESSON_NOTES, null);
res.moveToFirst();
while(res.isAfterLast() == false)
{
array_list.add(res.getString(res.getColumnIndex(DATE)));
res.moveToNext();
}
return array_list;
}
The code crashes with a NULL pointer exception here:
lessonNote.setAdapter(arrayAdapter);
Any ideas why this is happening?
I've tried debugging and the debugger is telling me that the arrayAdatper contains 1 entry as it should
I have nearly the same code for a different page and it's working 100% fine..
Any suggestions would be welcome!
Thanks
Are you sure about that line ?
lessonNote = (ListView)findViewById(R.id.listView1);
It seems that in your layout XML, no view have "listView1" id.

SQLite Database does't update listview item and inserts new instead

When item of listview is clicked, it gets opened in another activity which has edittext. After editing an item, when I save it, item does not get updated in the listview but it inserts a new entry in listview.
How can I update existing item without inserting new?
Here is my code
Activity: TRList.class
ArrayList<HashMap<String, String>> items = new ArrayList<>();
List<TRListFormat> list = trDb.getAllReminders();
for (TRListFormat val : list) {
HashMap<String, String> map = new HashMap<>();
map.put("title",val.getTitle());
map.put("description", val.getDes());
map.put("date", val.getDate());
map.put("time", val.getTime());
items.add(map);
}
adapter = new SimpleAdapter(this, items, R.layout.tr_list_format,
new String[] { "title", "description", "date", "time" },
new int[] {R.id.tbr_title, R.id.tbr_des, R.id.tbr_date, R.id.tbr_time });
lv = (ListView)findViewById(R.id.tbr_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(TRList.this, TRTimeReminder.class);
intent.putExtra("remId", (int)id);
startActivity(intent);
}
});
When listView item is clicked, it opens another activity
TRTimeReminder.class I have set save button in menu
case R.id.menu_tbr_done:
String title = edTitle.getText().toString();
String des = edDes.getText().toString();
String time = timeView.getText().toString();
String date = dateView.getText().toString();
Bundle extras = getIntent().getExtras();
if(extras != null) {
int value = extras.getInt("remId");
if (value > 0) {
trDb.updateReminder(new TRListFormat(value, title, des, date, time));
}
}
else{
trDb.addReminder(new TRListFormat(title, des, date, time));
}
Intent i = new Intent(getApplicationContext(), TRList.class);
startActivity(i);
edTitle.getText().clear();
edDes.getText().clear();
dateView.setText(currDate);
timeView.setText(currTime);
return true;
TRDBHelper.class
//Add new reminder
void addReminder(TRListFormat format){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, format.getTitle());
values.put(COLUMN_DES, format.getDes());
values.put(COLUMN_DATE, format.getDate());
values.put(COLUMN_TIME, format.getTime());
db.insert(TABLE_NAME, null, values);
db.close();
}
//Update single reminder
public void updateReminder(TRListFormat format){
SQLiteDatabase db = this.getWritableDatabase();
int id = format.getId();
ContentValues values = new ContentValues();
values.put(COLUMN_ID, format.getId());
values.put(COLUMN_TITLE, format.getTitle());
values.put(COLUMN_DES, format.getDes());
values.put(COLUMN_DATE, format.getDate());
values.put(COLUMN_TIME, format.getTime());
db.update(TABLE_NAME, values, COLUMN_ID+ " = " +id, null);
db.close();
}
I think there's problem with your adapter. There are 2 possible issues.
Data of adapter are not updated. You're saying opposite, new value is added to ListView. Are you really sure?
You haven't called your adapter's method notifyDataSetChanged() after you've changed values.

Android ListView sqlite update Refresh

My current application has a Listview which pulls and displays data from a sqlite DB. Data in the first column of the DB is displayed in the listview and when clicked, an activity starts showing the rest of the column associated with the first column. When the data is edited, the DB updates but the listview does not show the updates unless the application is restarted. I am trying to implement startActivityForResult() in my onResume method but am unsuccessful. I am trying to refresh my listview after the DB has been updated. How can I accomplish this.
ListView Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_listview);
loginList = (ListView)
findViewById(R.id.loginlist);
loginList.setOnItemClickListener(this);
webLogin = (Button)
findViewById(R.id.button3);
webLogin.setOnClickListener(this);
loginArrayList = new ArrayList<LoginDetails>();
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
loginList.setAdapter(loginListAdapter);
}
#Override
public void onClick (View v) {
Intent webLoginIntent = new Intent (this, LoginPlusActivity.class);
startActivity(webLoginIntent);
}
public List<String> populateList (){
List<String> webNameList = new ArrayList<String>();
dataStore openHelperClass = new dataStore (this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(dataStore.TABLE_NAME_INFOTABLE, null, null, null, null, null, dataStore.COLUMN_NAME_SITE, null);
startManagingCursor(cursor);
while (cursor.moveToNext()){
String sName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_SITE));
String wUrl = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_ADDRESS));
String uName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_USERNAME));
String pWord = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_PASSWORD));
String lNotes = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_NOTES));
LoginDetails lpDetails = new LoginDetails();
lpDetails.setsName(sName);
lpDetails.setwUrl(wUrl);
lpDetails.setuName(uName);
lpDetails.setpWord(pWord);
lpDetails.setlNotes(lNotes);
loginArrayList.add(lpDetails);
webNameList.add(sName);
}
sqliteDatabase.close();
return webNameList;
}
#Override
protected void onResume() {
super.onResume();
Intent i = new Intent(LoginList.this, UpdateDeleteLoginList.class);
LoginList.this.startActivityForResult(i, 1);
loginList.setAdapter(loginListAdapter);
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
loginList.setAdapter(loginListAdapter);
}
update Activity:
#Override
public void onClick(View v){
loginSitetext = sName.getText().toString();
loginAddresstext = wUrl.getText().toString();
loginUsertext = uName.getText().toString();
loginpassWordtext = pWord.getText().toString();
loginNotestext = lNotes.getText().toString();
LoginDetails loginDetails = new LoginDetails();
loginDetails.setsName(bundledWebSite);
loginDetails.setwUrl(bundledWebAddress);
loginDetails.setuName(bundledUserName);
loginDetails.setpWord(bundledPassWord);
loginDetails.setlNotes(bundledNotes);
if(v.getId()==R.id.rucBttn){
finish();
}else if(v.getId()==R.id.ruuBttn){
updateLoginDetails(loginDetails);
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}else if(v.getId()==R.id.rudBttn){
deleteLoginDetails(loginDetails);
}
}
private void updateLoginDetails(LoginDetails loginDetails){
dataStore androidOpenDbHelper = new dataStore(this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(dataStore.COLUMN_NAME_SITE, loginSitetext);
contentValues.put(dataStore.COLUMN_NAME_ADDRESS, loginAddresstext);
contentValues.put(dataStore.COLUMN_NAME_USERNAME, loginUsertext);
contentValues.put(dataStore.COLUMN_NAME_PASSWORD, loginpassWordtext);
contentValues.put(dataStore.COLUMN_NAME_NOTES, loginNotestext);
String[] whereClauseArgument = new String[1];
whereClauseArgument[0] = loginDetails.getsName();
System.out.println("whereClauseArgument[0] is :" + whereClauseArgument[0]);
sqliteDatabase.update(dataStore.TABLE_NAME_INFOTABLE, contentValues, dataStore.COLUMN_NAME_SITE+"=?", whereClauseArgument);
sqliteDatabase.close();
finish();
You can refresh the listview by calling notifyDataSetUpdated on the adapter. That forces the entire listview to refresh, and getView will be called on all views refreshing it.
The problem you're asking about has a standard solution, that is (unfortunately) more complex than a few lines of code. It is accomplished by a combination of Content Provider, Data Loader and Cursor Adapter.
I've put a little demo on GitHub that has a skeleton containing all the components and can be modified to accomplish what you need. It also handles one-pane / two-pane layouts on tablets (and newer phones as well).
Content provider is the module that serves as an interface to your database table and notifies your ListView about the changes, thus taking care of immediate refreshing of the list. Just grep for 'getContentResolver().notifyChange()' calls, these take care of refreshing your list. As long as you use Content Provider for all access to your data (CRUD - query,insert,delete,update,...), all your actions will be immediately reflected in the ListView.
There is a lot of info about this by Wolfram Rittmeyer, Lars Vogel, Alex Lockwood, ... if you want to get educated about the problem.
Good Luck

How to upgrade gridview in android using two threads with only one gridview in xml layout

I am having items in a gridview which where displayed from sqlite ..Now using another thread i am fetching data from json webservice and storing the data in sqlite now i want to display the updated items in the same grid view along with the existing items..
private void displayUpdate(String Bid) {
Log.w("Update cALL","Executing Update");
System.out.println("aeqw cursor that in display table value"+getid(Bid).getCount());
Cursor cursorx =getid(Bid);
int p=Integer.parseInt(Bid);
System.err.println("Recieving Bid to displayUpdate method"+p);
if (getid(Bid) != null)
{
while(cursorx.moveToFirst())
{
Log.e("Entering Loop", "WHILE EXECUTING");
String temp_id1 = cursorx.getString(0);
System.err.println("Name related to Bid to displayUpdate method"+temp_id1);
final String temp_name1 = cursorx.getString(1);
System.err.println("Name related to Bid to displayUpdate method"+temp_name1);
String temp_author1=cursorx.getString(2);
String temp_desc1=cursorx.getString(3);
byte[] temp_image1 = cursorx.getBlob(4);
String temp_rating1 = cursorx.getString(5);
String temp_price1 = cursorx.getString(6);
String temp_update1=cursorx.getString(7);
System.err.println("Name related to Bid to displayUpdate method"+temp_name1);
mapIdUp.add(temp_id1);
mapNameUp.add(temp_name1);
mapAuthorUp.add(temp_author1);
mapDescUp.add(temp_desc1);
mapRatingUp.add(temp_rating1);
mapPriceUp.add(temp_price1);
mapUp.add(temp_image1);
mapUpdatedUp.add(temp_update1);
Log.e("temp_id from the sqlite", temp_id1);
Log.i(temp_name1, temp_name1);
Log.i(temp_desc1, temp_desc1);
Log.i(temp_rating1, temp_rating1);
Log.e(temp_update1,temp_update1);
String[] captionArray1 = (String[]) mapNameUp.toArray(new String[mapNameUp.size()]);
ItemsAdapter itemsAdapter1 = new ItemsAdapter(
Bookicon.this, R.layout.item,captionArray1);
gridView1=(GridView)findViewById(R.id.list);
gridView1.setAdapter(itemsAdapter1);
itemsAdapter1.notifyDataSetChanged();
gridView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
break;
}
}
}
this method is called in the second thread to display the updated books ..
where are this method is used to display all the items in the sqlite table
private void getDataAndPopulate()
{
Log.w("hello","zyuk,");
Cursor cursor = getEvents("bcuk_book");
while (cursor.moveToNext())
{
String temp_id = cursor.getString(0);
final String temp_name = cursor.getString(1);
String temp_author=cursor.getString(2);
String temp_desc=cursor.getString(3);
byte[] temp_image = cursor.getBlob(4);
String temp_rating = cursor.getString(5);
String temp_price = cursor.getString(6);
String temp_update=cursor.getString(7);
mapId.add(temp_id);
mapName.add(temp_name);
mapAuthor.add(temp_author);
mapDesc.add(temp_desc);
mapRating.add(temp_rating);
mapPrice.add(temp_price);
map.add(temp_image);
mapUpdated.add(temp_update);
Log.e("temp_id from the sqlite", temp_id);
Log.i(temp_name, temp_name);
Log.i(temp_desc, temp_desc);
Log.i(temp_rating, temp_rating);
Log.e(temp_update,temp_update);
String[] captionArray = (String[]) mapName.toArray(new String[mapName.size()]);
ItemsAdapter itemsAdapter = new ItemsAdapter(
Bookicon.this, R.layout.item,captionArray);
gridView=(GridView)findViewById(R.id.list);
gridView.setAdapter(itemsAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
}
Issue is i am not able to display the updated one whereas it was showing already stored items ..
If let us assume there are items like 1,2,3,4,5 when i update new item with 6 i.e one record it is displaying first item i.e 1. If update 2 records then it displaying only first two records..
How to solve this issue

Categories

Resources