// I have a Custom ListView in android and have set a adapter . My problem is //that the list view does not show anything, regardless of the adapter, note I'm //retrieving information from a Backendless services . please help
// adapter Code
package za.ac.cut.afinal;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by User on 2017/09/12.
*/
public class StudentAdapter extends ArrayAdapter<Student_Class> {
private final Context context;
private final List<Student_Class> values;
TextView tvName, tvSurname,tvGender,tvRace;
public StudentAdapter(Context context, List<Student_Class> list)
{
super(context,R.layout.custom_student_row_layout);
this.context = context;
this.values = list;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Nullable
#Override
public Student_Class getItem(int position) {
return values.get(position);
}
#Override
public int getCount() {
return values == null ? 0 : values.size();
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.custom_student_row_layout,parent,false);
tvName = (TextView) rowView.findViewById(R.id.customSNmae);
tvSurname = (TextView) rowView.findViewById(R.id.tv_customSSurname);
tvGender = (TextView) rowView.findViewById(R.id.customSGender);
tvRace = (TextView) rowView.findViewById(R.id.customSRace);
Toast.makeText(context, "help" + values.get(position).getL_fname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help2" + values.get(position).getL_lname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help3" + values.get(position).getL_gender(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help4" + values.get(position).getL_race(), Toast.LENGTH_SHORT).show();
tvName.setText(values.get(position).getL_fname());
tvSurname.setText(values.get(position).getL_lname());
tvGender.setText(values.get(position).getL_gender());
tvRace.setText(values.get(position).getL_race());
return rowView ;
}
}
// class Listview
package za.ac.cut.afinal;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.persistence.BackendlessDataQuery;
import com.backendless.persistence.DataQueryBuilder;
import com.backendless.persistence.QueryOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import weborb.client.ant.wdm.View;
public class Student_List extends AppCompatActivity {
ListView lv;
List<Student_Class> StudentsList;
Student_Class student ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
lv = (ListView)findViewById(R.id.lvStudentDetails1);
retrieveStudent();
}
#Override
protected void onResume() {
super.onResume();
retrieveStudent();
}
private void retrieveStudent()
{
// progressBar.setVisibility(android.view.View.VISIBLE);
if(StudentsList != null)
{
StudentsList.clear();
}
String whereClause = "u_Name = '12'";
DataQueryBuilder queryBuilder = DataQueryBuilder.create();
queryBuilder.setWhereClause(whereClause);
queryBuilder.setPageSize(100);
queryBuilder.setSortBy("l_fname");
Backendless.Persistence.of(Student_Class.class).find(queryBuilder, new AsyncCallback<List<Student_Class>>() {
#Override
public void handleResponse(List<Student_Class> response) {
for (int x = 0; x < response.size(); x++) {
student = new Student_Class(response.get(x).getL_IDNo(), response.get(x).getL_fname(), response.get(x).getL_lname(),
response.get(x).getL_className(), response.get(x).getL_gender(),
response.get(x).getL_race(), response.get(x).getL_DOB(),
response.get(x).getL_classLang(), response.get(x).getL_fullOrhalfday(),
response.get(x).getL_DOE(), response.get(x).getL_address(),
response.get(x).getL_mGardian(), response.get(x).getL_fGardian(),
response.get(x).getL_mGardianEmail(), response.get(x).getL_fGardianEmail(),
response.get(x).getL_mGardianCell(), response.get(x).getL_fGardianCell(),
response.get(x).getL_doc(),
response.get(x).getL_doctCell(), response.get(x).getL_medicalAid(),
response.get(x).getL_medicalAidPlan(), response.get(x).getL_medicalAidPlanNo(),
response.get(x).getL_allergies(), response.get(x).getL_tuckshopBalance()
, response.get(x).getCreated(), response.get(x).getUpdated(),
response.get(x).getObjectID());
}
StudentsList.add(student);
if (StudentsList != null) {
StudentAdapter adapter = new StudentAdapter(Student_List.this,StudentsList);
lv.setAdapter(adapter);
Helper_Class.ShowToast(Student_List.this,"WTF");
}else {
// tv_emptyList.setVisibility(View.VISIBLE);
Helper_Class.ShowToast(Student_List.this,"No Learners enrolled for this class");
}
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
}
}
// Student Class
package za.ac.cut.afinal;
import java.util.Date;
/**
* Created by User on 2017/09/10.
*/
public class Student_Class {
private Date created;
private Date updated;
private String objectID;
private String l_IDNo;
private String l_fname;
private String l_lname;
private String l_className;
private String l_gender;
private String l_race;
private String l_DOB;
private String l_classLang;
private String l_fullOrhalfday;
private String l_DOE;
private String l_address;
private String l_mGardian;
private String l_fGardian;
private String l_mGardianEmail;
private String l_fGardianEmail;
private String l_mGardianCell;
private String l_fGardianCell;
private String l_doc;
private String l_doctCell;
private String l_medicalAid;
private String l_medicalAidPlan;
private String l_medicalAidPlanNo;
private String l_allergies;
private String l_tuckshopBalance;
public Student_Class(String l_fname, String l_lname, String l_gender, String l_race) {
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_gender = l_gender;
this.l_race = l_race;
}
public Student_Class() {
l_IDNo = null;
l_fname = null;
l_lname = null;
l_className = null;
l_gender = null;
l_race = null;
l_DOB = null;
l_classLang = null;
l_fullOrhalfday = null;
l_DOE = null;
l_address = null;
l_mGardian = null;
l_fGardian = null;
l_mGardianEmail = null;
l_fGardianEmail = null;
l_mGardianCell = null;
l_fGardianCell = null;
l_doc = null;
l_doctCell = null;
l_medicalAid = null;
l_medicalAidPlan = null;
l_medicalAidPlanNo = null;
l_allergies = null;
l_tuckshopBalance = null;
created = null;
updated = null;
objectID = null;
}
public Student_Class(String l_IDNo, String l_fname, String l_lname, String l_className, String l_gender, String l_race, String l_DOB, String l_classLang, String l_fullOrhalfday, String l_DOE, String l_address, String l_mGardian, String l_fGardian, String l_mGardianEmail, String l_fGardianEmail, String l_mGardianCell, String l_fGardianCell, String l_doc, String l_doctCell, String l_medicalAid, String l_medicalAidPlan, String l_medicalAidPlanNo, String l_allergies, String l_tuckshopBalance,Date created, Date updated, String objectID) {
this.created = created;
this.updated = updated;
this.objectID = objectID;
this.l_IDNo = l_IDNo;
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_className = l_className;
this.l_gender = l_gender;
this.l_race = l_race;
this.l_DOB = l_DOB;
this.l_classLang = l_classLang;
this.l_fullOrhalfday = l_fullOrhalfday;
this.l_DOE = l_DOE;
this.l_address = l_address;
this.l_mGardian = l_mGardian;
this.l_fGardian = l_fGardian;
this.l_mGardianEmail = l_mGardianEmail;
this.l_fGardianEmail = l_fGardianEmail;
this.l_mGardianCell = l_mGardianCell;
this.l_fGardianCell = l_fGardianCell;
this.l_doc = l_doc;
this.l_doctCell = l_doctCell;
this.l_medicalAid = l_medicalAid;
this.l_medicalAidPlan = l_medicalAidPlan;
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
this.l_allergies = l_allergies;
this.l_tuckshopBalance = l_tuckshopBalance;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getObjectID() {
return objectID;
}
public void setObjectID(String objectID) {
this.objectID = objectID;
}
public String getL_IDNo() {
return l_IDNo;
}
public void setL_IDNo(String l_IDNo) {
this.l_IDNo = l_IDNo;
}
public String getL_fname() {
return l_fname;
}
public void setL_fname(String l_fname) {
this.l_fname = l_fname;
}
public String getL_lname() {
return l_lname;
}
public void setL_lname(String l_lname) {
this.l_lname = l_lname;
}
public String getL_className() {
return l_className;
}
public void setL_className(String l_className) {
this.l_className = l_className;
}
public String getL_gender() {
return l_gender;
}
public void setL_gender(String l_gender) {
this.l_gender = l_gender;
}
public String getL_race() {
return l_race;
}
public void setL_race(String l_race) {
this.l_race = l_race;
}
public String getL_DOB() {
return l_DOB;
}
public void setL_DOB(String l_DOB) {
this.l_DOB = l_DOB;
}
public String getL_classLang() {
return l_classLang;
}
public void setL_classLang(String l_classLang) {
this.l_classLang = l_classLang;
}
public String getL_fullOrhalfday() {
return l_fullOrhalfday;
}
public void setL_fullOrhalfday(String l_fullOrhalfday) {
this.l_fullOrhalfday = l_fullOrhalfday;
}
public String getL_DOE() {
return l_DOE;
}
public void setL_DOE(String l_DOE) {
this.l_DOE = l_DOE;
}
public String getL_address() {
return l_address;
}
public void setL_address(String l_address) {
this.l_address = l_address;
}
public String getL_mGardian() {
return l_mGardian;
}
public void setL_mGardian(String l_mGardian) {
this.l_mGardian = l_mGardian;
}
public String getL_fGardian() {
return l_fGardian;
}
public void setL_fGardian(String l_fGardian) {
this.l_fGardian = l_fGardian;
}
public String getL_mGardianEmail() {
return l_mGardianEmail;
}
public void setL_mGardianEmail(String l_mGardianEmail) {
this.l_mGardianEmail = l_mGardianEmail;
}
public String getL_fGardianEmail() {
return l_fGardianEmail;
}
public void setL_fGardianEmail(String l_fGardianEmail) {
this.l_fGardianEmail = l_fGardianEmail;
}
public String getL_mGardianCell() {
return l_mGardianCell;
}
public void setL_mGardianCell(String l_mGardianCell) {
this.l_mGardianCell = l_mGardianCell;
}
public String getL_fGardianCell() {
return l_fGardianCell;
}
public void setL_fGardianCell(String l_fGardianCell) {
this.l_fGardianCell = l_fGardianCell;
}
public String getL_doc() {
return l_doc;
}
public void setL_doc(String l_doc) {
this.l_doc = l_doc;
}
public String getL_doctCell() {
return l_doctCell;
}
public void setL_doctCell(String l_doctCell) {
this.l_doctCell = l_doctCell;
}
public String getL_medicalAid() {
return l_medicalAid;
}
public void setL_medicalAid(String l_medicalAid) {
this.l_medicalAid = l_medicalAid;
}
public String getL_medicalAidPlan() {
return l_medicalAidPlan;
}
public void setL_medicalAidPlan(String l_medicalAidPlan) {
this.l_medicalAidPlan = l_medicalAidPlan;
}
public String getL_medicalAidPlanNo() {
return l_medicalAidPlanNo;
}
public void setL_medicalAidPlanNo(String l_medicalAidPlanNo) {
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
}
public String getL_allergies() {
return l_allergies;
}
public void setL_allergies(String l_allergies) {
this.l_allergies = l_allergies;
}
public String getL_tuckshopBalance() {
return l_tuckshopBalance;
}
public void setL_tuckshopBalance(String l_tuckshopBalance) {
this.l_tuckshopBalance = l_tuckshopBalance;
}
}
set adapter.notifyDataSetChanged(); after retrieving data from backend.
Info data variable must be same reference adress, I mean do not malloc again etc. after retrieving data.
there are some errors:
1) StudentsList is never istanciated (always null)
2) StudentsList.add(student); cannot work because SutendList is null
3) StudentsList.add(student); should be called inside for loop, why are you calling it outside?
Everything was working fine, i mistakenly typed in the wrong string here "String whereClause = "u_Name = '12'";"
36 hours when the problem was a string!
Related
I am trying to retrive values from firebase database. But when I am trying to run the app it crashes. Here is the java file:
package com.example.fresh24;
import android.content.Context;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class DBqueries {
public static FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
public static List<MachineCategoryModel> machineCategoryModelList = new ArrayList<>();
public static List<HomePageModel> homePageModelList = new ArrayList<>();
public static void loadCategories(final MachineCategoryAdapter machineCategoryAdapter, final Context context){
firebaseFirestore.collection("CATEGORIES").orderBy("index").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for(QueryDocumentSnapshot documentSnapshot : task.getResult()){
machineCategoryModelList.add(new MachineCategoryModel(documentSnapshot.get("categoryName").toString()));
}
machineCategoryAdapter.notifyDataSetChanged();
} else{
String error = task.getException().getMessage();
Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
}
}
});
}
public static void loadFragmentData(final HomePageAdapter adapter, final Context context){
firebaseFirestore.collection("CATEGORIES")
.document("CoolingCabinet")
.collection("TRAYS").orderBy("index").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for(QueryDocumentSnapshot documentSnapshot : task.getResult()){
if((long)documentSnapshot.get("view_type") == 0){
List<WishlistModel>viewAllProductList = new ArrayList<>();
List<HorizontalProductScrollModel> horizontalProductScrollModelList = new ArrayList<>();
long no_of_products= (long)documentSnapshot.get("no_of_products");
for(long x = 1; x < no_of_products; x++){
horizontalProductScrollModelList.add(new HorizontalProductScrollModel(documentSnapshot.get("product_ID_"+x).toString(),
documentSnapshot.get("product_location_"+x).toString(),
documentSnapshot.get("product_image_"+x).toString(),
documentSnapshot.get("product_title_"+x).toString(),
documentSnapshot.get("product_stock_"+x).toString(),
documentSnapshot.get("product_price_"+x).toString()));
viewAllProductList.add(new WishlistModel(
documentSnapshot.get("product_image_"+x).toString(),
documentSnapshot.get("product_title_"+x).toString(),
(long)documentSnapshot.get("free_coupons_"+x),
documentSnapshot.get("average_rating_"+x).toString(),
(long)documentSnapshot.get("tol_rating_"+x),
documentSnapshot.get("product_price_"+x).toString(),
documentSnapshot.get("product_cut_price_"+x).toString()
));
}
homePageModelList.add(new HomePageModel(0,documentSnapshot.get("layout_title").toString(),documentSnapshot.get("layout_background").toString(),horizontalProductScrollModelList,viewAllProductList));
}
}
adapter.notifyDataSetChanged();
} else{
String error = task.getException().getMessage();
Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is my Model class
package com.example.fresh24;
public class WishlistModel {
private String productImage;
private String productTitle;
private long freeCoupon;
private String rating;
private long totalRatings;
private String productPrice;
private String cutPrice;
public WishlistModel(String productImage, String productTitle, long freeCoupon, String rating, long totalRatings, String productPrice, String cutPrice) {
this.productImage = productImage;
this.productTitle = productTitle;
this.freeCoupon = freeCoupon;
this.rating = rating;
this.totalRatings = totalRatings;
this.productPrice = productPrice;
this.cutPrice = cutPrice;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductTitle() {
return productTitle;
}
public void setProductTitle(String productTitle) {
this.productTitle = productTitle;
}
public long getFreeCoupon() {
return freeCoupon;
}
public void setFreeCoupon(long freeCoupon) {
this.freeCoupon = freeCoupon;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public long getTotalRatings() {
return totalRatings;
}
public void setTotalRatings(long totalRatings) {
this.totalRatings = totalRatings;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getCutPrice() {
return cutPrice;
}
public void setCutPrice(String cutPrice) {
this.cutPrice = cutPrice;
}
}
Here is the the adapter file:
package com.example.fresh24;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
public class WishlistAdapter extends RecyclerView.Adapter<WishlistAdapter.ViewHolder> {
private List<WishlistModel> wishlistModelList;
private Boolean wishlist;
public WishlistAdapter(List<WishlistModel> wishlistModelList, Boolean wishlist) {
this.wishlistModelList = wishlistModelList;
this.wishlist = wishlist;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.wishlist_item_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WishlistAdapter.ViewHolder viewHolder, int position) {
String resource = wishlistModelList.get(position).getProductImage();
String title = wishlistModelList.get(position).getProductTitle();
long freeCoupon = wishlistModelList.get(position).getFreeCoupon();
String rating = wishlistModelList.get(position).getRating();
long totalRatings = wishlistModelList.get(position).getTotalRatings();
String productPrice = wishlistModelList.get(position).getProductPrice();
String cutPrice = wishlistModelList.get(position).getCutPrice();
viewHolder.setData(resource, title, freeCoupon, rating, totalRatings, productPrice, cutPrice);
}
#Override
public int getItemCount() {
return wishlistModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView productImage;
private TextView productTitle;
private TextView freeCoupons;
private TextView rating;
private TextView totalRatings;
private View priceCut;
private ImageView couponIcon;
private TextView productPrice;
private TextView cutPrice;
private ImageView deleteBtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
productImage = itemView.findViewById(R.id.product_image);
productTitle = itemView.findViewById(R.id.product_title);
freeCoupons = itemView.findViewById(R.id.free_coupon);
rating = itemView.findViewById(R.id.tv_product_rating_miniview);
totalRatings = itemView.findViewById(R.id.total_ratings);
priceCut = itemView.findViewById(R.id.price_cut);
couponIcon = itemView.findViewById(R.id.coupon_icon);
productPrice = itemView.findViewById(R.id.product_price);
cutPrice = itemView.findViewById(R.id.cut_price);
deleteBtn = itemView.findViewById(R.id.delete_btn);
}
private void setData(String resource, String title, long freeCouponsNo, String averageRate, long totalRatingsNo, String price, String cutPriceValue) {
Glide.with(itemView.getContext()).load(resource).apply(new RequestOptions().placeholder(R.drawable.home_icon_green)).into(productImage);
productTitle.setText(title);
if (freeCouponsNo != 0) {
couponIcon.setVisibility(View.VISIBLE);
if (freeCouponsNo == 1) {
freeCoupons.setText("free " + freeCouponsNo + " coupon");
} else {
freeCoupons.setText("free " + freeCouponsNo + " coupons");
}
}else{
couponIcon.setVisibility(View.INVISIBLE);
freeCoupons.setVisibility(View.INVISIBLE);
}
rating.setText(averageRate);
totalRatings.setText(totalRatingsNo+"(ratings)");
productPrice.setText(price);
cutPrice.setText(cutPriceValue);
if(wishlist){
deleteBtn.setVisibility(View.VISIBLE);
}else{
deleteBtn.setVisibility(View.GONE);
}
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(),"Testing Deleted",Toast.LENGTH_SHORT).show();
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent productDetailsIntent = new Intent(itemView.getContext(),ProductDetailsActivity.class);
itemView.getContext().startActivity(productDetailsIntent);
}
});
}
}
}
Here is the logcat error:
Process: com.example.fresh24, PID: 9413
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at com.example.fresh24.DBqueries$2.onComplete(DBqueries.java:68)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
The error is on this line in the java file - (long)documentSnapshot.get("free_coupons_"+x). I have selected numbers for the 'free coupons' and 'total ratings' field in the Firebase database. I have read that the number fields are converted to Long when fetched from the firebase database and hence I have casted them to long. I am unable to locate the source of my error. Please help. Thanks in advance.
This is due to the fact you are not checking if the value if null or not.So just put the whole code which fetches the long value inside a if loop with condition that it is != null this will solve the issue.Hope it is helpful.
I bought in courses on creating android application "Quiz app". But in this course, a random order of answers is not implemented. I'm a beginner programmer without any technical education I know that I need to insert somewhere in the code
"Collections.shuffle (list)" but I can not yet figure out where. Help please. I'm making an application for students that would make life easier for them. Helping me you are helping them.
QUIZ ACTIVITY
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.vn.iambulance.prototype_20.R;
import com.vn.iambulance.prototype_20.adapters.QuizAdapter;
import com.vn.iambulance.prototype_20.constants.AppConstants;
import com.vn.iambulance.prototype_20.data.preference.AppPreference;
import com.vn.iambulance.prototype_20.listeners.ListItemClickListener;
import com.vn.iambulance.prototype_20.models.quiz.QuizModel;
import com.vn.iambulance.prototype_20.models.quiz.ResultModel;
import com.vn.iambulance.prototype_20.utilities.ActivityUtilities;
import com.vn.iambulance.prototype_20.utilities.BeatBox;
import com.vn.iambulance.prototype_20.utilities.DialogUtilities;
import com.vn.iambulance.prototype_20.utilities.SoundUtilities;
public class QuizActivity extends BaseActivity implements DialogUtilities.OnCompleteListener {
private Activity mActivity;
private Context mContext;
private ImageButton btnSpeaker;
private Button btnNext;
private RecyclerView mRecyclerQuiz;
private TextView tvQuestionText;
private TextView tvQuestionTitle;
private ImageView imgFirstLife, imgSecondLife, imgThirdLife, imgFourthLife, imgFifthLife;
private QuizAdapter mAdapter = null;
private List<QuizModel> mItemList;
ArrayList<String> mOptionList;
ArrayList<String> mBackgroundColorList;
private int mQuestionPosition = 0;
private int mQuestionsCount = 0;
private int mScore = 0, mWrongAns = 0, mSkip = 0;
private int mLifeCounter = 5;
private boolean mUserHasPressed = false;
private boolean mIsSkipped = false, mIsCorrect = false;
private String mQuestionText, mGivenAnsText, mCorrectAnsText, mCategoryId;
private ArrayList<ResultModel> mResultList;
private BeatBox mBeatBox;
private List<SoundUtilities> mSounds;
private boolean isSoundOn;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//TODO: initializeRewardedAds();
//TODO: loadRewardedVideoAds();
initVar();
initView();
loadData();
initListener();
}
private void initVar() {
mActivity = QuizActivity.this;
mContext = mActivity.getApplicationContext();
Intent intent = getIntent();
if (intent != null) {
mCategoryId = intent.getStringExtra(AppConstants.BUNDLE_KEY_INDEX);
}
mItemList = new ArrayList<>();
mOptionList = new ArrayList<>();
mBackgroundColorList = new ArrayList<>();
mResultList = new ArrayList<>();
mBeatBox = new BeatBox(mActivity);
mSounds = mBeatBox.getSounds();
}
private void initView() {
setContentView(R.layout.activity_quiz);
imgFirstLife = (ImageView) findViewById(R.id.firstLife);
imgSecondLife = (ImageView) findViewById(R.id.secondLife);
imgThirdLife = (ImageView) findViewById(R.id.thirdLife);
imgFourthLife = (ImageView) findViewById(R.id.fourthLife);
imgFifthLife = (ImageView) findViewById(R.id.fifthLife);
btnSpeaker = (ImageButton) findViewById(R.id.btnSpeaker);
btnNext = (Button) findViewById(R.id.btnNext);
tvQuestionText = (TextView) findViewById(R.id.tvQuestionText);
tvQuestionTitle = (TextView) findViewById(R.id.tvQuestionTitle);
mRecyclerQuiz = (RecyclerView) findViewById(R.id.rvQuiz);
mRecyclerQuiz.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mAdapter = new QuizAdapter(mContext, mActivity, mOptionList, mBackgroundColorList);
mRecyclerQuiz.setAdapter(mAdapter);
initToolbar(true);
setToolbarTitle(getString(R.string.quiz));
enableUpButton();
initLoader();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void loadData() {
showLoader();
isSoundOn = AppPreference.getInstance(mActivity).getBoolean(AppConstants.KEY_SOUND, true);
setSpeakerImage();
loadJson();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setSpeakerImage() {
if (isSoundOn) {
btnSpeaker.setImageResource(R.drawable.ic_speaker);
} else {
btnSpeaker.setImageResource(R.drawable.ic_speaker_not);
}
}
public void initListener() {
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
isSoundOn = !isSoundOn;
AppPreference.getInstance(mActivity).setBoolean(AppConstants.KEY_SOUND, isSoundOn);
setSpeakerImage();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mUserHasPressed) {
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.skip_text), getString(R.string.skip_prompt), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_SKIP_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
} else {
updateResultSet();
setNextQuestion();
}
}
});
mAdapter.setItemClickListener(new ListItemClickListener() {
#Override
public void onItemClick(int position, View view) {
if (!mUserHasPressed) {
int clickedAnswerIndex = position;
if (mItemList.get(mQuestionPosition).getCorrectAnswer() != -1) {
for (int currentItemIndex = 0; currentItemIndex < mOptionList.size(); currentItemIndex++) {
if (currentItemIndex == clickedAnswerIndex && currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer()) {
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_GREEN);
mScore++;
mIsCorrect = true;
if (isSoundOn) {
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_ZERO_INDEX));
}
} else if (currentItemIndex == clickedAnswerIndex && !(currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer())) {
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_RED);
mWrongAns++;
if (isSoundOn) {
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_SECOND_INDEX));
}
decreaseLifeAndStatus();
} else if (currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer()) {
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_GREEN);
((LinearLayoutManager) mRecyclerQuiz.getLayoutManager()).scrollToPosition(currentItemIndex);
}
}
} else {
mBackgroundColorList.set(clickedAnswerIndex, AppConstants.COLOR_GREEN);
mScore++;
mIsCorrect = true;
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_ZERO_INDEX));
}
mGivenAnsText = mItemList.get(mQuestionPosition).getAnswers().get(clickedAnswerIndex);
mCorrectAnsText = mItemList.get(mQuestionPosition).getAnswers().get(mItemList.get(mQuestionPosition).getCorrectAnswer());
mUserHasPressed = true;
mAdapter.notifyDataSetChanged();
}
}
});
}
public void decreaseLifeAndStatus() {
mLifeCounter--;
setLifeStatus();
}
void increaseLifeAndStatus() {
if (mLifeCounter < AppConstants.BUNDLE_KEY_MAX_LIFE) {
mLifeCounter++;
setLifeStatus();
}
}
public void setLifeStatus() {
switch (mLifeCounter) {
case 1:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.GONE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 2:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 3:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 4:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.VISIBLE);
imgFifthLife.setVisibility(View.GONE);
break;
case 5:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.VISIBLE);
imgFifthLife.setVisibility(View.VISIBLE);
break;
default:
imgFirstLife.setVisibility(View.GONE);
imgSecondLife.setVisibility(View.GONE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
}
}
public void setNextQuestion() {
if (isSoundOn) {
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_FIRST_INDEX));
}
mUserHasPressed = false;
if (mQuestionPosition < mItemList.size() - 1 && mLifeCounter > 0) {
mQuestionPosition++;
updateQuestionsAndAnswers();
} else if (mQuestionPosition < mItemList.size() - 1 && mLifeCounter == 0) {
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.reward_dialog_title), getString(R.string.reward_dialog_message), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_REWARD_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
} else {
ActivityUtilities.getInstance().invokeScoreCardActivity(mActivity, ScoreCardActivity.class, mQuestionsCount, mScore, mWrongAns, mSkip, mCategoryId, mResultList, true);
AppPreference.getInstance(mActivity).setQuizResult(mCategoryId, mScore);
}
}
public void updateQuestionsAndAnswers() {
mOptionList.clear();
mBackgroundColorList.clear();
((LinearLayoutManager) mRecyclerQuiz.getLayoutManager()).scrollToPosition(AppConstants.BUNDLE_KEY_ZERO_INDEX);
mOptionList.addAll(mItemList.get(mQuestionPosition).getAnswers());
mBackgroundColorList.addAll(mItemList.get(mQuestionPosition).getBackgroundColors());
mAdapter.notifyDataSetChanged();
mQuestionText = mItemList.get(mQuestionPosition).getQuestion();
tvQuestionText.setText(Html.fromHtml(mQuestionText));
tvQuestionTitle.setText(getString(R.string.quiz_question_title, mQuestionPosition + 1, mQuestionsCount));
}
public void quizActivityClosePrompt() {
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.exit), getString(R.string.cancel_prompt), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_CLOSE_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
}
private void loadJson() {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(AppConstants.QUESTION_FILE)));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
parseJson(sb.toString());
}
public void parseJson(String jsonData) {
try {
JSONObject jsonObjMain = new JSONObject(jsonData);
JSONArray jsonArray = jsonObjMain.getJSONArray(AppConstants.JSON_KEY_QUESTIONNAIRY);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String question = jsonObj.getString(AppConstants.JSON_KEY_QUESTION);
int correctAnswer = Integer.parseInt(jsonObj.getString(AppConstants.JSON_KEY_CORRECT_ANS));
String categoryId = jsonObj.getString(AppConstants.JSON_KEY_CATEGORY_ID);
Log.d("TAG", categoryId.toString());
JSONArray jsonArray2 = jsonObj.getJSONArray(AppConstants.JSON_KEY_ANSWERS);
ArrayList<String> contents = new ArrayList<>();
ArrayList<String> backgroundColors = new ArrayList<>();
for (int j = 0; j < jsonArray2.length(); j++) {
String item_title = jsonArray2.get(j).toString();
contents.add(item_title);
backgroundColors.add(AppConstants.COLOR_WHITE);
}
if (mCategoryId.equals(categoryId)) {
mItemList.add(new QuizModel(question, contents, correctAnswer, categoryId, backgroundColors));
}
}
mQuestionsCount = mItemList.size();
Collections.shuffle(mItemList);
hideLoader();
updateQuestionsAndAnswers();
} catch (JSONException e) {
e.printStackTrace();
showEmptyView();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
quizActivityClosePrompt();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
quizActivityClosePrompt();
}
#Override
public void onComplete(Boolean isOkPressed, String viewIdText) {
if (isOkPressed) {
if (viewIdText.equals(AppConstants.BUNDLE_KEY_CLOSE_OPTION)) {
ActivityUtilities.getInstance().invokeNewActivity(mActivity, MainActivity.class, true);
} else if (viewIdText.equals(AppConstants.BUNDLE_KEY_SKIP_OPTION)) {
mSkip++;
mIsSkipped = true;
mGivenAnsText = getResources().getString(R.string.skipped_text);
mCorrectAnsText = mItemList.get(mQuestionPosition).getAnswers().get(mItemList.get(mQuestionPosition).getCorrectAnswer());
updateResultSet();
setNextQuestion();
} else if (viewIdText.equals(AppConstants.BUNDLE_KEY_REWARD_OPTION)) {
//TODO: mRewardedVideoAd.show();
}
} else if (!isOkPressed && viewIdText.equals(AppConstants.BUNDLE_KEY_REWARD_OPTION)) {
ActivityUtilities.getInstance().invokeScoreCardActivity(mActivity, ScoreCardActivity.class, mQuestionsCount, mScore, mWrongAns, mSkip, mCategoryId, mResultList, true);
AppPreference.getInstance(mContext).setQuizResult(mCategoryId, mScore);
AppPreference.getInstance(mContext).setQuizQuestionsCount(mCategoryId, mQuestionsCount);
}
}
public void updateResultSet() {
mResultList.add(new ResultModel(mQuestionText, mGivenAnsText, mCorrectAnsText, mIsCorrect, mIsSkipped));
mIsCorrect = false;
mIsSkipped = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
mBeatBox.release();
}
}
QUIZ ADAPTER
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import com.vn.iambulance.prototype_20.R;
import com.vn.iambulance.prototype_20.listeners.ListItemClickListener;
public class QuizAdapter extends RecyclerView.Adapter<QuizAdapter.ViewHolder> {
private Context mContext;
private Activity mActivity;
private ArrayList<String> mItemList;
private ArrayList<String> mColorList;
private ListItemClickListener mItemClickListener;
public QuizAdapter (Context mContext, Activity mActivity, ArrayList<String> mItemList, ArrayList<String> mColorList) {
this.mContext = mContext;
this.mActivity = mActivity;
this.mItemList = mItemList;
this.mColorList = mColorList;
}
public void setItemClickListener(ListItemClickListener itemClickListener) {
this.mItemClickListener = itemClickListener;
}
#Override
public QuizAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_quiz, parent, false);
return new QuizAdapter.ViewHolder(view, viewType, mItemClickListener);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvItemTitle;
private CardView lytContainer;
private ListItemClickListener itemClickListener;
public ViewHolder(View itemView, int viewType, ListItemClickListener itemClickListener) {
super(itemView);
this.itemClickListener = itemClickListener;
// Find all views ids
tvItemTitle = itemView.findViewById(R.id.answer_text);
lytContainer = itemView.findViewById(R.id.card_view);
lytContainer.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (itemClickListener != null) {
itemClickListener.onItemClick(getLayoutPosition(), view);
}
}
}
#Override
public int getItemCount() {
return (null != mItemList ? mItemList.size() : 0);
}
#Override
public void onBindViewHolder(QuizAdapter.ViewHolder mainHolder, int position) {
final String model = mItemList.get(position);
final String model1 = mColorList.get(position);
// setting data over views
mainHolder.tvItemTitle.setText(Html.fromHtml(model));
mainHolder.tvItemTitle.setBackgroundResource(mActivity.getResources().getIdentifier(model1, "drawable", mActivity.getPackageName()));
}
}
QUIZ MODEL
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class QuizModel implements Parcelable {
String question;
ArrayList<String> answers;
int correctAnswer;
String questinCategoryId;
ArrayList<String> backgroundColors;
public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors) {
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;
}
public String getQuestion() {
return question;
}
public int getCorrectAnswer() {
return correctAnswer;
}
public ArrayList<String> getAnswers() {
return answers;
}
public String getQuestingCategoryId() {
return questinCategoryId;
}
public void setBackgroundColors(ArrayList<String> backgroundColors) {
this.backgroundColors = backgroundColors;
}
public ArrayList<String> getBackgroundColors() {
return backgroundColors;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(question);
dest.writeList(answers);
dest.writeInt(correctAnswer);
dest.writeString(questinCategoryId);
dest.writeList(backgroundColors);
}
protected QuizModel (Parcel in) {
question = in.readString();
in.readList(answers, QuizModel.class.getClassLoader());
correctAnswer = in.readInt();
questinCategoryId = in.readString();
in.readList(backgroundColors, QuizModel.class.getClassLoader());
}
public static Creator<QuizModel> getCREATOR() {
return CREATOR;
}
public static final Creator<QuizModel> CREATOR = new Creator<QuizModel>() {
#Override
public QuizModel createFromParcel(Parcel source) {
return new QuizModel(source);
}
#Override
public QuizModel[] newArray(int size) {
return new QuizModel[size];
}
};
}
and JSON database
{
"question": "Тривале перебування в умовах спеки викликало у людини спрагу. Сигналiзацiя вiд яких рецепторiв, перш за все, зумовила її розвиток? ",
"answers": [
" Натрiєвi рецептори гiпоталамусу",
" Осморецептори печiнки",
" Глюкорецептори гiпоталамусу",
" Барорецептори дуги аорти",
" Осморецептори гiпоталамусу"
],
"correct_answer":4,
"question_category":"1"
},
Source code
https://drive.google.com/open?id=1zJ-dap6zvThs4lnj8ujwG0qTBjkT_WbD
Thank you!!!
You can place Collections.shuffle (list) directly in the constructor something like that:
public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors) {
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
Collections.shuffle(this.answers);
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;
}
Or else you can define a separate method for this purpose:
public void shuffleAnswers() {
Collections.shuffle(this.answers);
}
And call it from any place in your code where you've instantiated QuizModel:
quizModel.shuffleAnswers();
public class QuizModel implements Parcelable {
String question;
ArrayList<String> answers;
int correctAnswer;
String questinCategoryId;
ArrayList<String> backgroundColors;
String trueAnswer;
public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors) {
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
shuffleAnswers();
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;
this.trueAnswer = answers.get(correctAnswer);
}
private void shuffleAnswers() {
Collections.shuffle(answers);
correctAnswer = answers.indexOf(trueAnswer);
}
public boolean isCorrect(String answer) {
return trueAnswer.equals(answer);
}
Currently working on a ExpandableListView in android using RecyclerView. I have done almost all the thing but somehow I am getting a NullpointerException which I can not sort out.Any help will be appreciated.
I am sharing the code snippet and also the git link
Used Library
Code I have tried
The app is crasing at this line in the apadter class
public DriverScheduleExpandableAdapter(Context mContext, #NonNull
List<DriverSchedule.Schedules> parentList) {
super(parentList);//////**this is where the app is crashing**
mRecipeList = parentList;
mInflater = LayoutInflater.from(mContext);
}
Error coming is :
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper.generateChildItemList(ExpandableWrapper.java:99)
at com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper.<init>(ExpandableWrapper.java:33)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.generateParentWrapper(ExpandableRecyclerAdapter.java:1357)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.generateFlattenedParentChildList(ExpandableRecyclerAdapter.java:1326)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.<init>(ExpandableRecyclerAdapter.java:120)
at com.rtstl.expandablelistview.adapter.DriverScheduleExpandableAdapter.<init>(DriverScheduleExpandableAdapter.java:23)
at com.rtstl.expandablelistview.MainActivity.inflateadapter(MainActivity.java:50)
at com.rtstl.expandablelistview.MainActivity.initview(MainActivity.java:41)
at com.rtstl.expandablelistview.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6357)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2515)
at android.app.ActivityThread.access$1000(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5571)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
MainActivity.java
package com.rtstl.expandablelistview;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rtstl.expandablelistview.adapter.DriverScheduleAdapter;
import com.rtstl.expandablelistview.adapter.DriverScheduleExpandableAdapter;
import com.rtstl.expandablelistview.databinding.ActivityMainBinding;
import com.rtstl.expandablelistview.model.DriverSchedule;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
Context mContext;
DriverSchedule list_driver;
DriverScheduleAdapter adapter;
DriverScheduleExpandableAdapter adapterExp;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext=this;
gson=new Gson();
initview();
}
private void initview() {
binding= DataBindingUtil.setContentView(this, R.layout.activity_main);
inflateadapter();
}
private void inflateadapter() {
////for reading file from raw folder otherwise it's not required
list_driver= gson.fromJson(readFileFromRawDirectory(R.raw.driverschedule), new TypeToken<DriverSchedule>(){}.getType());
////////////////////////////////////////
Toast.makeText(mContext,""+list_driver.getData().getSclist().size(),Toast.LENGTH_SHORT).show();
adapterExp = new DriverScheduleExpandableAdapter(mContext, list_driver.getData().getSclist());
binding.rvRecycle.setLayoutManager(new LinearLayoutManager(this));
binding.rvRecycle.setAdapter(adapter);
}
private String readFileFromRawDirectory(int resourceId){
InputStream iStream = this.getResources().openRawResource(resourceId);
ByteArrayOutputStream byteStream = null;
try {
byte[] buffer = new byte[iStream.available()];
iStream.read(buffer);
byteStream = new ByteArrayOutputStream();
byteStream.write(buffer);
byteStream.close();
iStream.close();
//inflateadapter();
} catch (IOException e) {
e.printStackTrace();
}
return byteStream.toString();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_Recycle"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</layout>
Adapter class
package com.rtstl.expandablelistview.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
import java.util.List;
public class DriverScheduleExpandableAdapter extends ExpandableRecyclerAdapter<DriverSchedule.Schedules, DriverSchedule.Alloted_kids, RouteViewHolder, KidViewHolder> {
private LayoutInflater mInflater;
private List<DriverSchedule.Schedules> mRecipeList;
private static final int PARENT_NORMAL = 1;
private static final int CHILD_NORMAL = 3;
public DriverScheduleExpandableAdapter(Context mContext, #NonNull List<DriverSchedule.Schedules> parentList) {
super(parentList);//////**this is where the app is crashing**
mRecipeList = parentList;
mInflater = LayoutInflater.from(mContext);
}
#NonNull
#Override
public RouteViewHolder onCreateParentViewHolder(#NonNull ViewGroup parentViewGroup, int viewType) {
View recipeView;
switch (viewType) {
default:
case PARENT_NORMAL:
recipeView = mInflater.inflate(R.layout.group_item, parentViewGroup, false);
break;
}
return new RouteViewHolder(recipeView);
}
#NonNull
#Override
public KidViewHolder onCreateChildViewHolder(#NonNull ViewGroup childViewGroup, int viewType) {
View ingredientView;
switch (viewType) {
default:
case CHILD_NORMAL:
ingredientView = mInflater.inflate(R.layout.child_item, childViewGroup, false);
break;
}
return new KidViewHolder(ingredientView);
}
#Override
public void onBindParentViewHolder(#NonNull RouteViewHolder parentViewHolder, int parentPosition, #NonNull DriverSchedule.Schedules parent) {
parentViewHolder.bind(parent);
}
#Override
public void onBindChildViewHolder(#NonNull KidViewHolder childViewHolder, int parentPosition, int childPosition, #NonNull DriverSchedule.Alloted_kids child) {
childViewHolder.bind(child);
}
#Override
public int getParentViewType(int parentPosition) {
return PARENT_NORMAL;
}
#Override
public int getChildViewType(int parentPosition, int childPosition) {
return CHILD_NORMAL;
}
#Override
public boolean isParentViewType(int viewType) {
return viewType == PARENT_NORMAL;
}
}
DriverSchedule.java
package com.rtstl.expandablelistview.model;
import android.databinding.BaseObservable;
import com.bignerdranch.expandablerecyclerview.model.Parent;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by User1 on 09-03-2018.
*/
public class DriverSchedule extends BaseObservable {
#SerializedName("status")
#Expose
public String status;
#SerializedName("msg")
#Expose
public String msg;
#SerializedName("data")
#Expose
public Data data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
#SerializedName("schedules")
#Expose
List<Schedules> sclist;
#SerializedName("driver_details")
#Expose
Driver_details driver_details;
public List<Schedules> getSclist() {
return sclist;
}
public void setSclist(List<Schedules> sclist) {
this.sclist = sclist;
}
public Driver_details getDriver_details() {
return driver_details;
}
public void setDriver_details(Driver_details driver_details) {
this.driver_details = driver_details;
}
}
public class Schedules implements Parent<Alloted_kids> {
#SerializedName("is_active")
#Expose
public String is_active;
#SerializedName("route_details")
#Expose
public Route_details route_details;
#SerializedName("alloted_kids")
#Expose
public List<Alloted_kids> alloted_kids;
public String getIs_active() {
return is_active;
}
public void setIs_active(String is_active) {
this.is_active = is_active;
}
public Route_details getRoute_details() {
return route_details;
}
public void setRoute_details(Route_details route_details) {
this.route_details = route_details;
}
public List<Alloted_kids> getAlloted_kids() {
return alloted_kids;
}
public void setAlloted_kids(List<Alloted_kids> alloted_kids) {
this.alloted_kids = alloted_kids;
}
#Override
public List<Alloted_kids> getChildList() {
return null;
}
#Override
public boolean isInitiallyExpanded() {
return false;
}
}
public class Driver_details {
#SerializedName("driver_details")
#Expose
public Driver_details1 driver_details;
public Driver_details1 getDriver_details() {
return driver_details;
}
public void setDriver_details(Driver_details1 driver_details) {
this.driver_details = driver_details;
}
}
public class Route_details {
#SerializedName("ds_id")
#Expose
public String ds_id;
#SerializedName("kidpool_route_id")
#Expose
public String kidpool_route_id;
public String getDs_id() {
return ds_id;
}
public void setDs_id(String ds_id) {
this.ds_id = ds_id;
}
public String getKidpool_route_id() {
return kidpool_route_id;
}
public void setKidpool_route_id(String kidpool_route_id) {
this.kidpool_route_id = kidpool_route_id;
}
}
public class Alloted_kids {
#SerializedName("kid_name")
#Expose
public String kid_name;
#SerializedName("kid_image")
#Expose
public String kid_image;
public String getKid_name() {
return kid_name;
}
public void setKid_name(String kid_name) {
this.kid_name = kid_name;
}
public String getKid_image() {
return kid_image;
}
public void setKid_image(String kid_image) {
this.kid_image = kid_image;
}
}
public class Driver_details1 {
#SerializedName("driver_id")
#Expose
public String driver_id;
#SerializedName("driver_name")
#Expose
public String driver_name;
public String getDriver_id() {
return driver_id;
}
public void setDriver_id(String driver_id) {
this.driver_id = driver_id;
}
public String getDriver_name() {
return driver_name;
}
public void setDriver_name(String driver_name) {
this.driver_name = driver_name;
}
}
}
KidViewHolder.java
package com.rtstl.expandablelistview.adapter;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ChildViewHolder;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
class KidViewHolder extends ChildViewHolder{
private TextView mIngredientTextView;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
mIngredientTextView = (TextView) itemView.findViewById(R.id.tv_childname);
}
public void bind(#NonNull DriverSchedule.Alloted_kids ingredient) {
mIngredientTextView.setText(ingredient.getKid_name());
}
}
RouteViewHolder.java
package com.rtstl.expandablelistview.adapter;
import android.annotation.SuppressLint;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ParentViewHolder;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
class RouteViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
#NonNull
private final ImageView mArrowExpandImageView;
private TextView mRecipeTextView;
public RouteViewHolder(#NonNull View itemView) {
super(itemView);
mRecipeTextView = (TextView) itemView.findViewById(R.id.group_name);
mArrowExpandImageView = (ImageView) itemView.findViewById(R.id.iv_exp);
}
public void bind(#NonNull DriverSchedule.Schedules recipe) {
mRecipeTextView.setText(recipe.getRoute_details().getKidpool_route_id());
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (expanded) {
mArrowExpandImageView.setRotation(ROTATED_POSITION);
} else {
mArrowExpandImageView.setRotation(INITIAL_POSITION);
}
}
}
#Override
public void onExpansionToggled(boolean expanded) {
super.onExpansionToggled(expanded);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
RotateAnimation rotateAnimation;
if (expanded) { // rotate clockwise
rotateAnimation = new RotateAnimation(ROTATED_POSITION,
INITIAL_POSITION,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
} else { // rotate counterclockwise
rotateAnimation = new RotateAnimation(-1 * ROTATED_POSITION,
INITIAL_POSITION,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
}
rotateAnimation.setDuration(200);
rotateAnimation.setFillAfter(true);
mArrowExpandImageView.startAnimation(rotateAnimation);
}
}
}
See this issue it seems that your list has some null values
https://github.com/bignerdranch/expandable-recycler-view/issues/321
I ran your code and logged your list you have null values in a list
check this method
#Override
public List<Alloted_kids> getChildList() {
return null;
}
this method should return non null value this method only causing problem
use return Collections.emptyList(); instead of return null there
I tried data extraction code from many places but everywhere i get how to retrieve data in a simple list. As the structure of my JSON is complex and i can't change it now, so please help me in retrieving data from firebase database. Please help as i am not able to understand Firebase code. Following is my code and JSON database:
CategoryModel.xml
package com.example.firedb;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Android on 5/31/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList> categoryList;
public CategoryModel() {
}
public CategoryModel(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
// CategoryList
public static class CategoryList {
public int Category_id;
public String Category_name;
public ArrayList<String>Emails;
public ArrayList<String>Epabx;
public ArrayList<String>Category_Fax;
public ArrayList<Persons> persons;
public CategoryList() {
}
//constructor of CategoryList
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
// getters and setters of CategoryList
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
//Persons
public static class Persons {
private int Person_ID;
private String Name;
private String Designation;
private ArrayList<String> Office_Phone;
private ArrayList<String> Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
private ArrayList<String>Extra_info;
private String Category_name;
public Persons() {
}
// Constructor of Persons
public Persons(int person_ID, String name, String designation, ArrayList<String> office_Phone,
ArrayList<String> residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext,
ArrayList<String>extra_info, String category_name) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
Extra_info=extra_info;
Category_name=category_name;
}
// Getter and Setters of Persons
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public ArrayList<String> getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(ArrayList<String> office_Phone) {
Office_Phone = office_Phone;
}
public ArrayList<String> getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(ArrayList<String> residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
public ArrayList<String> getExtra_info() {
return Extra_info;
}
public void setExtra_info(ArrayList<String> extra_info) {
Extra_info = extra_info;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
}
}
CardviewActivity: Earlier i used an asset file but now i want to get data from firebase whose code is ambiguous online
package com.example.firedb;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.LoginFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import static android.R.attr.button;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
TextView toolbar_title_main;
ImageView back_cardviewActivity;
// DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
// db = new DatabaseHandler (CardViewActivity.this);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar_title_main=(TextView)findViewById(R.id.toolbar_title);
// mActionBarToolbar.setTitle("Hry. Govt. Telephone Directory");
// mActionBarToolbar.setLogo(R.drawable.logotoolbar);
// mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_main.setText("Hry. Govt. Telephone Directory");
back_cardviewActivity=(ImageView)findViewById(R.id.back);
back_cardviewActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
// Log.d( "onCreate: ", "List Size: "+categoryLists.size());
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
// JSONObject obj = new JSONObject(readJSONFromAsset());
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
// JSONObject jobE = emailArray.getString(j);
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
// JSONObject jobE = epabxArray.getString(j);
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
// JSONObject jobE = category_FaxJson.getString(j);
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
//this is for Office_Phone array
ArrayList<String>Office_Phone = new ArrayList<>();
JSONArray office_Phone = jobIn.getJSONArray("Office_Phone");
for (int k=0; k < office_Phone.length(); k++)
{
Office_Phone.add(office_Phone.getString(k));
}
//this is for Residence_Phone array
ArrayList<String>Residence_Phone = new ArrayList<>();
JSONArray residence_Phone = jobIn.getJSONArray("Residence_Phone");
for (int k=0; k < residence_Phone.length(); k++)
{
Residence_Phone.add(residence_Phone.getString(k));
}
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
//this is for Extra_info array
ArrayList<String>Extra_info = new ArrayList<>();
JSONArray extra_info = jobIn.getJSONArray("Extra_info");
for (int k=0; k < extra_info.length(); k++)
{
Extra_info.add(extra_info.getString(k));
}
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext,Extra_info,categoryName));
// db.addPerson(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
// VOIP, Address, Fax, Ext,Extra_info));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
// db.addCategory(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
Log.i("cat_name=",""+categoryName);
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
// ((RecyclerViewAdapterMain) mainAdapter).setOnItemClickListener(new RecyclerViewAdapterMain()
// .CategoryClickListener() {
// public void onItemClick(int position, View v) {
// Log.i(LOG_TAG, " Clicked on Item " + position);
// }
// });
}
}
RecyclerViewAdapter:
package com.example.firedb;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
/*TextView category_emails;
TextView category_epabx;
TextView category_fax;*/
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
}
// #Override
// public void onClick(View v) {
// categoryClickListener.onItemClick(getAdapterPosition(), v);
// }
}
// public void setOnItemClickListener(CategoryClickListener categoryClickListener) {
// this.categoryClickListener = categoryClickListener;
// }
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, final int position) {
/*final StringBuilder stringBuilder_emails = new StringBuilder();
for (String email : mcategoryset.get(position).getEmails()) {
if (!stringBuilder_emails.toString().isEmpty()) {
stringBuilder_emails.append(", ");
}
stringBuilder_emails.append(email);
}
final StringBuilder stringBuilder_Epabx = new StringBuilder();
for (String epabx : mcategoryset.get(position).getEpabx()) {
if (!stringBuilder_Epabx.toString().isEmpty()) {
stringBuilder_Epabx.append(", ");
}
stringBuilder_Epabx.append(epabx);
}
final StringBuilder stringBuilder_Category_Fax = new StringBuilder();
for (String category_Fax : mcategoryset.get(position).getCategory_Fax()) {
if (!stringBuilder_Category_Fax.toString().isEmpty()) {
stringBuilder_Category_Fax.append(", ");
}
stringBuilder_Category_Fax.append(category_Fax);
}*/
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
/*holder.category_emails.setText(stringBuilder_emails.toString());
holder.category_epabx.setText(stringBuilder_Epabx.toString());
holder.category_fax.setText(stringBuilder_Category_Fax.toString());*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent (v.getContext(), PeopleListActivity.class);
i.putParcelableArrayListExtra("Persons",mcategoryset.get(position).getPersons());
i.putStringArrayListExtra("emails",mcategoryset.get(position).getEmails());
//i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
The only way to get data from Firebase Database it's using a ValueEventListener.
Firebase work with asynchronous calls, so you can't call the function, get the data and use it. You have to set a ValueEventListener in a specific database reference.
For your actual problem, you have to create an array, set the Firebase Reference, add the ValueEventListener and inside add each occurrence of CategoryList in the array. Finally , still inside of the ValueEventListener, you can create your CategoryModel, with the CategoryList's array as parameter, and update your UI, to see the data in CategoryModel:
CategoryModel categoryModel;
ArrayList<CategoryList> array = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference categoryRef = database.getReference("Category");
categoryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
array.add(categoryList);
}
categoryModel = new CategoryModel(array);
// Method to show the data in category model,
// usually populating an ListView or something
updateUI()
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
For have this working, your CategoryList class has to implement all the setters of his members so "datasnapshot.getValue()" works.
Another approach can be, create a Constructor in CategoryList that recibe a DataSnapshot in this way:
public CategoryList(DataSnapshot snapshot){
Category_id = snapshot.child("Category_id").getValue(int.class);
Category_name = snapshot.child("Category_name").getValue(String.class);
GenericTypeIndicator<List<String>> stringList = new GenericTypeIndicator<List<String>>() {};
Emails = snapshot.child("Emails").getValue(stringList);
Epabx= snapshot.child("Epabx").getValue(stringList);
Category_Fax= snapshot.child("Category_Fax").getValue(stringList);
GenericTypeIndicator<List<Persons>> personsList = new GenericTypeIndicator<List<Persons>>() {};
persons = snapshot.child("Persons").getValue(personsList);
}
If you create the constructor, you have to replace this line:
CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
with this:
CategoryList categoryList = new CategoryList(childSnapshot);
You can see that I use GenericTypeIndicator to work with collections of data, this is a helper class provide for Firebase to work with Lists, Maps, Sets or another Collection.
Just a recommendation! This is not a good data structure, you should denormalize your data.Then you can observe your data by ChildEventListener or ValueEventListener.
For example:
-Category
--CategoryId
---CategoryList
---Persons
----user1: true
----user2: true, etc.
-Users
--user1Id
---user1details
--user2Id
---user2details, etc.
Here is some useful links about denormalizing your data
Link1,
Link2
New to using okhttp and Gson. I am practicing by creating a List View that will display information from Rotten Tomatoes API
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
ListView listView;
Response responseObj;
CustomAdapter adapter;
String url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=9htuhtcb4ymusd73d4z6jxcj";
Gson gson;
OkHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.myList);
client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(com.squareup.okhttp.Response response) throws IOException {
String responseStr = response.body().string();
gson = new Gson();
**responseObj = gson.fromJson(responseStr,Response.class);**
adapter = new CustomAdapter(MainActivity.this, responseObj.getMovies());
listView.setAdapter(adapter);
}
});
}
}
This is the Error I get for line 44
FATAL EXCEPTION: OkHttp Dispatcher
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException:
Invalid double: ""
public class Response {
private String link_template;
/**
* id : 771312089
* title : The Hunger Games: Mockingjay - Part 2
* year : 2015
* mpaa_rating : PG-13
* runtime : 136
* critics_consensus :
* release_dates : {"theater":"2015-11-20"}
* ratings : {"critics_rating":"Fresh","critics_score":70,"audience_rating":"Upright","audience_score":71}
* synopsis : The second half of Suzanne Collins' final Hunger Games book is adapted in this Lionsgate production. ~ Jeremy Wheeler, Rovi
* posters : {"thumbnail":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg","profile":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg","detailed":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg","original":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg"}
* abridged_cast : [{"name":"Jennifer Lawrence","id":"770800260","characters":["Katniss Everdeen"]},{"name":"Julianne Moore","id":"162654248","characters":["President Alma Coin"]},{"name":"Gwendoline Christie","id":"771060732","characters":["Commander Lyme"]},{"name":"Josh Hutcherson","id":"162654356","characters":["Peeta Mellark"]},{"name":"Robert Knepper","id":"162707688","characters":["Antonius"]}]
* links : {"self":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089.json","alternate":"http://www.rottentomatoes.com/m/the_hunger_games_mockingjay_part_2/","cast":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/cast.json","reviews":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/reviews.json","similar":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/similar.json"}
*/
private List<MoviesEntity> movies;
public void setLinks(LinksEntity links) {
this.links = links;
}
public void setLink_template(String link_template) {
this.link_template = link_template;
}
public void setMovies(List<MoviesEntity> movies) {
this.movies = movies;
}
public LinksEntity getLinks() {
return links;
}
public String getLink_template() {
return link_template;
}
public List<MoviesEntity> getMovies() {
return movies;
}
public static class LinksEntity {
private String self;
private String alternate;
public void setSelf(String self) {
this.self = self;
}
public void setAlternate(String alternate) {
this.alternate = alternate;
}
public String getSelf() {
return self;
}
public String getAlternate() {
return alternate;
}
}
public static class MoviesEntity {
private String id;
private String title;
private int year;
private String mpaa_rating;
private int runtime;
private String critics_consensus;
/**
* theater : 2015-11-20
*/
private ReleaseDatesEntity release_dates;
/**
* critics_rating : Fresh
* critics_score : 70
* audience_rating : Upright
* audience_score : 71
*/
private RatingsEntity ratings;
private String synopsis;
/**
* thumbnail : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
* profile : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
* detailed : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
* original : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
*/
private PostersEntity posters;
/**
* self : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089.json
* alternate : http://www.rottentomatoes.com/m/the_hunger_games_mockingjay_part_2/
* cast : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/cast.json
* reviews : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/reviews.json
* similar : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/similar.json
*/
private LinksEntity links;
/**
* name : Jennifer Lawrence
* id : 770800260
* characters : ["Katniss Everdeen"]
*/
private List<AbridgedCastEntity> abridged_cast;
public void setId(String id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setYear(int year) {
this.year = year;
}
public void setMpaa_rating(String mpaa_rating) {
this.mpaa_rating = mpaa_rating;
}
public void setRuntime(int runtime) {
this.runtime = runtime;
}
public void setCritics_consensus(String critics_consensus) {
this.critics_consensus = critics_consensus;
}
public void setRelease_dates(ReleaseDatesEntity release_dates) {
this.release_dates = release_dates;
}
public void setRatings(RatingsEntity ratings) {
this.ratings = ratings;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public void setPosters(PostersEntity posters) {
this.posters = posters;
}
public void setLinks(LinksEntity links) {
this.links = links;
}
public void setAbridged_cast(List<AbridgedCastEntity> abridged_cast) {
this.abridged_cast = abridged_cast;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public int getYear() {
return year;
}
public String getMpaa_rating() {
return mpaa_rating;
}
public int getRuntime() {
return runtime;
}
public String getCritics_consensus() {
return critics_consensus;
}
public ReleaseDatesEntity getRelease_dates() {
return release_dates;
}
public RatingsEntity getRatings() {
return ratings;
}
public String getSynopsis() {
return synopsis;
}
public PostersEntity getPosters() {
return posters;
}
public LinksEntity getLinks() {
return links;
}
public List<AbridgedCastEntity> getAbridged_cast() {
return abridged_cast;
}
public static class ReleaseDatesEntity {
private String theater;
public void setTheater(String theater) {
this.theater = theater;
}
public String getTheater() {
return theater;
}
}
public static class RatingsEntity {
private String critics_rating;
private int critics_score;
private String audience_rating;
private int audience_score;
public void setCritics_rating(String critics_rating) {
this.critics_rating = critics_rating;
}
public void setCritics_score(int critics_score) {
this.critics_score = critics_score;
}
public void setAudience_rating(String audience_rating) {
this.audience_rating = audience_rating;
}
public void setAudience_score(int audience_score) {
this.audience_score = audience_score;
}
public String getCritics_rating() {
return critics_rating;
}
public int getCritics_score() {
return critics_score;
}
public String getAudience_rating() {
return audience_rating;
}
public int getAudience_score() {
return audience_score;
}
}
public static class PostersEntity {
private String thumbnail;
private String profile;
private String detailed;
private String original;
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public void setProfile(String profile) {
this.profile = profile;
}
public void setDetailed(String detailed) {
this.detailed = detailed;
}
public void setOriginal(String original) {
this.original = original;
}
public String getThumbnail() {
return thumbnail;
}
public String getProfile() {
return profile;
}
public String getDetailed() {
return detailed;
}
public String getOriginal() {
return original;
}
}
public static class LinksEntity {
private String self;
private String alternate;
private String cast;
private String reviews;
private String similar;
public void setSelf(String self) {
this.self = self;
}
public void setAlternate(String alternate) {
this.alternate = alternate;
}
public void setCast(String cast) {
this.cast = cast;
}
public void setReviews(String reviews) {
this.reviews = reviews;
}
public void setSimilar(String similar) {
this.similar = similar;
}
public String getSelf() {
return self;
}
public String getAlternate() {
return alternate;
}
public String getCast() {
return cast;
}
public String getReviews() {
return reviews;
}
public String getSimilar() {
return similar;
}
}
public static class AbridgedCastEntity {
private String name;
private String id;
private List<String> characters;
public void setName(String name) {
this.name = name;
}
public void setId(String id) {
this.id = id;
}
public void setCharacters(List<String> characters) {
this.characters = characters;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public List<String> getCharacters() {
return characters;
}
}
}
}
package com.example.nano1.gsonexample;
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 com.squareup.picasso.Picasso;
import java.util.List;
public class CustomAdapter extends BaseAdapter {
private List<Response.MoviesEntity> mMovieItem;
private Context context;
private LayoutInflater inflater;
public CustomAdapter(Context context, List<Response.MoviesEntity> mMovieItem) {
this.context = context;
this.mMovieItem = mMovieItem;
}
#Override
public int getCount() {
return mMovieItem.size();
}
#Override
public Object getItem(int position) {
return mMovieItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.each_list_item, parent, false);
Response.MoviesEntity item = (Response.MoviesEntity) getItem(position);
ImageView thumbnail = (ImageView) rowView.findViewById(R.id.thumnnail);
TextView title = (TextView) rowView.findViewById(R.id.title);
TextView rating = (TextView) rowView.findViewById(R.id.rating);
String imageURL = item.getPosters().getOriginal();
Picasso.with(context).load(imageURL).into(thumbnail);
title.setText(item.getTitle());
rating.setText(item.getRatings().getAudience_rating());
return rowView;
}
}
in the declared classes above you have members of type int now in the response you are getting values for these members as empty string "" which is not allowed, it should be an integer. that makes the exception, you either:
1- change member type to String, and handle empty string as 0 in the setters/getters
or
2- ask the back-end team to send correct data
or
3- use a custom TypedAdapter in the Gson converter to handle integers when they have empty string
P.S: i am aware the sample json does not contain empty strings but on the real call on the service, you might have an empty strings for integer members