Android: Refresh ArrayAdapter on resume - android

I am trying to create a refesh function for my main page. I have searched many site but i can't seem to find a (for me) acccesseble exaple. I am loading information from a sQLLite database. When i use my add activity and i return to the MainScreen activity the item i have added do not appear. How could i refresh this data the moment de activity is resumed.
Any help is welcome, thx in advance.
public ListView whiskeylist;
String[] DataArryWhiskey;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start db view of whiskey
DBConfig info = new DBConfig(this);
info.open();
DataArryWhiskey = info.getDataInArray();
info.close();
whiskeylist = (ListView) findViewById(R.id.listofWhiskey);
whiskeylist.setOnItemClickListener(this);
whiskeylist.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DataArryWhiskey));
}// end onCreate
On The advice of Adil i change the code to
public ListView whiskeylist;
String[] DataArryWhiskey;
ListAdapter Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start db view of whiskey
DBConfig info = new DBConfig(this);
info.open();
DataArryWhiskey = info.getDataInArray();
info.close();
whiskeylist = (ListView) findViewById(R.id.listofWhiskey);
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DataArryWhiskey);
whiskeylist.setAdapter(Adapter);
// End db view of whiskey
}// end onCreate
#Override
public void onResume()
{
super.onResume();
DBConfig info = new DBConfig(this);
info.open();
DataArryWhiskey = info.getDataInArray();
info.close();
Adapter.notifyDataSetChanged(); // refresh adapter
}
however i get a error on notifyDataSetChanged "the method notifyDataSetChanged is undefined for the type ListAdapter" <- fixed it by changing the ListAdapter to ArrayAdapter but the app still crashes.

//made changes in your oncreate method, see below
DBConfig info;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start db view of whiskey
info = new DBConfig(this);
whiskeylist = (ListView) findViewById(R.id.listofWhiskey);
whiskeylist.setOnItemClickListener(this);
}// end onCreate
another method give below, call this method from on ActivityResult(), but before doing that ensure that
the field you added with another activity also saved into database.
call show Data() from onActivityResult method or from onResume()
private void showData()
{
info.open();
DataArryWhiskey = info.getDataInArray();
info.close();
whiskeylist.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DataArryWhiskey));
}

Get a class level variable of ArrayAdapter adapter; and initialize it like this way:
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DataArryWhiskey);
hiskeylist.setAdapter(adapter);
and inside onResume() do like this way.
public void onResume()
{
super.onResume();
info.open();
DataArryWhiskey = info.getDataInArray();
info.close();
adapter.notifyDataSetChanged(); // refresh adapter
}
My Recommendation:
Since you are getting your values from database, use SimpleCursorAdapter instead of ArrayAdapter. which will do lots of other work also for you.
Here is a tutorial how to use SimpleCursorAdapter

You can try using adapter.clear(); before adding items.

Related

update listview on save

I have a code where I add all TODOs to the adapter, like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
adapter = new TODOAdapter(this, TODO.listAll(TODO.class));
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
When add I new TODO, I do this
private void createTodo(String s) {
TODOWorker.createTodo(s);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Your TODO was saved!", Toast.LENGTH_LONG).show();
}
but my listview is not beign updated...what am I missing?
My best guess after looking at your code is before calling notifyDatasetChanged() on your adapter you need to set the new list on the adapter. So when a new TODO is created add it to the list and update the list that the adapter is working with. Then call the notifyDatasetChanged()
So let's say your adapter has a List<TODO> mDataList then you need to have a function like this
public void setData(List<TODO> updatedList) {
mDataList = new ArrayList<>(updatedList);
notifyDataSetChanged();
}
and change your createToDo() to this
private void createToDo(String s) {
TODOWorker.createTodo(s);
adapter.setData(TODO.listAll(TODO.class));
Toast.makeText(getApplicationContext(), "Your TODO was saved!", Toast.LENGTH_LONG).show();
}
Hope this helps. I am assuming of course that your TODOWorker is not updating the list that the adapter is working with.
When you create Adapter, it is backed by List, which you create by TODO.listAll(TODO.class)
You have to make sure that new item is inserted into this List before adapter.notifyDataSetChanged() called.

Handler in android giving error

