I want to load in a GridView a list of images saved in res->drawable->"a1.png"
In the activity where is the GridView I have a function which reads a JSON and return it as a JSON array.
For each object in the JSON array I create a new monsterobject(m) and set the variables (m.setName, m.setIcon).
All Itemobjects will be added to an Array of ItemObject and sent it to an adapter.
Here Adapter.class
package com.example.anonymous.mh4;
/**
* Created by Anonymous on 21/02/2018.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.reflect.Field;
public class MonsterAdapter extends BaseAdapter {
private final Context mContext;
private final Monster[] monsters;
// 1
public MonsterAdapter(Context context, Monster[] monsters) {
this.mContext = context;
this.monsters = monsters;
}
// 2
@Override
public int getCount() {
return monsters.length;
}
// 3
@Override
public long getItemId(int position) {
return 0;
}
// 4
@Override
public Object getItem(int position) {
return null;
}
// 5
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1
// 2
if (convertView == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(R.layout.listviewitemmonster, null);
}
// 3
final ImageView imageView = (ImageView)convertView.findViewById(R.id.imglayout);
final TextView nameTextView = (TextView)convertView.findViewById(R.id.namelayout);
// 4
final Monster m = monsters[position];
nameTextView.setText(m.getName());
imageView.setImageResource(getDrawableId(m.Icon()));
return convertView;
}
public int getDrawableId(String name){
try {
Field fld = R.drawable.class.getField(name);
return fld.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
Looks like if I use the function to get the id of the image using the name of my icon (obtained from the class --> obtained from de json) and set it to the imgview in my layout, my grid view is lagging in the app.
In case i use:
imageview.setImageDrawable(getResources().getDrawable(a1));;
Loads the same image for all monsters but the gridview isn't lagging. Obviously I want to put the correct image to all monsters without lagging.
I don't know if is because don't need to get the id or because only need to load the same image all the time.
Hope someone can help me to optimize this or give me some advice, sorry for my English.
All comments are welcome.