As title says, it get this exception from the code I pasted below. I tried to make it work both with the uncommented code and also with the commented part insted of the IF block just before it.
The error I get is: java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor which I don't understand, since the item in the listview should exactly be a String! Any idea?
public class ListScoutActivity extends ListActivity {
private DBHelper database;
private ListView listav;
private Cursor cursor;
ArrayList<String> stringlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_scout);
database = new DBHelper(getApplicationContext());
SQLiteDatabase db = database.getWritableDatabase();
listav = this.getListView();
listav.setVisibility(View.VISIBLE);
int codpartita;
String team;
cursor = db.rawQuery("SELECT _codpartita as _id, team, FROM partita ORDER BY _codpartita DESC", null);
cursor.moveToFirst();
while ( !cursor.isAfterLast() ) {
team = cursor.getString(cursor.getColumnIndex("team"));
stringlist.add(team);
cursor.moveToNext();
}
cursor.moveToFirst();
if (cursor.getCount()>0) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(ListScoutActivity.this,
android.R.layout.simple_list_item_1, cursor, new String[]{"team"},
new int[]{android.R.id.text1}, 0);
listav.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListScoutActivity.this,
// android.R.layout.simple_list_item_1, android.R.id.text1, stringlist);
// listav.setAdapter(adapter);
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor)l.getItemAtPosition(position);
//.. other things..
}
I display a listview with database rows. When a row is clicked, a dialog pops up with the (editable) items of that row.
public class ViewDataActivity extends ListActivity {
private ListView listView;
HashMap<Integer, String> results = new HashMap<Integer, String>();;
ArrayList<String> dataValues = new ArrayList<String>();
ArrayList<Integer> keyValues = new ArrayList<Integer>();
ArrayAdapter<String> arrayAdapter;
Integer itemKey;
String itemValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
results = (HashMap<Integer, String>) getIntent().getSerializableExtra(MainActivity.EXTRA_MESSAGE);
for(Map.Entry<Integer, String> entry: results.entrySet()) {
keyValues.add(entry.getKey());
dataValues.add(entry.getValue());
}
// Display items
listView = getListView();
View v = getLayoutInflater().inflate(R.layout.list_view_header, null);
listView.addHeaderView(v);
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
dataValues );
listView.setAdapter(arrayAdapter);
// Make Items clickable
listView.setChoiceMode(CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("List position clicked", String.valueOf(listView.getCheckedItemPosition()));
itemKey = keyValues.get(listView.getCheckedItemPosition()-1);
itemValue = dataValues.get(listView.getCheckedItemPosition()-1);
showInputBox(itemKey, itemValue);
}
});
}
// Show dialog with values
public void showInputBox(final Integer itemKey, String listItemValue){
final Dialog dialog=new Dialog(ViewDataActivity.this);
dialog.setTitle("Edit Item");
dialog.setContentView(R.layout.list_item_edit_popup);
TextView txtMessage=(TextView)dialog.findViewById(R.id.txtmessage);
txtMessage.setText("Update");
txtMessage.setTextColor(Color.parseColor("#ff2222"));
String[] listItemValues = listItemValue.split(",");
final String liCategory = listItemValues[2];
final String liDescription = listItemValues[3];
final String liAmount = listItemValues[4];
EditText editText1=(EditText)dialog.findViewById(R.id.txtinput1);
EditText editText2=(EditText)dialog.findViewById(R.id.txtinput2);
EditText editText3=(EditText)dialog.findViewById(R.id.txtinput3);
editText1.setText(liCategory);
editText2.setText(liDescription);
editText3.setText(liAmount);
Button bt=(Button)dialog.findViewById(R.id.btdone);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Write new Values
dbHelper.updateExpense(itemKey, liCategory, liDescription, liAmount);
// Refresh ListView
arrayAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
}
}
But when i update the values in the dialog and click the button, the dialog closes but the row isn't updated in the database. The update being executed is this:
public boolean updateExpense(Integer id, String category, String description, String amount) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_CATEGORY, category);
contentValues.put(COLUMN_DESCRIPTION, description);
contentValues.put(COLUMN_AMOUNT, amount);
// Returns 1 but no update
Log.d("DBUpdate", String.valueOf(db.update(TABLE_NAME, contentValues, COLUMN_ID + " = ? ", new String[] { Integer.toString(id) } )));
return true;
}
What am i missing?
Hard to tell as clearly the code you're showing us is incomplete, but if you're using database.beginTransaction();, make sure you use database.setTransactionSuccessful(); after your update call. Also don't forget database.endTransaction(); in your finally statement.
I have created listview with two textfield and one toggle button.i am able to get text from the listview when put toggle button on,but problem is when i close my application or i scroll the listview my toggle button state is changed.
the below is my full code :
public class MainActivity extends Activity {
ArrayList<String> call_log_no;
ArrayList<String> call_log_name;
String strStatus = "";
//Array of booleans to store toggle button status
public boolean[] status;
StringBuffer sb;
String phNum,cname,details;
MatrixCursor mMatrixCursor;
ArrayList<String> choiceList;
ListView lvCountries;
HashMap<String,Object> hm;
int pos;
// Each row in the list stores country name and its status
List<HashMap<String,Object>> aList
= new ArrayList<HashMap<String,Object>> ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
/** Restore from the previous state if exists */
if(savedInstanceState!=null){
status = savedInstanceState.getBooleanArray("status");
}
call_log_no = new ArrayList<String>();
call_log_name = new ArrayList<String>();
choiceList = new ArrayList<String>();
lvCountries = (ListView) findViewById(R.id.lv_countries);
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?>
lv, View item, int position, long id) {
ListView lView = (ListView) lv;
SimpleAdapter adapter = (SimpleAdapter) lView.getAdapter();
HashMap<String,Object> hm = (HashMap) adapter.getItem(position);
/** The clicked Item in the ListView */
RelativeLayout rLayout = (RelativeLayout) item;
/** Getting the toggle button corresponding to the clicked item */
ToggleButton tgl = (ToggleButton) rLayout.getChildAt(0);
String strStatus = "";
if(tgl.isChecked()){
tgl.setChecked(false);
strStatus = "Off";
status[position]=false;
}else{
tgl.setChecked(true);
strStatus = "On";
status[position]=true;
}
Toast.makeText(getBaseContext(), (String) hm.get("no") + " : " + strStatus, Toast.LENGTH_SHORT).show();
}
};
lvCountries.setOnItemClickListener(itemClickListener);
// Each row in the list stores country name and its status
List<HashMap<String,Object>> aList = new ArrayList<HashMap<String,Object>>();
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","details"} );
getCallDetails();
//Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringExists = (call_log_no.contains(homePhone)||(call_log_no.contains("+91"+homePhone)));
if(isStringExists==true)
{
}
else{
call_log_no.add(homePhone);
call_log_name.add(displayName);
}
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringE = (call_log_no.contains(mobilePhone)||(call_log_no.contains("+91"+mobilePhone)));
if(isStringE==true)
{
}
else{
call_log_no.add(mobilePhone);
call_log_name.add(displayName);
}
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringExis = (call_log_no.contains(workPhone)||(call_log_no.contains("+91"+workPhone)));
if(isStringExis==true)
{
}
else{
call_log_no.add(workPhone);
call_log_name.add(displayName);
}
break;
}
}
}while(dataCursor.moveToNext());
String details = "";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
status = new boolean[call_log_name.size()];
for(int i = 0,j = 0,k=0; i < call_log_name.size() ; i++,j++,k++)
{
HashMap<String, Object> hm = new HashMap<String,Object>();
status[k]=false;
// choiceList.add("\nName: "+call_log_name.get(i)+"\nPhone Number: " + call_log_no.get(j));
hm.put("no", call_log_no.get(i));
hm.put("txt", call_log_name.get(j));
hm.put("stat",status[k]);
aList.add(hm);
}
// Keys used in Hashmap
String[] from = {"txt","no","stat" };
// Ids of views in listview_layout
int[] to = {R.id.tv_item,R.id.tv_no, R.id.tgl_status};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.activity_main, from, to);
lvCountries.setAdapter(adapter);
}
}
please help me.. and i want to save the all toggle button state and the text corresponding to the data
It is better to approach the listview as follows.
Create a class to hold the listview data. for example :
public class Countries{
private String mName;
private boolean mChecked;
public Countries{
}
public String getName(){
return mName;
}
public void setName(String name){
mName = name;
}
public boolean isChecked(){
return mChecked;
}
public void setChecked(boolean checked){
mChecked = checked;
}
}
Create a custom array adapter for the listview.
public class CountriesListAdapter extends ArrayAdapter {
public CountriesListAdapter(Context context, int resource, ArrayList<Countries>countriesList) {
super(context, resource, countriesList);
}
#Override
public View getView(int position, View cell, ViewGroup parent) {
//Get an instance of our cell holder
Holder holder;
//If this is the first time the Listview is going to display this cell
//Create new Holder
if(cell == null)
{
Holder = new Holder();
//Get layout inflater service to inject our view in the listview cell
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cell = vi.inflate(R.layout.your_xml_layout, parent, false);
holder.textView = (TextView)cell.findViewById(R.id.textview);
holder.toggleButton = (ToggleButton)cell.findViewById(R.id.toggleButton);
//Attach the new cell to the listview row
cell.setTag(holder);
}else{
//The row was already created before to get it from the row
holder = (Holder)cell.getTag();
}
//Get item at current position
Countries country = getItem(position);
//Set row data
holder.textview.setText(country.getName());
holder.toggleButton.setChecked(country.isChecked());
//return the cell to the listview to dosplay
return cell;
}
//this holder class will be filled from the layout xml and attached
//to the row as a tag object
private class Holder{
TextView textView;
ToggleButton toggleButton;
}
}
After your create a new array of countries items in your activity or fragment.
Then initiate a new adapter pass the countries list.
set adapter to the listview.
now on the click listener you get the Country object at the given position.
With this method you can scroll and the toggled button remained toggled.
I have 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 ListView needs to be updated to reflect this, but it doesn't show the updates unless the application is restarted.
I've tried calling, notifyDataSetChanged() and startActivityForResult() in my onResume() method but that didn't work. What method should I use to accomplish updating the ListView in my current code?
I understand a SimpleCursorAdapter may be used and I have tried to implement that code with no success. I'm a novice and need actual code to understand what needs to be done.
public class LoginList extends Activity implements OnClickListener, OnItemClickListener {
private ListView loginList;
private Button webLogin;
private ListAdapter loginListAdapter;
private ArrayList<LoginDetails> loginArrayList;
#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();
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
loginList.setAdapter(loginListAdapter);
}
#Override
public void onItemClick(AdapterView<?> arg0 , View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Selected ID :" + 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());
loginBundle.putString("clickedNotes",clickedObject.getlNotes());
updateDeleteLoginInfo.putExtras(loginBundle);
startActivityForResult(updateDeleteLoginInfo, 0);
}
}
This is exactly what a Loader is great for. I suggest you create a SimpleCursorAdapter to bind the DB to the UI (ListView in this case), a ContentProvider to interface with the DB, and a CursorLoader to monitor the DB for changes, and update the UI when necessary. The Loader will handle all DB changes and update your ListView by simply updating your adapter. It seems like a lot of work up front, but is incredibly powerful once configured, and will work through the entire Android lifecycle.
These tutorials should be helpful:
https://developer.android.com/training/load-data-background/index.html
http://www.vogella.com/articles/AndroidSQLite/article.html#background_loader
https://github.com/browep/AndroidCursorLoaderTutorial
Edit
private ArrayList<LoginDetails> loginArrayList = new ArrayList<LoginDetails>();;
#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);
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,loginArrayList );
loginList.setAdapter(loginListAdapter);
populateList();
}
#Override
public void onClick (View v) {
Intent webLoginIntent = new Intent (this, LoginPlusActivity.class);
startActivity(webLoginIntent);
}
public void populateList () {
loginListAdapter.clear();
loginArrayList.clear();
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);
}
loginListAdapter.notifyDatasetChanged();
sqliteDatabase.close();
}
You are losing reference to your listview that why your list isn't updating...
Do this modification in your code.
1. Initialize your ArrayList when it is declared(globally).
ArrayList loginArrayList = new ArrayList<LoginDetails>();
Directly set assign list to Adapter (onCreate)
loginListAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, loginArrayList);
call populateList() in onCreate().
In your populateList() instead of Adding data to the new list add to existing list associated with your Adapter i.e loginArrayList
if your list is completely new call adapter.clear() and loginArrayList.clear() in the populateList() before adding data to the loginArrayList.
After Adding the data to the loginArrayList call adapter.notifyDataSetChanged()
This should Work...
My recomendation.
Do not do a loop to load your list. If it is a simple list with all
strings. Try to use a SimpleCursorAdapter and will make your app
faster and shorter code.
Once you update the database, then what you do is query the DB to get the Cursor, and to the Adapter use .swapCursor(newCursor). That will update your list while maintaining the scroll position.
If you're manually creating the backing data of the adapter (in this case you're using an ArrayAdapter - which is completely acceptable in a lot of cases) then when the database changes you need to requery the database, recreate your dataset, change the backing dataset of your adapter, and tell the list that the dataset has changed.
A way to accomplish this may be to broadcast an intent that lets your activity know to perform the steps mentioned above (by catching that intent with a BroadcastReceiver).
Here's my sample code for editing the each row as well as the database of the listview I hope it will helps you
First create I create an Adapter name "ListAdapterItem.java"
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ListAdapterItem extends BaseAdapter {
private ArrayList<HashMap<String, Object>> list;
private Context context;
private RelativeLayout ll;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private TextView label,label_id;
String name,id;
public ListAdapterItem (Context context,ArrayList<HashMap<String, Object>> list) {
this.list = list;
this.context = context;
}
public void setSelectedPosition(int pos) {
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition() {
return selectedPos;
}
public View getView(int position, View convertView, ViewGroup parent) {
ll = (RelativeLayout) LayoutInflater.from(this.context).inflate(R.layout.data_list_item, null);
// get text view
label = (TextView) ll.findViewById(R.id.txtview_country_name);
label_id=(TextView) ll.findViewById(R.id.txtview_id);
id=list.get(position).get("Id").toString();
name = list.get(position).get("Name").toString();
label.setText(name);
label_id.setText(id);
return ll;
}
public int getCount() {
return this.list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
And here's my data_list_item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txtview_id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="8dp"
android:layout_marginRight="2dp"
android:textColor="#android:color/black"
android:textSize="22dp"
android:visibility="invisible"/>
<TextView
android:id="#+id/txtview_country_name"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="8dp"
android:layout_marginRight="2dp"
android:textColor="#android:color/black"
android:textSize="22dp" />
</RelativeLayout>
And the main Class "Main.java"
public class Main extends Activity implements OnClickListener {
String name;
SQLiteDatabase db;
Cursor cursor;
private ProgressDialog progressDialog;
public ListAdapterItem list_adapter;
private ArrayList<HashMap<String, Object>> lst_data;
private HashMap<String, Object> hm;
private ListView listview;
private String list_id;
private int counter_id,selectedPosition;
private View selectedView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
lst_data = new ArrayList<HashMap<String, Object>>();
listview = (ListView) findViewById(R.id.list);
new FetchDB().execute();
}
private class FetchDB extends AsyncTask<String, Void,ArrayList<HashMap<String, Object>>> {
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Main.this,"Fetching Data", "Loading,Please wait...", true);
}
protected ArrayList<HashMap<String, Object>> doInBackground(String... lstStrings)throws IllegalArgumentException {
try {
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
cursor = db.rawQuery("SELECT * FROM person WHERE Id <> ''",null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
hm = new HashMap<String, Object>();
hm.put("Id",cursor.getInt(cursor.getColumnIndex("Id")));
hm.put("Name", cursor.getString(cursor.getColumnIndex("Name")));
lst_data.add(hm);
} while (cursor.moveToNext());
}// end of cursor.moveToFirst()
cursor.close();
}
} catch (Exception e) {
e.getMessage();
}
db.close();// database close
return lst_data;
}// end of doInbackgournd
#Override
protected void onPostExecute(ArrayList<HashMap<String, Object>> result) {
progressDialog.dismiss();
list_adapter = new ListAdapterItem(Main.this,result);
listview.setAdapter(list_adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
list_adapter.setSelectedPosition(arg2);
selectedPosition = arg2;
selectedView = arg1;
list_id=((TextView) selectedView.findViewById(R.id.txtview_id)).getText().toString();
}
});
}
}// end of FetchDBTask
private class SaveTask extends AsyncTask<String, Void,ArrayList<HashMap<String, Object>>> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Main.this,"Saving Data", "Loading,Please wait...", true);
}
protected ArrayList<HashMap<String, Object>> doInBackground(String... arg0)throws IllegalArgumentException {
counter_id++;
name = editext_name.getText().toString();
hm = new HashMap<String, Object>();
hm.put("Id",counter_id);
hm.put("Name",name);
lst_data.add(hm);
saveDB();
return lst_data;
}// end of doInbackgournd
protected void onPostExecute(ArrayList<HashMap<String, Object>> result) {
progressDialog.dismiss();
list_adapter = new ListAdapterItem(Main.this,result);
listview.setAdapter(list_adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
list_adapter.setSelectedPosition(arg2);
selectedPosition = arg2;
selectedView = arg1;
list_id=((TextView) selectedView.findViewById(R.id.txtview_id)).getText().toString();
}
});
}
}// end of saveTask
public void saveDB(){
String sql;
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
// create table if not e exist
db.execSQL("CREATE TABLE IF NOT EXISTS person(Name VARCHAR ,Id INT(3));");
sql = "SELECT * FROM person WHERE Id="+list_id; //selected or click row in list item
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
String sqlUpdate = "UPDATE person SET Name=? WHERE Id="+db_id;
db.execSQL(sqlUpdate, new Object[] {db_name});
cursor.close();
db.close();// database close
} else {// empty insert
String sqlInsert = "INSERT INTO person VALUES (?,"+null+")";
db.execSQL(sqlInsert, new Object[] {db_name,db_address,db_phone,db_email,db_license,db_comments,db_company,db_policy,db_phone_insurance,vehc_year,vehc_make,vehc_model,vehc_license,vehc_vinnum,vehc_color,db_position });
cursor.close();
db.close();// database close
}
}
//Edit by row
private class EditData extends AsyncTask<String, Void,ArrayList<HashMap<String, Object>>> {
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Main.this,"Saving Data", "Loading Please wait...", true);
}
protected ArrayList<HashMap<String, Object>> doInBackground(String... id)throws IllegalArgumentException {
name = editext_name.getText().toString();
hm = new HashMap<String, Object>();
hm.put("Id",counter_id);
hm.put("Name",name);
lst_data.set(selectedPosition, hm); //specific row update
list_id=Integer.parseInt(edit_counter);
saveDB();
return lst_data;
}// end of doInbackgournd
protected void onPostExecute(ArrayList<HashMap<String, Object>> result) {
progressDialog.dismiss();
list_adapter = new ListAdapterItem(Main.this,result);
listview.setAdapter(list_adapter);
}
}
}
And the main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="#android:color/transparent"
android:cacheColorHint="#00000000"
android:dividerHeight="2dp"
android:paddingTop="8dp"
android:transcriptMode="normal" />
</LinearLayout>
Specify your id every listrow in the listview hope that this answer your question
I think that in your populate() method before the while block you should call loginListAdapter.notifyDataSetChanged() and loginListAdapter.clear();
That would clear the adapter and notice to it of the new list of data.
The block will look like this:
loginListAdapter.notifyDataSetChanged();
loginListAdapter.clear();
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);
}
I Just edited because the order you call the notify and clear wasn't correct. The clear must occur after the notify, is just what i got from my experience, unless the adapter wouldn't redraw the list.
Try this code
in public area add variable : List<String> arrayList = new ArrayList<String>();
and in onCreate() add this :
arrayList = populateList();
//then add variable in adapter like this
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList );
in onResume() this code:
#Override
protected void onResume() {
super.onResume();
loginArrayList.clear();
arrayList.clear();
arrayList = populateList();
loginListAdapter.notifyDataSetChanged()
}
Let us know if you solved it.
I want to be able to fetch a row from a list view and populate textViews in a different activity. I want to be able to do this onclick of an item with the list view..
public class CBFilter extends Activity {
ListView RecipeNames;
Cursor cursor;
SimpleCursorAdapter adapter;
CBDataBaseHelper data;
SQLiteDatabase data2;
TextView RecipeText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecipeNames = (ListView) findViewById(R.id.List1);
RecipeNames.setTextFilterEnabled(true);
RecipeText = (TextView) findViewById(R.id.recipeText);
adapter = new SimpleCursorAdapter (this, 0, cursor, null, null);
data = new CBDataBaseHelper(this);
data.open();
cursor = data.query();
startManagingCursor(cursor);
String[] from = {CBDataBaseHelper.KEY_NAME};
int[] to = { R.id.recipeText};
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
RecipeNames.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void CreateNew(View view){
Intent myIntent = new Intent(this, CBCreate.class);
startActivity(myIntent);
}
}
How can i convert this code in order to achieve the required functionality.. thanks Stefan
try like this
public void onListItemClick(ListView parent, View v, int position, long id) {
String string = from[position]); // this depends on your Adapter ...
Intent i = new Intent(CheckData.this,ShowData.class);
i.putExtra("SELECTED", string);
startActivity(i);
i got it from this link , it will be use full for you :
Use of SQLite