I am using handler in my code to update the app on every specific time interval.
For that i written follwing code:
public class Messages extends Activity {
protected Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String id = intent.getStringExtra(MainActivity.EXTRA_ID);
String[] lst = null;
ListView lm=(ListView)findViewById(R.id.listView1);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome " + message);
handler.postDelayed(new UpdateTask(),500);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.messages, menu);
return true;
}
class UpdateTask implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
setContentView(R.layout.activity_messages);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String id = intent.getStringExtra(MainActivity.EXTRA_ID);
String[] lst = null;
ListView lm=(ListView)findViewById(R.id.listView1);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome " + message);
CallSoap cs=new CallSoap();
lst=cs.GetMessage(id);
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lst);
lm.setAdapter(adpt);
handler.postDelayed(this, 500);
}
}
}
But it is giving me error on :
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lst);
Text: Constructor ArrayAdapter is undefined.
Please help me.
ArrayAdapter<String> adpt = new ArrayAdapter<String>(Messages.this, android.R.layout.simple_list_item_1,lst);
But i don't understand why you put all those inside a handler.
Also i see setContentView twice for the same activity which is not a good design.
If you need to update the listview update the underlying data that populates listview and call notifyDataSetchanged on your adapter.
Also setContentView and intializing views everytime is not a good idead
you shold change this
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lst);
by
ArrayAdapter<String> adpt = new ArrayAdapter<String>(YourActivity.this, android.R.layout.simple_list_item_1,lst);
Relace "this" reference in the constructor with ActivityName.this.
Changing
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lst);
to
ArrayAdapter<String> adpt = new ArrayAdapter<String>(Messages.this, android.R.layout.simple_list_item_1,lst);
should work.
That being said, if you are looking for periodic update only, then the above code need not be necessary to be called all the times.
Instead simply calling adapter.notifyDataSetChanged(); should do the work,.

Refresh ListView after updating in another Activity

I have two simple Activities -
Activity1: ListView from an Array
Activity2: EditText for editing the clicked row in Activity1
When I edit the value in Activity2 and returning to Activity1, the ListView doesn't reload the new value.
I want to refresh the ListView when I return from Activity2 or resume Activity1 or something that will update the list.
My code:
static ArrayAdapter<String> dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Loading the values to list array
String[][] fulllist = loadArrays();
String[] list = new String[fulllist.length];
for(int i = 0; i<fulllist.length; i++) {
list[i] = fulllist[i][1];
}
// --------------------------------
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
list);
setListAdapter(dataAdapter);
}
#Override
public void onResume() {
super.onResume();
// Loading the values to list array
String[][] fulllist = loadArrays();
String[] list = new String[fulllist.length];
for(int i = 0; i<fulllist.length; i++) {
list[i] = fulllist[i][1];
}
// --------------------------------
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
list);
dataAdapter.notifyDataSetChanged();
}
loadArrays() is just method that converts from SharedPreferences to String Array. Activity2 saves the new data in SharedPreferences and than Activity1 can read it (with the new data).
If I return to the "main activity" (it is not Activity1) and than come back to Activity1 - the new data is shown, but I want this data will be updated when I return from Activity2 immediately.
loadArrays() method: pastebin.com/MHwNC0jK
Thanking you in advance!
On clicking the item in your first Activity, start your second Activity with startActivityForResult()
And then in Second Activity, after entering in EditText, probably there is a button. And in onClick of that button call,
intent.putExtra("edittextvalue", findViewById(R.id.edittext).getText().toString());
setResult(RESULT_OK, intent);
finish();
Now you come back to your first Activity and here you have to implement onActivityResult() callback. You can extract data from that intent's extras and set that respective item in your array and call notifyDataSetChanged().
This is ideally how you should be doing it.
If you want more info on how to use startActivityForResult() try this link - http://manisivapuram.blogspot.in/2011/06/how-to-use-startactivityforresult.html
1) Get reference ListView
mListView = (ListView)findViewById(R.id.auto_listview);
2) Create adapter One more time with changed values
MyAdapter myAdapter = new MyAdapter(getApplicationContext(),
R.layout.locations_list_item_layout,dataArray;
mListView.setAdapter(myAdapter);
setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int i, long l) {
myAdapter = new MyAdapter(getApplicationContext(),
//pass changed values vlues array R.layout.locations_list_item_layout,dataArray;
mListView.setAdapter(myAdapter);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Declare fulllist as Globle Variable and used static arraylist .

how to display a arraylist in listview?

Can anybody help me to display the following arraylist in a listview.I am struck with this.
[E000199, E000100, ER008,EW999,EQ333,EQ111,E9089,E1001,E777,E999,E0123,E00054,E0032,E0016,E0016, E009,
E008,E007,E005,E003,E001].
This is the response I get from a webservice.When I try to display it in a listview in another activity I am getting error as
java.lang.IllegalStateException: System services not available to Activities before onCreate().
pls help me.this is my code in second activity.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.listView1);
}
public void sendList(ArrayList<String> list) {
// TODO Auto-generated method stub
this.emp_list=list;
System.out.println("^^^^^^"+emp_list);
adapt = new ArrayAdapter<String>(this,R.layout.list,R.id.title,emp_list);
listview.setAdapter(adapt);
setContentView(R.layout.viewlist);
}
For your problem you must you custom adapter.
LINK for your reference
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewlist);
listview = (ListView) findViewById(R.id.listView1);
adapt = new ArrayAdapter<String>(this,R.layout.list,R.id.title,emp_list);
listview.setAdapter(adapt);
}
public void sendList(ArrayList<String> list) {
// TODO Auto-generated method stub
this.emp_list.clear();
this.emp_list.addAll( list );
adapt.notifyDataChanged();
}
Yes it is...because you are trying to display ListView and setAdapter before setContentView() method. Instead it should be as below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewlist); // It should be here //1st solution
listview = (ListView) findViewById(R.id.listView1);
sendList(list); // you forgot to call this method
}
public void sendList(ArrayList<String> list) {
// TODO Auto-generated method stub
this.emp_list=list;
System.out.println("^^^^^^"+emp_list);
adapt = new ArrayAdapter<String>(this,R.layout.list,R.id.title,emp_list);
listview.setAdapter(adapt);
}
Just Keep SetContentView(R.layout.viewlist); after super Statement.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewlist);
listview = (ListView) findViewById(R.id.listView1);
adapt = new ArrayAdapter<String>(this,R.layout.list,R.id.title,emp_list);
listview.setAdapter(adapt);
}
as listview.setAdapter(adapt); will directly Set the Value.
before you'll get a view,you must call setContentView.so you can do like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewlist); //add this
listview = (ListView) findViewById(R.id.listView1);
}
public void sendList(ArrayList<String> list) {
// TODO Auto-generated method stub
this.emp_list=list;
System.out.println("^^^^^^"+emp_list);
adapt = new ArrayAdapter<String>(this,R.layout.list,R.id.title,emp_list);
listview.setAdapter(adapt);
}

