Android ListView only shows data after app restart - android

I'm trying to fill a list view with data i'm receiving from and odata service in json format. The data is already fetched and can be accessed with getIODataEntry().
I'm appending the respective values to a string to see an output in LogCat and split the string afterwards to fill my listView with the single values.
ListView listView_CarrierCollection = null;
...
private void showData() {
Log.d("debug", "log 1");
String carrierCollection = "";
for(int i=0; i<getIODataEntry().size(); i++) {
carrierCollection += getIODataEntry().get(i).getPropertyValue("Carrname");
carrierCollection += ";";
}
Log.d("debug", carrierCollection);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(carrierCollection.split(";")));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.custom_textview, list);
listView_CarrierCollection.setAdapter(arrayAdapter);
Log.d("debug", "log 2");
}
everything works, but only after my devices' screen has turned off and has being turned on again or after i close and reopen the app. The logs instead are prompted instantly to logcat, but the listView only contains the data after reopening the app.
Am i missing something out? Every hint would be appreciated!
EDIT:
Finally got it to work - turned out it had nothing to do with the posted code above. I had some listeners, that were trying to update a TextField in a Fragment. It seems as if MyFragment.textfield.setText("test"); blocked any further operations in some way. Surrounding it with runOnUiThread(new Runnable(){ ... }) solved it for me and got the whole thing to work.
Nevertheless thank you for your ideas and help!

Late to the party but may help someone else in the future
In my case, I wasn't calling notifyDataSetChanged() when i was updating my mutable array list. Therefore it was only working when i was tuning sceen off and on again. But after calling notifyDataSetChanged() it worked as usual.
Hope it helps ;)

Related

Update a submenu item in a NavigationView populated with Realm Data

I am creating a submenu in a NavigationView that is populated with the last three projects the user has worked with.
RealmResults<Project> lastestProjectsReaml = mDB.where(Project.class).findAll().sort("pLastModification", Sort.DESCENDING);
ArrayList<String> recentProjects = new ArrayList<>();
for (int i = 0; i < 3; i++){
recentProjects.add(lastestProjectsReaml.get(i).getpName());
}
for (String value : lastestProjects){
recentProjectSubMenu.add(value)
}
My problem is that the list will not be updated if a new project is created or if one of the latest projects is deleted. Update the list with new projects is not a problem since I can do it manually every time the user creates one. However, when a project is deleted, I don't know how to deal with it since this operation is handled internally by the adapter and not in the activity.
Any idea how could overcome this?
Thanks in advance for your time.
After a couple of days breaking my mind to solve this, as soon as I posted the question, the solution came to my mind.
I simply added a changelistener to my RealmResults that will be triggered when adding/deleting projects.
RealmResults<Project> userProject = mDB.where(Project.class).findAll().sort("pLastModification", Sort.DESCENDING);
userProject.addChangeListener(new RealmChangeListener<RealmResults<Project>>() {
#Override
public void onChange(RealmResults<Project> element) {
setRecentProjectSubMenu(navigationView);
}
});
A small remark: within setRecentProjectSubMenu, the submenu has to be cleared. recentProjectSubMenu.clear();

Android listview refresh only once

I am really desperate, please help me.
In my main Activity I want to remove all items from the listview then add other data. I am able to delete the data and refresh the listview, but when I add new data, something strange happens. I insert the data in my Array. I call notifydatasetchanged on my adapter after every insertion. The adapter gets those items (I have confirmed this in debug mode). But the listview will not refresh. And now comes the VERY STRANGE thing: When I tap the back button on my device, the application quits (this part is ok), but for a moment before quitting it refreshes the listview with the correct data.
Here are some parts of my code:
For deleting the data I use:
newsArrayList = new ArrayList<NewsClass>();
Adapter = new NewsAdapter(this, newsArrayList);
lv.setAdapter(Adapter);
"lv" is my listview. The listview correctly loses all items and refreshes. I have also tried this:
newsArrayList.clear();
Adapter.notifyDataSetChanged();
Also worked like expected. Then I use a "for" loop to add new items to my array, where I have the following lines:
newsArrayList.add(news[i]);
Adapter.notifyDataSetChanged();
As I wrote, when running in debug mode, everything seems fine. I have spent all day working on this problem. I have read several posts about similar issues on stackoverflow, I even watched a video on youtube. I am calling everything from the main UI thread.
I can work around this problem by restarting my activity, but I want to do it better than that. I have tried invalidate and such things, but nothing helped. Please note the VERY STRANGE thing, I wrote...
I think, that I have to force the activity to redraw its views, or something like that, but even refreshDrawableState(); on my listview did not help.
Thank you in advance!
Basically If you want to clear list data then just call
newsArrayList.clear();
lv.setAdapter(null);
Again add what ever your data in ArrayList and set adapter
newsArrayList = new ArrayList<NewsClass>();
Adapter = new NewsAdapter(this, newsArrayList); // considering list with some elements
lv.setAdapter(Adapter);
If you are getting outofmemory error/exception then there is problem with your Adapter Class inside getView method

