I get an error while creating a listview adapter - java

I would create some listview from my api json response, but I stuck with this LinkedTreeMap error in my code. Could anyone help me to solve this?
public class KategoriListAdapter extends BaseAdapter {
Context context;
ArrayList<Barang> barang;
public KategoriListAdapter(Context context, ArrayList<Barang> barang) {
this.context = context;
this.barang = barang;
}
#Override
public int getCount() {
return barang.size();
}
#Override
public Barang getItem(int i) {
return this.barang.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.custom_list_view_kategori, viewGroup, false);
}
TextView tvNama = (TextView) view.findViewById(R.id.tv_nama);
TextView tvHarga = (TextView) view.findViewById(R.id.tv_harga);
TextView tvUsername = (TextView) view.findViewById(R.id.tv_username);
Object getrow = this.barang.get(i);
LinkedTreeMap<Object, Object> rowmap = (LinkedTreeMap) getrow;
String nama = rowmap.get("nama").toString();
String harga = rowmap.get("harga").toString();
String username = rowmap.get("username").toString();
tvNama.setText(nama);
tvHarga.setText(harga);
tvUsername.setText(username);
return view;
}
}
public class Barang {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("nama")
#Expose
private String nama;
#SerializedName("harga")
#Expose
private String harga;
#SerializedName("gambar")
#Expose
private String gambar;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getGambar() {
return gambar;
}
public void setGambar(String gambar) {
this.gambar = gambar;
}
}
The log result while I run the activity is
java.lang.ClassCastException: com.example.barangkoz.model.Barang cannot be
cast to com.google.gson.internal.LinkedTreeMap
at com.example.barangkoz.activities.KategoriListAdapter.getView(KategoriListAdapter.java:57)`

You are passing ArrayList of "Barang" Object in you adapter constructor it means you already have a list of object Barang in your adapter and you can directly use it without casting to TreeMap.
In your getView method of adapter change this
Object getrow = this.barang.get(i);
to
Barang barang = barang.get(i);
it will give the Barang object at the position of i from the list of Barang.
and you can get the data from this object using the getters methods defined inside your object Barang like this.
String harga = barang.getHarga();
String nama = barang.getNama();
String userName = barang.getUsername();
and set it to your TextView or
You can directly set the data to TextView from Barang object (without doing extra step to setting it in variable before setting to TextView), like this
tvHarga.setText(barang.getHarga());
tvNama.setText(barang.getNama());
tvUsername.setText(barang.getUsername());

Replace
Object getrow = this.barang.get(i);
LinkedTreeMap<Object, Object> rowmap = (LinkedTreeMap) getrow;
String nama = rowmap.get("nama").toString();
String harga = rowmap.get("harga").toString();
String username = rowmap.get("username").toString();
With
Barang getrow = this.barang.get(i);
String nama = getrow.getName();
String harga = getrow.getHarga();
String username = getrow.getUsername();

Related

RecyclerView does not update ROOM Database although data exists

My Entity class looks like this:
#Entity
public class User {
public int getId() {
return id;
}
#NonNull
public ArrayList<String> getValues(){
return values;
}
#NonNull
public ArrayList<String> getDates(){
return dates;
}
#NonNull
public String getType_counter() {
return type_counter;
}
#NonNull
public String getWhere_counter() {
return where_counter;
}
#PrimaryKey(autoGenerate = true)
public int id;
#ColumnInfo(name = "d")
#TypeConverters({Converters.class})
public ArrayList<String> dates;
#ColumnInfo(name = "value")
#TypeConverters({Converters.class})
public ArrayList<String> values;
#ColumnInfo(name = "type")
public String type_counter;
#ColumnInfo(name = "location")
public String where_counter;
}
I have one RecyclerView which shows only type and location and when you click on any item it goes to another activity where another RecyclerView shows values and dates of this particular User (by Id) as arrays.
My problem is this: user of my app can either create new User object or update it (add value and date to ArrayLists) and when updating RecyclerView is not working properly.
Suppose I have two User objects and my database looks like this:
My fist object has two values and dates but RecyclerView shows only one.
When I add another value and date to the second User object, RecyclerView shows two elements in both objects.
This is how I update values:
private void saveNewValue(String value, String type, String location){
// Getting current date
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
// checking if the counter exists
int mList = userViewModel.setTypeLocation(type, location);
if (mList == 0){
//Saving new User
User user = new User();
if (user.values == null){
user.values = new ArrayList<String>();
}
if (user.dates == null){
user.dates = new ArrayList<String>();
}
user.values.add(value);
user.dates.add(formattedDate);
user.type_counter = type;
user.where_counter = location;
userViewModel.insert(user);
Toast.makeText(this, "Successfully saved!", Toast.LENGTH_SHORT).show();
}
else {
//Getting current data
User mUser = userViewModel.getUserWithLocationType(type, location);
ArrayList<String> values_user = mUser.getValues();
ArrayList<String> dates_user = mUser.getDates();
// Updating arrays
values_user.add(value);
dates_user.add(formattedDate);
// Creating new User object with updated values
User updatedUser = new User();
updatedUser.id = mUser.getId();
updatedUser.type_counter = type;
updatedUser.where_counter = location;
updatedUser.values = values_user;
updatedUser.dates = dates_user;
userViewModel.update(updatedUser);
//userAdapter.notifyItemChanged();
Toast.makeText(this, "Successfully updated!", Toast.LENGTH_SHORT).show();
}
}
This is Adapter class for an already described RecyclerView:
public class CalculationAdapter extends RecyclerView.Adapter<CalculationAdapter.CalcViewHolder>{
private LayoutInflater inflater;
private Context mContext;
private ArrayList<String> mValues;
private ArrayList<String> mDates;
private User mUser;
public CalculationAdapter(Context ctx){
inflater = LayoutInflater.from(ctx);
mContext = ctx;
}
public void setUser(User user){
mUser = user;
mValues = user.getValues();
mDates = user.getDates();
notifyDataSetChanged();
Log.i("values", String.valueOf(mValues));
Log.i("dates", String.valueOf(mDates));
}
#NonNull
#Override
public CalculationAdapter.CalcViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.calculations_item, parent, false);
CalculationAdapter.CalcViewHolder holder = new CalculationAdapter.CalcViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull CalculationAdapter.CalcViewHolder holder, int position) {
if (mValues != null & mDates != null){
String value = mValues.get(position);
String date = mDates.get(position);
holder.setValuesDates(value, date, position);
}
else{
holder.mValue.setText("No value");
holder.mDate.setText("No date");
}
}
#Override
public int getItemCount() {
if (mValues != null){
return mValues.size();
} else return 0;
}
class CalcViewHolder extends RecyclerView.ViewHolder {
private TextView mValue;
private TextView mDate;
private int mPosition;
public CalcViewHolder(#NonNull View itemView) {
super(itemView);
mValue = itemView.findViewById(R.id.item_value);
mDate = itemView.findViewById(R.id.item_date);
}
public void setValuesDates(String value, String date, int position){
mValue.setText(value);
mDate.setText(date);
mPosition = position;
}
}
}
This is ViewModel class:
public class UserViewModel extends AndroidViewModel {
private String TAG = this.getClass().getSimpleName();
private UserDao userDao;
private AppDatabase appDatabase;
private LiveData<List<User>> mAllUsers;
private LiveData<String[]> mAllLocations;
private LiveData<User> mUser;
private int UserLocationTypeExists;
public UserViewModel(#NonNull Application application) {
super(application);
appDatabase = AppDatabase.getInstance(application);
userDao = appDatabase.userDao();
mAllUsers = userDao.getAllValues();
mAllLocations = userDao.getAllLocations();
}
public void setId(int id){
mUser = userDao.getUserWithId(id);
}
public User getUserWithLocationType(String type, String location){
return userDao.getUserwithLocationType(type, location);
}
public int setTypeLocation(String type, String location){
UserLocationTypeExists = userDao.UserWithTypeLocationExists(type, location);
return UserLocationTypeExists;
}
public void update(User user) {
new UpdateAsyncTask(userDao).execute(user);
}
public void insert(User user){
new InsertAsyncTask(userDao).execute(user);
}
public void delete(User user){
new DeleteAsyncTask(userDao).execute(user);
}
public LiveData<List<User>> getAllUsers(){
return mAllUsers;
}
public LiveData<String[]> getAllLocations() {
return mAllLocations;
}
public LiveData<User> getUserAtId(){
return mUser;
}
private class InsertAsyncTask extends AsyncTask<User, Void, Void> {
UserDao userDao;
public InsertAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.insertValue(users[0]);
return null;
}
}
private class DeleteAsyncTask extends AsyncTask<User, Void, Void> {
UserDao userDao;
public DeleteAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.deleteValue(users[0]);
return null;
}
}
private class UpdateAsyncTask extends AsyncTask<User, Void, Void> {
UserDao userDao;
public UpdateAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.update(users[0]);
return null;
}
}
}
This is the Activity where I have RecyclerView:
public class CalculationActivity extends AppCompatActivity{
private int id_counter;
private UserViewModel userViewModel;
private CalculationAdapter calcAdapter;
private int rate;
private String value1, date1, value2, date2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id_counter = extras.getInt("id");
}
RecyclerView recyclerView = findViewById(R.id.recyclerView_calc);
calcAdapter = new CalculationAdapter(this);
recyclerView.setAdapter(calcAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
userViewModel.setId(id_counter);
userViewModel.getUserAtId().observe(this, new Observer<User>() {
#Override
public void onChanged(User user) {
calcAdapter.setUser(user);
}
});
}
}
Could somebody please help me figure out why doesn't my RecyclerView update data correctly? Thanks in advance.
I can add more info if necessary.
This is TypeConverters.class:
public class Converters {
#TypeConverter
public static ArrayList<String> fromString(String value) {
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
return new Gson().fromJson(value, listType);
}
#TypeConverter
public static String fromArrayList(ArrayList<String> list) {
Gson gson = new Gson();
return gson.toJson(list);
}
}
EDIT: I saved different values in the database. Here is how the database looking:
This is Activity1:
When I click on both items they both show value 2222:
Output of SetUser method (when I click on each of the items):
I/values: [2222]
I/dates: [27-Juli-2022]
I/values: [2222]
I/dates: [27-Juli-2022]
Small mistake... I've been sending ID to Activity2 the wrong way. I've been getting it in the onBindViewHolder method which goes over all the elements and which is why I got only values from the last saved element. I needed to get ID in the Holder class in OnClick method. Thanks for all the help anyway.

problem with scrolling up or down of listview

When I try to take all the values of the NumberPicker, it correctly returns the ones in the middle, while the first and last returns only the last one that has been modified between them. I don't understand where I'm wrong.
public class piatto {
String nome;
String Descrizione;
String prezzo;
String immagine;
String tag;
public piatto(String nome, String Descrizione, String prezzo, String immagine, String tag) {
this.nome= nome;
this.Descrizione= Descrizione;
this.prezzo= prezzo;
this.immagine=immagine;
this.tag=tag;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescrizione() {
return Descrizione;
}
public void setDescrizione(String descrizione) {
Descrizione = descrizione;
}
public String getPrezzo() {
return prezzo;
}
public void setPrezzo(String prezzo) {
this.prezzo = prezzo;
}
public String getImmagine() {
return immagine;
}
public void setImmagine(String immagine) {
this.immagine = immagine;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
this is my adapeter
public class ProductListAdapterforListView extends BaseAdapter {
private Context mContext;
private List<piatto> mProductList;
public ProductListAdapterforListView(Context mContext, List<piatto> mProductList) {
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public piatto getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listitemview ;
if (convertView==null){
listitemview = View.inflate(mContext, R.layout.row_data_list, null);
ImageView i = (ImageView) listitemview.findViewById(R.id.imagepiatto);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) listitemview.findViewById(R.id.number_picker);
TextView n=(TextView) listitemview.findViewById(R.id.namepiatto);
TextView p=(TextView) listitemview.findViewById(R.id.prezzopiatto);
n.setText(mProductList.get(position).getNome());
p.setText(mProductList.get(position).getPrezzo()+" €");
Picasso.get().load(mProductList.get(position).getImmagine()).into(i);
} else {
listitemview=convertView;
}
return listitemview;
}
}
And this is my Java class where I get the values of the NumberPicker of each Item
#Override
public void onClick(View view) {
if (view.getId()==R.id.buttonnext){
Float totale = (float) 0.0;
String listapiatti="";
for (int i = 0; i < listView.getChildCount(); i++) {
view = listView.getChildAt(i);
TextView n = view.findViewById(R.id.namepiatto);
String nome = n.getText().toString();
TextView p = view.findViewById(R.id.prezzopiatto);
String pricestr = p.getText().toString();
String[] prezzo = pricestr.split(" ");
Float price = Float.valueOf(prezzo[0]);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) view.findViewById(R.id.number_picker);
int value = numberPicker.getValue();
if (value != 0) {
totale = totale + (price * value);
listapiatti = listapiatti + nome + ": " + value + ", ";
Toast.makeText(getApplicationContext(), String.valueOf(i)+" "+value,
Toast.LENGTH_LONG).show();
}
}
String finale=String.valueOf(totale);
startActivity(new Intent(carrello3.this, ordine.class));
}
if (view.getId()==R.id.buttonback){
onBackPressed();
}
}
it doesn't seem like a good idea to create an object on setOnScrollListener which gets called many many times during scrolling up/down. if you could provide more detail would be great.

Getter returning null when testing get methods

I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.
Any insight would be appreciated as I am lost here. Thanks in advance.
Here is where I initialise the class:
public ArrayList<GameStats> getAllData() {
ArrayList<GameStats> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String lName = cursor.getString(1);
int lScore = cursor.getInt(2);
String rName = cursor.getString(3);
int rScore = cursor.getInt(4);
String notes = cursor.getString(5);
GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
arrayList.add(gameStats);
}
return arrayList;
}
Here is where I am trying to use the getters:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_saved_games, null);
TextView lName = convertView.findViewById(R.id.lName);
TextView lScore = convertView.findViewById(R.id.lScore);
TextView rName = convertView.findViewById(R.id.rName);
TextView rScore = convertView.findViewById(R.id.rScore);
TextView notes = convertView.findViewById(R.id.notes);
GameStats gameStats = arrayList.get(position);
testVar = gameStats.getlName();
Log.d("MyAdaptor","gameStats = " + var);
lName.setText(gameStats.getlName());
lScore.setText(String.valueOf(gameStats.getlScore()));
rName.setText(gameStats.getrName());
rScore.setText(String.valueOf(gameStats.getrScore()));
notes.setText(gameStats.getNotes());
return convertView;
}
Here is the model class:
public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getlScore() {
return lScore;
}
public void setlScore(int lScore) {
this.lScore = lScore;
}
public int getrScore() {
return rScore;
}
public void setrScore(int rScore) {
this.rScore = rScore;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
and here is where I am calling the methods:
public class SavedGameScreen extends AppCompatActivity {
ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_game_screen);
lv1 = findViewById(R.id.lv1);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
loadData();
}
private void loadData() {
arrayList = databaseHelper.getAllData();
myAdaptor = new MyAdaptor(this, arrayList);
lv1.setAdapter(myAdaptor);
myAdaptor.notifyDataSetChanged();
}
}
Please change the constructor as below and see if that works,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
In your model class initialize the variables using constrtuctor. I guess that is the problem. Since you are not initializing the model class properties, it the getters will return "null" or any garbage value
You are passing the values to the model constructor but you are not assigning it to the model variables. You need to change the code as below,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
Else initialise each variable through setter() method.

My Firebase Database returns null for each Member properties

I created a Firebase database to store members just like contacts, am trying to fetch all the members properties stored in the database. Now the list of members is fetching correctly but the member details e.g the phone, email etc return null. Please help me out.
This the Firebase database structure:
This is my code to fetch the list of members:
members = new ArrayList<>();
member = new Member();
adapter = new AllMembersAdapter(members, this);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference().child("Rad5 Tech Hub");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
members.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()){
member = ds.getValue(Member.class);
Log.d("debugger", "member email: " + member.getEmail()); //returns null
members.add(member);
}
recyclerViewList.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here is my Member Class
public class Member {
private String mMonthName;
private String mLastName;
private String mGender;
private String mEmail;
private String mPhone;
private String mAddress;
private String mDate;
private String mOccupation;
public Member(){}
public Member(String mAddress, String mDate, String mEmail, String mGender,
String mLastName, String mMonthName, String mOccupation, String mPhone) {
this.mLastName = mLastName;
this.mGender = mGender;
this.mEmail = mEmail;
this.mPhone = mPhone;
this.mAddress = mAddress;
this.mDate = mDate;
this.mOccupation = mOccupation;
this.mMonthName = mMonthName;
}
public String getLastName() {
return mLastName;
}
public String getGender() {
return mGender;
}
public String getEmail() {
return mEmail;
}
public String getPhone() {
return mPhone;
}
public String getAddress() {
return mAddress;
}
public String getDate() {
return mDate;
}
public String getMonthName() {
return mMonthName;
}
public String getOccupation() {
return mOccupation;
}
public Map<String, Object> toMap(){
HashMap<String, Object> result = new HashMap<>();
result.put("address", mAddress);
result.put("birthday", mDate);
result.put("email", mEmail);
result.put("gender", mGender);
result.put("last name", mLastName);
result.put("month name", mMonthName);
result.put("occupation", mOccupation);
result.put("phone number", mPhone);
return result;
}
}
Here is my adapter class:
public class AllMembersAdapter extends RecyclerView.Adapter<AllMembersAdapter.MembersViewHolder> {
ArrayList<Member> members;
ListItemClickListener listItemClickListener;
public AllMembersAdapter(ArrayList<Member> members, ListItemClickListener listItemClickListener) {
this.members = members;
this.listItemClickListener = listItemClickListener;
}
#NonNull
#Override
public MembersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.member_item, parent, false);
return new MembersViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MembersViewHolder holder, int position) {
Member member = members.get(position);
String _monthName = member.getMonthName();
holder.mMonth.setText(_monthName);
holder.mName.setText(member.getLastName());
holder.mDate.setText(member.getDate());
}
#Override
public int getItemCount() {
return members.size();
}
public interface ListItemClickListener{
void onListItemClick(int position);
}
public class MembersViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mMonth;
TextView mName;
TextView mDate;
public MembersViewHolder(View itemView) {
super(itemView);
mMonth = (TextView) itemView.findViewById(R.id.txt_month);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDate = (TextView) itemView.findViewById(R.id.txt_date);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listItemClickListener.onListItemClick(getAdapterPosition());
}
}
}
As #TheTechWolf mentioned in his comment, the problem is that Member class fields are different then the names of the fields that you have in your Firebase database. Let's take an example, in your model class you have a field named mMonthName but in the database the corresponding field is named month name. When you are using a getter named getMonthName(), Firebase is looking after a field named monthName and not mMonthName as you have now. So to solve this, please use the following model class which contains all member fields that you need:
public class Member {
private String monthName, lastName, gender, email, phone, address, date, occupation;
public Member() {}
public Member(String monthName, String lastName, String gender, String email, String phone, String address, String date, String occupation) {
this.monthName = monthName;
this.lastName = lastName;
this.gender = gender;
this.email = email;
this.phone = phone;
this.address = address;
this.date = date;
this.occupation = occupation;
}
public String getMonthName() { return monthName; }
public String getLastName() { return lastName; }
public String getGender() { return gender; }
public String getEmail() { return email; }
public String getPhone() { return phone; }
public String getAddress() { return address; }
public String getDate() { return date; }
public String getOccupation() { return occupation; }
}

Android GSON access List in ArrayList

I'm using GSON to parse a JSON feed like this here:
http://dvz.hj.cx/api/get_recent_posts/?dev=1
My model class looks like this one here:
public class Recent {
#Expose
private String status;
#Expose
private int count;
#Expose
private int count_total;
#Expose
private int pages;
#Expose
private List<Post> posts = new ArrayList<Post>();
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Recent withStatus(String status) {
this.status = status;
return this;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Recent withCount(int count) {
this.count = count;
return this;
}
public int getCount_total() {
return count_total;
}
public void setCount_total(int count_total) {
this.count_total = count_total;
}
public Recent withCount_total(int count_total) {
this.count_total = count_total;
return this;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public Recent withPages(int pages) {
this.pages = pages;
return this;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public Recent withPosts(List<Post> posts) {
this.posts = posts;
return this;
}
}
As you can see I'm referring to another model class called Post.
The Post model class looks like this one:
public class Post {
#Expose
private int id;
#Expose
private String url;
#Expose
private String title;
#Expose
private String date;
#Expose
private List<Category> categories = new ArrayList<Category>();
#Expose
private List<Object> tags = new ArrayList<Object>();
#Expose
private Author author;
#Expose
private List<Attachment> attachments = new ArrayList<Attachment>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Post withId(int id) {
this.id = id;
return this;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Post withUrl(String url) {
this.url = url;
return this;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Post withTitle(String title) {
this.title = title;
return this;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Post withDate(String date) {
this.date = date;
return this;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public Post withCategories(List<Category> categories) {
this.categories = categories;
return this;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Post withAuthor(Author author) {
this.author = author;
return this;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public Post withAttachments(List<Attachment> attachments) {
this.attachments = attachments;
return this;
}
}
And again I'm reffering to some other models. Until now erverything works perfect, but now I need to access some of this getters and setters in my BaseAdapter.
My Adapter classe looks like this:
public class NewsList extends BaseAdapter {
private List<Recent> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public ImageLoader imageLoader;
public NewsList(Context context, List<Recent> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.news_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.commentView = (TextView) convertView.findViewById(R.id.comment);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Recent rec = (Recent) listData.get(position);
Post post = (Post) rec.getPosts();
Attachment att = (Attachment) post.getAttachments();
List<Images> img = att.getImages();
Thumbnail thumb = (Thumbnail) img.getThumbnail();
Author author = (Author) post.getAuthor();
if(post != null){
/* date and time */
String date = post.getDate().replace("-",".");
String zeit = date.substring(11,16);
String datum = date.substring(0, 11);
String djahr = datum.substring(0,4);
String dmonat = datum.substring(5,8);
String dtag = datum.substring(8,10);
holder.headlineView.setText(Html.fromHtml(post.getTitle()));
holder.reportedDateView.setText(Html.fromHtml("Am <b>" + dtag+"."+dmonat+djahr+" </b>um <b>"+zeit+"</b>"));
holder.commentView.setText(Html.fromHtml("Von: <b>" + author.getName()));
ImageView image = holder.imageView;
if(post.attachments.getMime_type().contains("image")){
imageLoader.DisplayImage(thumb.getUrl(), image);
}
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView commentView;
TextView reportedDateView;
ImageView imageView;
}
}
As you see I try to get the List<Post> which is located inside the ArrayList<Recent>.
This line works perfect:
Recent rec = (Recent) listData.get(position);
But as soon as it comes to this line it doesn't work:
Post post = (Post) rec.getPosts();
I have no idea how to resolve this. Please help its very important for me. If you have a better solution, its welcome.
When it comes to this line Post post = (Post) rec.getPosts();, LogCat says
Cannot convert ArrayList to List
You are misinterpreting List<T> with T and this same problem is present at different parts of your code:
getPosts() returns List<Post> not Post like getImages() returns List<Images> not Images, you might need a loop to iterate over your List<Post>, getting single Post and then getting its data like List<Attachment>.
Change it to the following:
Recent rec = (Recent) listData.get(position);
List<Post> posts = rec.getPosts();
for(int i = 0; i < posts.size(); i++){
Post post = (Post) posts.get(i);
if(post != null){
List<Attachment> atts = post.getAttachments();
Attachment att = (Attachment) atts.get(0) // You can use loop instead of get(0)
List<Images> imgs = att.getImages();
Images img = (Images) imgs.get(0); // You can use loop instead of get(0)
Thumbnail thumb = (Thumbnail) img.getThumbnail();
Author author = (Author) post.getAuthor();
...
}
}

Categories