Android java.lang.IllegalStateException on ListView - java

I use ListActivity with SpecialAdapter that show some log information.
I do not use background thread but I get an error when scroll list:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class ru.FoxGSM.ui.DebugActivity$SpecialAdapter)]
Please, help me.
(FoxLog is static class that get log information, perhaps from another thread. But in list a want show FoxLog snapshot)
public class DebugActivity extends ListActivity {
private class SpecialAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public SpecialAdapter(Context context) {
super();
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return FoxLog.count();
}
public long getItemId(int index) {
return index;
}
public Object getItem(int index) {
return FoxLog.get(FoxLog.count()-index-1);
}
// Get the type of View
public View getView(int position, View convertView, ViewGroup parent) {
TextView text;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.debug_list, null);
text = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(text);
} else
text = (TextView) convertView.getTag();
String s = (String) getItem(position);
if (s==null)
return convertView;
text.setText(s);
boolean isError = false;
if (s!=null && s.length()>0) {
String prefix = s.substring(0, 1);
if (prefix.equals("E") || prefix.equals("W"))
isError = true;
}
if (isError)
text.setBackgroundResource(R.color.red);
else
text.setBackgroundDrawable(null);
return convertView;
}
}
private void RefreshData() {
FoxLog.ReInit(this);
SpecialAdapter adapter = (SpecialAdapter)this.getListAdapter();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debug);
FoxLog.ReInit(this);
SpecialAdapter adapter = new SpecialAdapter(this);
setListAdapter(adapter);
Button mExit = (Button)findViewById(R.id.exit);
mExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}

Related

Can't put an ArrayList in a ListView inside a CustomAdapter in Android Studio

I'm having a problem understanding how to finish this part of my code.
It's an app that searches a list of games with the help of an API.
Everything is working so far so good right now, but one final thing.
In the code, first of all I have a simple activity with an edit_text, a button and an empty list view that it is called "lv_listofgames".
Then, when I press the "search" button, I fill the "lv_listofgames" with a series of rows formed by an imageview, a listView called "list_item_text" and a button.
To this point everything is okay it seems.
Then I should just fill the "list_item_text" inside the "lv_listofgames" with the contents of an arraylist but I just can't make it happen. I tried in many ways but I'm stuck. I even tried using 2 adapters but the app crashed everytime or the "list_item_text" remained empty.
The arrayList is something like: [game_title='Name', release_date='date', platform=platform]
I seem so close to the solution but I just can't figure it out how to accomplish that. Im going crazy :(
tl;dr: problem: when I press the "search" button the arrayList content doesn't appear in the ListView "list_item_text".
Here is the code, tell me if something is wrong, thanks:
public class MainActovity extends AppCompatActivity {
EditText et_searchName;
Button btn_search;
ListView lv_listofgames;
ListView lv;
final GamesDataService gameDataService = new GamesDataService(MainActovity.this);
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
et_searchName = findViewById(R.id.et_searchName);
btn_search = findViewById(R.id.btn_search);
lv_listofgames= findViewById(R.id.lv_listofgames);
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gameDataService.getGameName(et_searchName.getText().toString(), new GamesDataService.searchGamesResponse() {
#Override
public void onError(String message) {
Toast.makeText(MainActovity.this, "Error", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(List<GamesReportModel> gamesReportModels) {
List<GamesReportModel> newName = gamesReportModels;
List<String> stringsList = new ArrayList<>(newName.size());
for (Object object : newName) {
stringsList.add(Objects.toString(object, null));
}
System.out.println("stringsList:" + stringsList);
lv = (ListView) findViewById(R.id.lv_listofnames);
MyListAdapter adapter = new MyListAdapter(MainActovity.this, R.layout.details, stringsList);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
}
});
}
class MyListAdapter extends ArrayAdapter<String> {
private int layout;
public MyListAdapter(#NonNull Context context, int resource, #NonNull List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
MainActovity.ViewHolder mainViewHolder = null;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
MainActovity.ViewHolder viewHolder = new MainActovity.ViewHolder();
viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.list_item_thumbnail);
viewHolder.title = (ListView) convertView.findViewById(R.id.list_item_text);
viewHolder.button = (Button) convertView.findViewById(R.id.list_item_btn);
convertView.setTag(viewHolder);
viewHolder.button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
else {
mainViewHolder = (MainActovity.ViewHolder) convertView.getTag();
}
return convertView;
}
}
public class ViewHolder {
ImageView thumbnail;
ListView title;
Button button;
}
}
GamesReportModel:
public class GamesReportModel {
private String game_title;
private String release_date;
private String platform;
public GamesReportModel(String game_title, String release_date, String platform) {
this.game_title = game_title;
this.release_date = release_date;
this.platform = platform;
}
public GamesReportModel() {
}
#Override
public String toString() {
return "game_title='" + game_title + '\'' +
", release_date='" + release_date + '\'' +
", platform=" + platform;
}
public String getGame_title() {
return game_title;
}
public void setGame_title(String game_title) {
this.game_title = game_title;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
}
There are two things you need to change in your code to get the desired effect.
In your row view layout (R.layout.details), replace the ListView with a TextView since you are just trying to show text for a given row (not a nested list inside each row). Then update the view holder to hold the correct view type as well
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_text);
//...
public class ViewHolder {
ImageView thumbnail;
TextView title;
Button button;
}
In the adapter's getView method you have to actually set the text to show for that row. You never set the text to show anywhere, which is why your rows are blank. That should look like this:
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
MainActovity.ViewHolder mainViewHolder = null;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
MainActovity.ViewHolder viewHolder = new MainActovity.ViewHolder();
viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.list_item_thumbnail);
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_text);
viewHolder.button = (Button) convertView.findViewById(R.id.list_item_btn);
convertView.setTag(viewHolder);
}
else {
mainViewHolder = (MainActovity.ViewHolder) convertView.getTag();
}
// Here, you need to set what values to show for this row - this
// is why your list is empty/blank
mainViewHolder.title.setText((String)getItem(position));
return convertView;
}