tabhost and listview sqlite database cause leak

I tried to find a solution to my problem already in google and here on stackoverflow, however nothing could answer my question.
I use a sqlite database to populate a listview. Also on top of the listview there is a tabhost where one can switch to a different activity. When switching to that activity and back then back again to the listview a leak is found. However whatever try there is apparently a leak. Can someone help me in finding that leak?
Here is the listview activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
contactlist = (ListView) findViewById(R.id.list);
entry.open();
c = entry.getData();
startManagingCursor(c);
String[] from = new String[] {"_id", "firstname", "lastname"};
int[] to = new int[] {R.id.iVPI, R.id.tvfirstName, R.id.tvlastName};
adapter = new MySimpleCursorAdapter(this, R.layout.contacts_list_item, c, from, to);
contactlist.setAdapter(adapter);
contactlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(contacts.this, contactsdetails.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("ID", cursor.getInt(cursor.getColumnIndex("_id")));
c.close();
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
entry.open();
}
protected void onPause() {
super.onPause();
entry.close();
}
protected void onStop() {
super.onStop();
entry.close();
}
protected void onDestroy() {
super.onDestroy();
entry.close();
}
The tabhostactivity is quite simple:
th = getTabHost();
th.addTab(th.newTabSpec("tag1").setIndicator("Contacts", getResources().getDrawable(R.drawable.book)).setContent(new Intent(this, contacts.class)));
th.addTab(th.newTabSpec("tag2").setIndicator("Profile", getResources().getDrawable(R.drawable.mailbox)).setContent(new Intent(this, incomingcallpopup.class)));
th.setCurrentTab(0);
Can anyone spot the leak?
Thanks in advance for you help.
Can you get source of contacts.class and incomingcallpopup.class?
The problem is that you try to connect to db twice when switch between tabs (you don't close db connection in the first tab).
I had this problem in my project when I had 2 SlqHelpers to 1 db and use them at the same time.

Categories

Resources