NullPointerException Inside AsyncTask

I want to populate listview with catalog names which are inside other specific catalog that my application is creating in other activities.
Here's the doInBackground method:
#Override
protected ArrayList<String> doInBackground(Void... arg0) {
ArrayList<String> wynik = new ArrayList<String>();
File katalog = new File(Environment.getExternalStorageDirectory().getPath()+"/DBConnector/Projekty/");
File[] projekty = katalog.listFiles();
for (File projekt : projekty) {
if (projekt.isDirectory()) {
wynik.add(projekt.getName());
}
}
return wynik;
}
It's throwing NullPointerException. As far as I know, even if there were no folders there it just should leave the ArrayList empty and pass it on (I'm using if(result.isEmpty()) later in onPostExecute to give info to user about that or actually populate listview if it's not empty - very similar code worked in other place, where I populated listview with data from resultset). Still, there are multiple folders there. I'm afraid I made some stupid mistake, but I just can't see it. I would appreciate some help.
EDIT: The thing that helped was restarting eclipse. Should have thought about it first though I still have no idea how it could have happened.
Without the logcat it's quite difficult to say for sure.
Are you sure you can access external storage? (Manifest Permission)
Is File Katalog a valid? or just null?
Is File[] projekty returning an empty array?
Use breakpoints and check those points above.

How can i check boxes from simple_list_item_multiple_choice via retrieving data from a sharedPreferences?

i'm pretty new to android-development and im trying to build a ListView with 8 items, that each have checkboxes. is set them up already, but i dont know how i can set one/several box beeing checked via retrieving key.value-pairs from a SharedPreferences.
i think im pretty close, but there is one or two lines of code missing :(
this my code in the onCreate-method:
lv = (ListView) findViewById(R.id.lvMain);
getPreferences(MODE_PRIVATE).edit().putString("Spiel4", "yes").commit();
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, lvItems));
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
for (int i=1;i<9;i++) {
tmpString = null;
tmpString = getPreferences(MODE_PRIVATE).getString("Spiel"+i,"");
if (tmpString.equals("yes")) {
// -----> MISSING LINE HERE <-----
Log.i(tag,"Spiel"+i+"-value is YES!");
}
}
p.s.: my first post, formatting tricked me :(
you can use
lv.setItemChecked(i, true);
add this line on missing line :)
Have you considered the PrefenceActivity or PreferenceFragement?
Take a look at:
http://developer.android.com/guide/topics/ui/settings.html
Another option is write your own Adapter, that is not hard too. Look that:
http://www.vogella.com/articles/AndroidListView/article.html#adapterown_custom

Android ListAdapter or Possibly ListView Updating Text at Runtime

Hello folkes I have this little problem for which I cannot find a suitable answer looking around the web and on these forums. Please don't direct me to articles in which people have requested list view text color changes at run time, as I read lots of them and not found one to help me out.
I have a simple ListView that displays an array of String objects via the use of a ListAdapter.
I need to update some of ListView Strings at run time, based on their contents. Using a global reference to the list adapter used in the lists views creation I can get the contents of each list view String using following code below.
However, in addition to retrieval I'd like to be able to modify each string in turn, then put it back in the same index position and have the list view reflect the changes. How?
for (int x = 0; x <= listAdapter.getCount();x++)
{
Object o = this.listAdapter.getItem(x);
if (o.getClass().getSimpleName().equals("String"))
{
String s = (String) o;
s = modifyString(s);
//s is the string I want to modify then put back in the same place.
}//end if
}//end for
As far as I know you cannot change the items in an Adapter - unless you are using a custom Adapter (by extending a BaseAdapter etc...)
So, I think you will have to:
make sure you Adapter's constructor takes in the data structure that holds your strings
make sure your data structure is global
make the changes in that data structure whenever you need to
call myAdapter.notifyDataSetChanged();
This will tell adapter that there were changes done in the list and listview should be recreated.
And after your listview is renewed you can even take the user back to the index by:
list.setSelection(positionWhereTheUserClicked);
I hope this helps, let me know if you need more code references.
Here is some code
private ArrayList<String> results = new ArrayList<String>(); //global
private BaseAdapter searchAdapter = new BaseAdapter (results, this); //global
private void updateResults(final ArrayList<String> updatedList){
results = updatedList;
final ListView list = (ListView)findViewById(R.id.search_results);
list.setAdapter(searchAdapter);
list.setOnItemClickListener(new ListView.OnItemClickListener(){
// implementation of what happens when you click on an item //
});
searchAdapter.notifyDataSetChanged();
}
This code works just fine on my end, I hope it helps.
Just stumbled on this problem and found a solution.
I'm using a
m_ListAdapter = new SimpleAdapter(this, m_List, R.layout.option_list_row, columns, renderTo);
Each item in my listView is a manu option causing a dialog to show, once data is received through the dialog, all I have to do is just create a new SimpleAdapter with an updated ArrayList that includes the new data, then just setAdapter to the new adapter.
The ListView will update instantly.

Categories

Resources