How do I send the text of the ListView item that was clicked to my new activity?

I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.

setAdapter in recyclerView cannot be applied

So I followed an online tutorial to have a sort of gallery app. The pictures are shown inside a GridView but I needed to change it into a recyclerview. When I do that though I get that error and my adapter doesn't seem to work with the recyclerview. Here is my adapter code:
class AlbumAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap< String, String >> data;
public AlbumAdapter(Activity a, ArrayList < HashMap < String, String >> d) {
activity = a;
data = d;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
AlbumViewHolder holder = null;
if (convertView == null) {
holder = new AlbumViewHolder();
convertView = LayoutInflater.from(activity).inflate(
R.layout.album_row, parent, false);
holder.galleryImage = (ImageView) convertView.findViewById(R.id.galleryImage);
holder.gallery_count = (TextView) convertView.findViewById(R.id.gallery_count);
holder.gallery_title = (TextView) convertView.findViewById(R.id.gallery_title);
convertView.setTag(holder);
} else {
holder = (AlbumViewHolder) convertView.getTag();
}
holder.galleryImage.setId(position);
holder.gallery_count.setId(position);
holder.gallery_title.setId(position);
HashMap < String, String > song = new HashMap < String, String > ();
song = data.get(position);
try {
holder.gallery_title.setText(song.get(Function.KEY_ALBUM));
holder.gallery_count.setText(song.get(Function.KEY_COUNT));
Glide.with(activity)
.load(new File(song.get(Function.KEY_PATH))) // Uri of the picture
.into(holder.galleryImage);
} catch (Exception e) {}
return convertView;
}
}
class AlbumViewHolder {
ImageView galleryImage;
TextView gallery_count, gallery_title;
}
And this is some of the code from the activity in which I set my adapter:
#Override
protected void onPostExecute(String xml) {
AlbumAdapter adapter = new AlbumAdapter(ProfileActivity.this, albumList);
galleryGridView.setAdapter(adapter);
galleryGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
Intent intent = new Intent(ProfileActivity.this, AlbumActivity.class);
intent.putExtra("name", albumList.get(+position).get(Function.KEY_ALBUM));
startActivity(intent);
}
});
}
This is the error I'm currently getting:
Error message
I basically want to fix the adapter so that it works inside a recyclerview.
You have to create RecyclerView.Adapter to work with RecyclerView. It's bit different that BaseAdapter. Let me give you example of how to implement this.
public class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.ViewHolder> {
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.album_row, viewGroup, false);
return new AlbumAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
holder.galleryImage.setId(position);
holder.gallery_count.setId(position);
holder.gallery_title.setId(position);
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView galleryImage;
TextView gallery_count, gallery_title;
public ViewHolder(View v) {
galleryImage = v.findViewById(R.id.galleryImage);
gallery_count =v.findViewById(R.id.gallery_count);
gallery_title = v.findViewById(R.id.gallery_title);
}
}
}

How to keep custom listview items when they are out of screen?

I am trying to design a menu like this:
It almost works, however there is a problem. The menu works fine at start, but after scrolling down and up again, the items are gone and downloaded again and it takes a little time. Is there a way to set a number of elements to create at start and keep them from disappearing?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
Possibly you can implement lazy loading with some sort of caching of images or whatever you are downloading...
You say the images are donwloaded, i assume that the images are coming from internet. Implement a custom cache for http download or download and store the images in one place before you use

Android custom list view data is not updating while using shared preference

I am trying to get the value from shared preference and display it in customized list view. But the problem is list view is not getting updated with second value, means first time it's perfectly working fine but second time it overwrites the first value or may be it is opening another screen and displaying over there.
I want to add all the shared preferences data in list view one by one. please help me to solve this. Following is my code.
ListModel.java
public class ListModel {
private String Title = "";
private String Description = "";
/*********** Set Methods ******************/
public void setTitle(String Title) {
this.Title = Title;
}
public void setDescription(String Description) {
this.Description = Description;
}
/*********** Get Methods ****************/
public String getTitle() {
return this.Title;
}
public String getDescription() {
return this.Description;
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList<?> data;
private static LayoutInflater inflater = null;
public Resources res;
ListModel tempValues = null;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList<?> d, Resources resLocal) {
/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView textViewTitle;
public TextView textViewDescr;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.displaydata, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.textViewTitle = (TextView) vi.findViewById(R.id.title);
holder.textViewDescr = (TextView) vi.findViewById(R.id.description);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
if (data.size() <= 0) {
holder.textViewTitle.setText("No Data");
} else {
/***** Get each Model object from Arraylist ********/
tempValues = null;
tempValues = (ListModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.textViewTitle.setText(tempValues.getTitle());
holder.textViewDescr.setText(tempValues.getDescription());
// holder.image.setImageResource(res.getIdentifier(
// "com.androidexample.customlistview:drawable/"
// + tempValues.getImage(), null, null));
/******** Set Item Click Listner for LayoutInflater for each row *******/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked=====");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener {
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View arg0) {
Assignment sct = (Assignment) activity;
sct.onItemClick(mPosition);
}
}
}
Class Which reads shared preferencedata
public class Assignment extends Activity {
ListView list;
ImageView imageView;
CustomAdapter adapter;
public Assignment CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment);
imageView = (ImageView) findViewById(R.id.createassignment);
list = (ListView) findViewById(R.id.displaydata);
CustomListView = this;
setListData();
Resources res = getResources();
adapter = new CustomAdapter(CustomListView, CustomListViewValuesArr,
res);
list.setAdapter(adapter);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Assignment.this,
Assignment_Create.class);
startActivity(intent);
}
});
}
public void setListData() {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setTitle("Title : "
+ PreferenceConnector.readString(this,
PreferenceConnector.TITLE, null));
sched.setDescription("Description : "
+ PreferenceConnector.readString(this,
PreferenceConnector.DESC, null));
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
}
public void onItemClick(int mPosition) {
ListModel tempValues = (ListModel) CustomListViewValuesArr
.get(mPosition);
Toast.makeText(
CustomListView,
"" + tempValues.getTitle() + "" + ""
+ tempValues.getDescription(), Toast.LENGTH_LONG)
.show();
}
}
This function shows how i am writing data in shared Preference
public void sharedPrefernces() {
if (Code.title != null)
PreferenceConnector.writeString(this, PreferenceConnector.TITLE,
Code.title);
if (Code.description != null)
PreferenceConnector.writeString(this, PreferenceConnector.DESC,
Code.description);
}
In setListData() you're only adding 1 item to the Adapter, so the listView is not going to have the 2nd item shown.

Categories