This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 5 years ago.
Can you help me to solving this error? Where is the problem?
private final String TAG = "MulaiUjian";
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private RecycleViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mulai_ujian);
recyclerView = (RecyclerView)findViewById(R.id.recycle_txtSoal);
layoutManager = new LinearLayoutManager(MulaiUjian.this);
recyclerView.setLayoutManager(layoutManager);
requestJsonObject();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
private void requestJsonObject(){
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://www.rootorial.com/worthit2/resgister/showalluser.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<ItemObject> posts = new ArrayList<ItemObject>();
posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
adapter = new RecycleViewAdapter(MulaiUjian.this, posts);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
}
Stacktrace:
Process: com.example.root.pmb, PID: 7806
**com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was
BEGIN_OBJECT at line 1 column 2 path $**
at com.google.gson.Gson.fromJson(Gson.java:826)
at com.google.gson.Gson.fromJson(Gson.java:779)
at com.google.gson.Gson.fromJson(Gson.java:728)
at com.google.gson.Gson.fromJson(Gson.java:700)
at com.example.root.pmb.MulaiUjian$1.onResponse(MulaiUjian.java:59)
at com.example.root.pmb.MulaiUjian$1.onResponse(MulaiUjian.java:52)
at
com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at
com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at
com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but
was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
at
com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:70)
at com.google.gson.Gson.fromJson(Gson.java:814)
at com.google.gson.Gson.fromJson(Gson.java:779)
at com.google.gson.Gson.fromJson(Gson.java:728)
at com.google.gson.Gson.fromJson(Gson.java:700)
at com.example.root.pmb.MulaiUjian$1.onResponse(MulaiUjian.java:59)
at com.example.root.pmb.MulaiUjian$1.onResponse(MulaiUjian.java:52)
at
com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at
com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at
com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
The problem is that, your whole JSON response is a JSONObject if see it carefully.
{
"id_soal": [{
"id_soal": "So0045",
"isi_soal": "Pemilihan Umum tahun 1999 diikuti oleh:",
"bobot_nilai": "1",
"jawab_a": "10 partai politik",
"jawab_b": "18 partai politik",
"jawab_c": "45 partai politik",
"jawab_d": "48 partai politik",
"jawaban_benar": "D"
}, {
"id_soal": "So0039",
"isi_soal": "Prinsup Pembangunan Berkelanjutan adalah :",
"bobot_nilai": "1",
"jawab_a": "Pembangunan terus menerus",
"jawab_b": "Pembangunan yang tidak merusak lingkungan",
"jawab_c": "Pembangunan yang mempertimbangkan kehidupan generasiyang akan datang",
"jawab_d": "Pembangunan yang sesuai rencana pemerintah",
"jawaban_benar": "C"
}, {
"id_soal": "So0065",
"isi_soal": "Dimanakah tempat dibacakan naskah Proklamasi Indonesia ?",
"bobot_nilai": "1",
"jawab_a": "Jl. Diponogoro No. 56",
"jawab_b": "Jl. Pegangsaan timur No. 56",
"jawab_c": "Jl. Teuku Umar No. 67",
"jawab_d": "Jl. Cokroaminoto No. 67",
"jawaban_benar": "B"
}
}
and for Gson to parse your Response Successfully you need to need to Have two model class like below
public class ItemObject {
private List<IdSoal> id_soal = null;
private Integer success;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public List<IdSoal> getIdSoal() {
return id_soal;
}
public void setIdSoal(List<IdSoal> idSoal) {
this.id_soal = idSoal;
}
public Integer getSuccess() {
return success;
}
public void setSuccess(Integer success) {
this.success = success;
}
}
and,
public class IdSoal {
private String id_soal;
private String isi_soal;
private String bobot_nilai;
private String jawab_a;
private String jawab_b;
private String jawab_c;
private String jawab_d;
private String jawaban_benar;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getId_soal() {
return id_soal;
}
public void setId_soal(String id_soal) {
this.id_soal = id_soal;
}
public String getIsi_soal() {
return isi_soal;
}
public void setIsi_soal(String isi_soal) {
this.isi_soal = isi_soal;
}
public String getBobot_nilai() {
return bobot_nilai;
}
public void setBobot_nilai(String bobot_nilai) {
this.bobot_nilai = bobot_nilai;
}
public String getJawab_a() {
return jawab_a;
}
public void setJawab_a(String jawab_a) {
this.jawab_a = jawab_a;
}
public String getJawab_b() {
return jawab_b;
}
public void setJawab_b(String jawab_b) {
this.jawab_b = jawab_b;
}
public String getJawab_c() {
return jawab_c;
}
public void setJawab_c(String jawab_c) {
this.jawab_c = jawab_c;
}
public String getJawab_d() {
return jawab_d;
}
public void setJawab_d(String jawab_d) {
this.jawab_d = jawab_d;
}
public String getJawaban_benar() {
return jawaban_benar;
}
public void setJawaban_benar(String jawaban_benar) {
this.jawaban_benar = jawaban_benar;
}
}
then all you need to do is like this
ItemObject itemObject = mGson.fromJson(response, ItemObject.class));
You probably need to check your models or the response you are receiving. You are using ItemObject[].class) but might be expecting an object so deserialization is failing.
Related
I am having this issue for some time now, when I retrieved data from a database using volley and then show it in a recycler view, if the items are 8 or less than 8 then it shows them without any problem, but if I retrieve more than 8 items from database then the activity closes/crashes and goes back to the main activity. I don't get any error in the run console in android studio. I am retrieving 3 things from database for a single item, 2 strings and an image. I don't think the error is in the php file which is used to get the data as that I have checked and it retrieves without any issue. I have searched android documentation of recycler view but couldn't find anything
NOTE: I am getting image as string and then converting to bitmap.
if there is anything else needed then I can provide them without any issue.
the code is below:
Method which is used to call the recycler view activity which has problems.
public void onViewAttendanceButtonClick(int position, String courseCode,
String courseName, String batchName) {
if (MainActivity.teacherData != null) {
seeAttendanceDetails(MainActivity.teacherData.getEmail(),courseCode,
batchName, courseName, getDateAndTime);
}
}
private void seeAttendanceDetails(final String email,final String
courseCode, final String batchName,final String courseName, final String
date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
seeAttendanceDetails, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
String fullName = data.getString("full_name");
String Email = data.getString("email");
String photo = data.getString("photo");
Toast.makeText(CoursesActivity.this, courseCode,
Toast.LENGTH_LONG).show();
Attendance attendance1 = new Attendance(fullName, Email, photo);
attendanceArrayList.add(attendance1);
}
if (!attendanceArrayList.isEmpty()) {
Intent intent = new Intent(CoursesActivity.this,
ShowAttendanceActivity.class);
Bundle bundle = new Bundle();
bundle.putString("attendanceCourseCode",
courseCode);
bundle.putString("attendanceCourseName",
courseName);
bundle.putString("attendanceBatchName", batchName);
bundle.putSerializable("attendanceList",
attendanceArrayList);
intent.putExtras(bundle);
startActivity(intent);
}
else if (RegistrationActivity.teacherData != null) {
//
seeAttendanceDetails(RegistrationActivity.teacherData.getEmail(),
batchName,courseName, getDateAndTime);
// Toast.makeText(CoursesActivity.this,"No Record
Found",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CoursesActivity.this,
error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("batch", batchName);
params.put("date", date);
params.put("courseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
<br/>
The recycler view activity code
public class ShowAttendanceActivity extends AppCompatActivity implements
ShowAttendanceActivityAdapter.RemoveAttendanceClickListener {
private RecyclerView recyclerView;
private String courseCode,courseName,batchName;
private ArrayList<Attendance> attendanceArrayList = new ArrayList<>();
private TextView
textViewCourseCode,textViewCourseName,textViewBatchName;
private String deleteStudentAttendance =
"https://asuiot.umargulzar.com/Teacher%20API%2
0Files/deleteStudentattendance.php";
int success;
private String TAG_SUCCESS = "success";
private String TAG_MESSAGE = "message";
private String getDateAndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_attendance);
recyclerView = findViewById(R.id.attendance_details_recyclerView);
textViewCourseCode = findViewById(R.id.SA_textView_course_code);
textViewCourseName = findViewById(R.id.SA_textView_course_name);
textViewBatchName = findViewById(R.id.SA_textView_Batch);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
Calendar calendar = Calendar.getInstance();
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyy hh:mm:ss a");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
String dateTime = simpleDateFormat.format(calendar.getTime());
this.getDateAndTime = dateTime;
courseCode = (String) getIntent().getStringExtra("attendanceCourseCode");
courseName = (String) getIntent().getStringExtra("attendanceCourseName");
batchName = (String) getIntent().getStringExtra("attendanceBatchName");
attendanceArrayList = (ArrayList<Attendance>) getIntent().getExtras().getSerializable("attendanceList");
textViewCourseCode.setText(courseCode);
textViewCourseName.setText(courseName);
textViewBatchName.setText(batchName);
recyclerView.setAdapter(new ShowAttendanceActivityAdapter(attendanceArrayList,this));
}
#Override
public void onRemoveAttendanceClick(int position,String email) {
// Toast.makeText(ShowAttendanceActivity.this,"The Email of Student:"+email,Toast.LENGTH_LONG).show();
if(MainActivity.teacherData !=null){
deleteStudentAttendance(email,getDateAndTime,courseCode);
}
}
private void deleteStudentAttendance(final String email, final String getDateAndTime,final String courseCode) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, deleteStudentAttendance, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE)+" Plz refresh the page.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", email);
params.put("Date",getDateAndTime);
params.put("CourseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
the recycler view activity adapter
public class ShowAttendanceActivityAdapter extends RecyclerView.Adapter<ShowAttendanceActivityAdapter.AttendanceView> {
private ArrayList<Attendance> attendanceData;
Bitmap bitmap;
private RemoveAttendanceClickListener removeAttendanceClickListener;
public ShowAttendanceActivityAdapter(ArrayList<Attendance> attendanceData,RemoveAttendanceClickListener removeAttendanceClickListener){
this.attendanceData = attendanceData;
this.removeAttendanceClickListener = removeAttendanceClickListener;
}
#NonNull
#Override
public AttendanceView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_attendance_data,parent,false);
return new AttendanceView(view,removeAttendanceClickListener);
}
#Override
public void onBindViewHolder(#NonNull AttendanceView holder, int position) {
Attendance attendance = attendanceData.get(position);
holder.textViewName.setText(attendance.getStudentName());
// holder.textViewEmail.setText(attendance.getStudentEmail());
holder.textViewEmail.setText(attendance.getStudentEmail());
decodeStringToImage(attendance.getStudentPhoto());
holder.imageViewPhoto.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return attendanceData.size();
}
public void decodeStringToImage(String photo) {
// Bitmap bitmap = photo.
byte[] bytes = Base64.decode(photo, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public class AttendanceView extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textViewName, textViewEmail;
ImageView imageViewPhoto;
Button buttonRemoveCourse;
RemoveAttendanceClickListener removeAttendanceClickListener;
public AttendanceView(#NonNull View itemView,RemoveAttendanceClickListener removeAttendanceClickListener) {
super(itemView);
textViewName = itemView.findViewById(R.id.textView_name);
textViewEmail = itemView.findViewById(R.id.textView_Email);
imageViewPhoto = itemView.findViewById(R.id.textView_SA_Photo);
this.removeAttendanceClickListener = removeAttendanceClickListener;
buttonRemoveCourse = itemView.findViewById(R.id.btn_remove_attendance);
buttonRemoveCourse.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_remove_attendance:
removeAttendanceClickListener.onRemoveAttendanceClick(getAdapterPosition(),textViewEmail.getText().toString());
break;
}
}
}
public interface RemoveAttendanceClickListener{
void onRemoveAttendanceClick(int position,String email);
}
}
You are probably getting OutOfMemory exception while converting bytes array in to bitmap if the image sizes are huge.
Add try catch in your decodeStringToImage method where you are converting bitmaps and check the log when you load more than 8 images.
I tried using GenericTypeIndicator in a recycler view to set A Array of data to a recycler view inside a recycler view.
The GenericTypeIndicator throws an error that causes the application to crash.
I tried figuring out the error but it seems it was expecting a list but got a Hashmap instead.
public class ScheduleOrder extends AppCompatActivity implements IFirebaseLoadListener {
DeviceSession deviceSession;
UserSession userSession;
String Device_Id="",User_Id="";
IFirebaseLoadListener iFirebaseLoadListener;
RecyclerView my_recycler_view;
DatabaseReference myData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_order);
deviceSession = new DeviceSession(getApplicationContext());
Device_Id = deviceSession.getDeviceDetails();
userSession = new UserSession(getApplicationContext());
final HashMap<String, String> user = userSession.getUserDetails();
User_Id = user.get(UserSession.User_Id);
FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.schedule_add);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),Schedule_Order.class);
startActivity(i);
finish();
}
});
myData=FirebaseDatabase.getInstance().getReference("Cart_Schedule"+"/"+Device_Id);
iFirebaseLoadListener=this;
my_recycler_view=findViewById(R.id.my_recyclr_view);
my_recycler_view.setHasFixedSize(true);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this));
getFirebaseData();
}
private void getFirebaseData() {
myData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<ItemGroup>itemGroups=new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){
ItemGroup itemGroup=new ItemGroup();
for(DataSnapshot newdatasnap:groupSnapShot.child("listItem").getChildren()){
itemGroup.setD_Time(groupSnapShot.child("d_Time").getValue(true).toString());
itemGroup.setF_Amount(groupSnapShot.child("f_Amount").getValue(true).toString());
GenericTypeIndicator<ArrayList<ItemData>> genericTypeIndicator=new GenericTypeIndicator<ArrayList<ItemData>>(){};
Log.d("JADOO", "onDataChange: ??? "+genericTypeIndicator);
// Log.d("JADOO", "onDataChange: ??? "+itemData1.getB_Quantity());
// Log.d("JADOO", "onDataChange: ??? "+itemData1.getC_Price());
itemGroup.setListItem(newdatasnap.getValue(genericTypeIndicator));
itemGroups.add(itemGroup);
}}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<ItemGroup> itemGroupList) {
MyItemGroupAdapter adapter = new MyItemGroupAdapter(this,itemGroupList);
my_recycler_view.setAdapter(adapter);
}
#Override
public void onFirebaseLoadFailed(String message) {
}
}
ItemData.java
private String a_Item_name;
private String b_Quantity;
private String c_Price;
private String d_Time;
private String e_ID;
private String f_Amount;
private String g_COD;
private String h_Address;
public ItemData(){
}
public ItemData(String a_Item_name,String b_Quantity,String c_Price, String d_Time, String e_ID,String f_Amount, String g_COD,String h_Address)
{
this.a_Item_name=a_Item_name;
this.b_Quantity=b_Quantity;
this.c_Price=c_Price;
this.d_Time=d_Time;
this.e_ID=e_ID;
this.f_Amount=f_Amount;
this.g_COD=g_COD;
this.h_Address=h_Address;
}
public String getA_Item_name() {
return a_Item_name;
}
public void setA_Item_name(String a_Item_name) {
this.a_Item_name = a_Item_name;
}
public String getB_Quantity() {
return b_Quantity;
}
public void setB_Quantity(String b_Quantity) {
this.b_Quantity = b_Quantity;
}
public String getC_Price() {
return c_Price;
}
public void setC_Price(String c_Price) {
this.c_Price = c_Price;
}
public String getD_Time() {
return d_Time;
}
public void setD_Time(String d_Time) {
this.d_Time = d_Time;
}
public String getE_ID() {
return e_ID;
}
public void setE_ID(String e_ID) {
this.e_ID = e_ID;
}
public String getF_Amount() {
return f_Amount;
}
public void setF_Amount(String f_Amount) {
this.f_Amount = f_Amount;
}
public String getG_COD() {
return g_COD;
}
public void setG_COD(String g_COD) {
this.g_COD = g_COD;
}
public String getH_Address() {
return h_Address;
}
public void setH_Address(String h_Address) {
this.h_Address = h_Address;
}
}
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.food.pilo, PID: 1501
com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToParameterizedType(com.google.firebase:firebase-database##16.0.4:233)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database##16.0.4:176)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.4:101)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.4:239)
at com.food.pilo.ScheduleOrder$2.onDataChange(ScheduleOrder.java:111)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##16.0.4:183)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)```
FireBase Database Screenshot attached with fields of data that needs to retracted
Based on the provided screenshot, the data at */someGroup/listItem/someChild has the shape of an ItemData object. Inside your onDataChange() handler you are trying to read the value of */someGroup/listItem/someChild as an array using a GenericTypeIndicator, which is failing because it's not an array. This is fixed by passing in the class reference to ItemData instead.
List<ItemGroup>itemGroups=new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){
// moved: outside of loop so that values only processed once (for performance)
String group_d_Time = groupSnapShot.child("d_Time").getValue(true).toString()
String group_f_Amount = groupSnapShot.child("f_Amount").getValue(true).toString()
for(DataSnapshot newdatasnap:groupSnapShot.child("listItem").getChildren()) {
ItemGroup itemGroup = new ItemGroup(); // moved: inside loop to create new object on each loop
itemGroup.setD_Time(group_d_Time);
itemGroup.setF_Amount(group_f_Amount);
itemGroup.setListItem(newdatasnap.getValue(ItemData.class)); // changed: value of newdatasnap is an ItemData object, not an array of ItemData objects
itemGroups.add(itemGroup);
}
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
why my data cant show, the error in logcat is "No adapter attached; skipping layout" and "the mapper function return null",
this my viewModel i get my api in here Model.java
public class Model extends ViewModel {
private static final String API_KEY = "my-api";
private MutableLiveData<ArrayList<MoviesItems>> listMovies = new MutableLiveData<>();
void setMovies(){
AsyncHttpClient client = new AsyncHttpClient();
final ArrayList<MoviesItems> listItems = new ArrayList<>();
String url = "https://api.themoviedb.org/3/discover/movie?api_key=" + API_KEY + "&language=en-US";
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String result = new String(responseBody);
JSONObject object = new JSONObject(result);
JSONArray list = object.getJSONArray("results");
for (int i = 0;1 < list.length(); i++){
JSONObject movies = list.getJSONObject(i);
MoviesItems moviesItems = new MoviesItems(movies);
listItems.add(moviesItems);
}
listMovies.getValue();
}catch (Exception e){
Log.d("Exception", e.getMessage());
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("onFailure", error.getMessage());
}
});
}
public LiveData<ArrayList<MoviesItems>> getMovies(){
return listMovies;
}
}
and this my fragment i think my error in here MoviesFragment.java
View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
viewModel = ViewModelProviders.of(this).get(Model.class);
viewModel.getMovies().observe(this, getMovie);
//pb = rootView.findViewById(R.id.pb);
moviesAdapter = new MoviesAdapter(getActivity());
moviesAdapter.notifyDataSetChanged();
rv_grid_movies = rootView.findViewById(R.id.rv_grid_movies);
RecyclerView.LayoutManager manager = new GridLayoutManager(getActivity(), 2);
rv_grid_movies.setLayoutManager(manager);
rv_grid_movies.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(3), true));
rv_grid_movies.setItemAnimator(new DefaultItemAnimator());
rv_grid_movies.setAdapter(moviesAdapter);
rv_grid_movies.setHasFixedSize(true);
return rootView;
}
private Observer<ArrayList<MoviesItems>> getMovie = new Observer<ArrayList<MoviesItems>>() {
#Override
public void onChanged(#Nullable ArrayList<MoviesItems> moviesItems) {
if (moviesItems != null){
moviesAdapter.setData(moviesItems);
//loadData(false);
}
}
};
this my modelitems this place i get jsonObject MoviesItems.java
public MoviesItems(JSONObject object){
try {
//JSONArray array = object.getJSONArray("results");
int id = object.getInt("id");
String title = object.getString("title");
String overview = object.getString("overview");
String poster_path = object.getString("poster_path");
String release_date = object.getString("release_date");
this.id = id;
this.title = title;
this.overview = overview;
this.poster_path = poster_path;
this.release_date = release_date;
}catch (Exception e){
e.printStackTrace();
}
}
and this my adapter MoviesAdapter.java
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder> {
private ArrayList<MoviesItems> mItems;
private Context context;
public MoviesAdapter(Context context){
this.context = context;
}
public void setData(ArrayList<MoviesItems> mItems) {
mItems.clear();
mItems.addAll(mItems);
notifyDataSetChanged();
}
public void addItems(final MoviesItems moviesItems){
mItems.add(moviesItems);
notifyDataSetChanged();
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
private void clearData(){
mItems.clear();
}
#NonNull
#Override
public MoviesViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.grid_movies, viewGroup, false);
final MoviesViewHolder holder = new MoviesViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MoviesViewHolder moviesViewHolder, int i) {
moviesViewHolder.bind(mItems.get(i));
}
#Override
public int getItemCount() {
return (mItems != null) ? mItems.size(): 0;
}
public class MoviesViewHolder extends RecyclerView.ViewHolder {
TextView txt_title_movies, txt_date_movies, txt_description_movies;
ImageView img_movies;
String url = "https://image.tmdb.org/t/p/original";
public MoviesViewHolder(#NonNull View itemView) {
super(itemView);
txt_title_movies = itemView.findViewById(R.id.txt_titlemovie);
txt_date_movies = itemView.findViewById(R.id.txt_datemovie);
txt_description_movies = itemView.findViewById(R.id.txt_descriptionmovie);
img_movies = itemView.findViewById(R.id.img_movie);
}
public void bind(MoviesItems moviesItems) {
txt_title_movies.setText(moviesItems.getTitle());
txt_date_movies.setText(moviesItems.getRelease_date());
txt_description_movies.setText(moviesItems.getOverview());
Glide.with(context)
.load(url+moviesItems.getPoster_path())
.into(img_movies);
}
}
}
and this json i want get
{
"page": 1,
"total_results": 432039,
"total_pages": 21602,
"results": [
{
"vote_count": 672,
"id": 384018,
"video": false,
"vote_average": 6.5,
"title": "Fast & Furious Presents: Hobbs & Shaw",
"popularity": 317.725,
"poster_path": "/keym7MPn1icW1wWfzMnW3HeuzWU.jpg",
"original_language": "en",
"original_title": "Fast & Furious Presents: Hobbs & Shaw",
"genre_ids": [
28
],
"backdrop_path": "/hpgda6P9GutvdkDX5MUJ92QG9aj.jpg",
"adult": false,
"overview": "A spinoff of The Fate of the Furious, focusing on Johnson's US Diplomatic Security Agent Luke Hobbs forming an unlikely alliance with Statham's Deckard Shaw.",
"release_date": "2019-08-01"
},
and this my error
java.lang.NullPointerException: The mapper function returned a null value.
at io.reactivex.d.b.b.a(ObjectHelper.java:39)
at io.reactivex.d.e.b.g$a.onNext(ObservableMap.java:59)
at io.reactivex.d.e.b.i$a.run(ObservableScalarXMap.java:248)
at io.reactivex.d.e.b.f.b(ObservableJust.java:35)
at io.reactivex.h.a(Observable.java:11442)
at io.reactivex.d.e.b.g.b(ObservableMap.java:33)
at io.reactivex.h.a(Observable.java:11442)
at io.reactivex.d.e.b.l$b.run(ObservableSubscribeOn.java:96)
at io.reactivex.a.b.b$b.run(HandlerScheduler.java:109)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
Screen Image
In MoviesFragment.java inside observer of ArrayList<MoviesItems> onChanged() method call moviesAdapter.notifyDataSetChanged(); after the moviesAdapter.setData(moviesItems);
On response of your API, you aren't setting up newly received value in LiveData variable.
So make below changes and your code will work.
void setMovies(){
AsyncHttpClient client = new AsyncHttpClient();
final ArrayList<MoviesItems> listItems = new ArrayList<>();
String url = "https://api.themoviedb.org/3/discover/movie?api_key=" + API_KEY + "&language=en-US";
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String result = new String(responseBody);
JSONObject object = new JSONObject(result);
JSONArray list = object.getJSONArray("results");
for (int i = 0;1 < list.length(); i++){
JSONObject movies = list.getJSONObject(i);
MoviesItems moviesItems = new MoviesItems(movies);
listItems.add(moviesItems);
}
// Replace below line.
// listMovies.getValue();
// With
listMovies.setValue(listItems);
}catch (Exception e){
Log.d("Exception", e.getMessage());
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("onFailure", error.getMessage());
}
});
}
UPDATE 2:
Change position of code as below in fragment.
viewModel = ViewModelProviders.of(this).get(Model.class);
//pb = rootView.findViewById(R.id.pb);
moviesAdapter = new MoviesAdapter(getActivity());
moviesAdapter.notifyDataSetChanged();
rv_grid_movies = rootView.findViewById(R.id.rv_grid_movies);
RecyclerView.LayoutManager manager = new GridLayoutManager(getActivity(), 2);
rv_grid_movies.setLayoutManager(manager);
rv_grid_movies.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(3), true));
rv_grid_movies.setItemAnimator(new DefaultItemAnimator());
rv_grid_movies.setAdapter(moviesAdapter);
rv_grid_movies.setHasFixedSize(true);
// Add observer here, after initialising adapter and recyclerview.
viewModel.getMovies().observe(this, getMovie);
Trying to convert JSON array to list of objects using Gson library.
Code:
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {}; //this line throws the following exception
public class Comment implements Serializable{
#SerializedName("id")
private int mID;
#SerializedName("content")
private String mContent;
#SerializedName("author")
private String mAuthor;
#SerializedName("author_id")
private int mAuthorID;
#SerializedName("author_email")
private String mAuthorEmail;
#SerializedName("date")
private String mDate;
#SerializedName("name")
private String mName;
#SerializedName("image")
private String mImage;
public int getmID() {
return mID;
}
public void setmID(int mID) {
this.mID = mID;
}
public String getmContent() {
return mContent;
}
public void setmContent(String mContent) {
this.mContent = mContent;
}
public String getmAuthor() {
return mAuthor;
}
public void setmAuthor(String mAuthor) {
this.mAuthor = mAuthor;
}
public int getmAuthorID() {
return mAuthorID;
}
public void setmAuthorID(int mAuthorID) {
this.mAuthorID = mAuthorID;
}
public String getmAuthorEmail() {
return mAuthorEmail;
}
public void setmAuthorEmail(String mAuthorEmail) {
this.mAuthorEmail = mAuthorEmail;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmImage() {
return mImage;
}
public void setmImage(String mImage) {
this.mImage = mImage;
}
}
public class CommentListingActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "CommentListingActivity";
private ListView mListViewComments;
private CommentAdapter mCommentAdapter;
private ArrayList<Comment> mCommentList = new ArrayList<Comment>();
private ProgressBar mProgressBar;
private TextView mTextViewErrorMessage;
private Button mButtonRefresh;
private LinearLayout mLinearLayoutError;
private int mPostID;
private boolean isCommentListLoading = true;
private EditText mEditTextComment;
private ImageView mImageViewSend;
private InputMethodManager mInputMethodManager;
private SwipeRefreshLayout mSwipeRefreshLayout;
private boolean mIsRefreshing = false;
private int mOffset = 0;
private View mProgressBarView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_listing);
mPostID = getIntent().getIntExtra("postID",0);
setToolbar();
setToolBarTitle(getString(R.string.commentsLabel));
setToolbarHomeAsUpEnabled(true);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
mIsRefreshing = true;
mOffset = 0;
fetchComments();
}
});
mListViewComments = (ListView) findViewById(R.id.listViewComments);
mCommentAdapter = new CommentAdapter(this, mCommentList,mImageLoader);
mListViewComments.setAdapter(mCommentAdapter);
mProgressBarView = getLayoutInflater().inflate(R.layout.recyclerview_loading_item,null);
mListViewComments.addFooterView(mProgressBarView);
// set the custom dialog components - text, image and button
mEditTextComment = (EditText) findViewById(R.id.editTextComment);
mImageViewSend = (ImageView) findViewById(R.id.imageViewSend);
mImageViewSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postComment();
}
});
mEditTextComment.requestFocus();
mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
initProgressBar();
initErrorView();
mListViewComments.setOnScrollListener(new EndlessScrollListener() {
#Override
public boolean onLoadMore(int page, int totalItemsCount) {
mOffset = mOffset + LIST_LIMIT;
mListViewComments.addFooterView(mProgressBarView);
fetchComments();
return true;
}
});
fetchComments();
}
private void fetchComments(){
if (!mIsRefreshing && mCommentAdapter.getCount()==0)
showProgressBar();
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("post",String.valueOf(mPostID));
parameters.put("offset",String.valueOf(mOffset));
NetworkUtility.getJSONRquest(this, APIURLs.LIST_COMMENTS, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Remove loading item
if(mCommentList.size()>0) {
mListViewComments.removeFooterView(mProgressBarView);
}
try {
if(response.getString(API_KEY_STATUS).equalsIgnoreCase(API_RESPONSE_SUCCESS)){
JSONArray jsonArrayComments = response.getJSONArray(API_KEY_DATA);
if(jsonArrayComments.length()>0) {
if (mIsRefreshing) {
mCommentList.clear();
mCommentAdapter.notifyDataSetChanged();
}
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
mCommentList.addAll((Collection<? extends Comment>) GsonUtility.convertJSONStringToObject(jsonArrayComments.toString(), token));
mCommentAdapter.notifyDataSetChanged();
}
mIsRefreshing = false;
if(mCommentAdapter.getCount()>0) {
showContent();
} else {
if (mOffset == 0)
showError("No comments found.");
}
} else {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),response.getString(API_KEY_MESSAGE),getString(R.string.okLabel),null,null,null);
} else
showError(response.getString(API_KEY_MESSAGE));
}
} catch (JSONException e) {
e.printStackTrace();
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(getString(R.string.volleyErrorMessage));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(error.getCause().getMessage());
}
error.printStackTrace();
}
},null,TAG);
}
private void postComment() {
final AppProgressDialog appProgressDialog = new AppProgressDialog(this);
appProgressDialog.setProgressDialogTitle("Posting Comment");
appProgressDialog.setProgressDialogMessage("Please Wait...");
appProgressDialog.showProgressDialog();
try {
final String comment = mEditTextComment.getText().toString();
if (!ValidatorUtility.isBlank(comment) && mPostID!=0) {
JSONObject jsonData = new JSONObject();
jsonData.put("content",comment);
jsonData.put("post",mPostID);
NetworkUtility.postRquestWithBasicAuth(this, APIURLs.POST_COMMENT, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.has("id") && response.getInt("id")>0){
AppToast.toastLong(mContext,"Comment Added");
Comment objComment = new Comment();
if (response.has("author_name"))
objComment.setmAuthor(response.getString("author_name"));
if (response.has("author_email"))
objComment.setmAuthorEmail(response.getString("author_email"));
if (response.has("author"))
objComment.setmAuthorID(response.getInt("author"));
objComment.setmContent(comment);
if (response.has("date"))
objComment.setmDate(response.getString("date"));
if (response.has("id"))
objComment.setmID(response.getInt("id"));
objComment.setmImage(mUser.getImage());
objComment.setmName(mUser.getName());
mCommentList.add(0,objComment);
mCommentAdapter.notifyDataSetChanged();
mEditTextComment.setText(null);
mEditTextComment.clearFocus();
mInputMethodManager.hideSoftInputFromWindow(mEditTextComment.getWindowToken(),0);
showContent();
} else {
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),"Failed to add comment. Please try again later.",getString(R.string.okLabel),null,null,null);
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
appProgressDialog.dismissProgressDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
appProgressDialog.dismissProgressDialog();
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),error.getCause().getMessage(),getString(R.string.okLabel),null,null,null);
}
}, jsonData, TAG);
} else {
appProgressDialog.dismissProgressDialog();
}
} catch (Exception e){
e.printStackTrace();
appProgressDialog.dismissProgressDialog();
}
}
private void initProgressBar(){
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void initErrorView(){
mLinearLayoutError = (LinearLayout) findViewById(R.id.linearLayoutError);
mTextViewErrorMessage = (TextView) findViewById(R.id.textViewErrorMessage);
mButtonRefresh = (Button) findViewById(R.id.buttonRefresh);
mButtonRefresh.setOnClickListener(this);
}
private void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.GONE);
}
private void showContent(){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.VISIBLE);
}
private void showError(String message){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.GONE);
mTextViewErrorMessage.setText(message);
}
#Override
public void onClick(View view) {
if(view == mButtonRefresh){
fetchComments();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
KeyboardUtility.closeKeyboard(this,mEditTextComment);
}
}
Exception:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate app.govindaconnect.mangaltaraproductions.com.views.CommentListingActivity$4$1.toString()
Only 1 JSON objects get converted and added to the list.
What might be causing the exception? Because this is not happening with other classes.
You can try this
replace this line
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
with this and try
Type token = new TypeToken<List<Comment>>() {}.getType();
List<Comment> commentsList = gson.fromJson(String.valueOf(resultArray), type);
I took JSON array in a string variable and then it started working.
why don't you try Jackson parser for conversion, it's much simpler and easier
example for you :
List<Comment> list=null;
String json="your json array";
ObjectMapper mapper = new ObjectMapper();
try {
list= mapper.readValue(json, new TypeReference<List<Comment>>(){});
} catch (IOException e) {
throw new Exception(e);
}
I want show image into RecyclerView and i should use this images from drawable folder. I write below codes, but show me this error :
java.lang.IllegalArgumentException: Unknown type class [I. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class
at com.bumptech.glide.RequestManager.loadGeneric(RequestManager.java:629)
at com.bumptech.glide.RequestManager.load(RequestManager.java:598)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:66)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:29)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5768)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5801)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5037)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2101)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1858)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5845)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at jav
Model codes:
public class MainDataModel implements Serializable {
private static final long serialVersionUID = 1L;
private String category;
private String categoryID;
private String categoryDescription;
private int[] categoryImages;
private TimeInterpolator interpolator;
public MainDataModel(String categoryID, String category, String categoryDescription, int[] categoryImages,
TimeInterpolator interpolator) {
this.categoryID = categoryID;
this.category = category;
this.categoryDescription = categoryDescription;
this.categoryImages = categoryImages;
this.interpolator = interpolator;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategoryID() {
return categoryID;
}
public void setCategoryID(String caategoryID) {
this.categoryID = caategoryID;
}
public String getCategoryDescription() {
return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
public TimeInterpolator getInterpolator() {
return interpolator;
}
public void setInterpolator(TimeInterpolator interpolator) {
this.interpolator = interpolator;
}
public int[] getCategoryImages() {
return categoryImages;
}
public void setCategoryImages(int[] categoryImages) {
this.categoryImages = categoryImages;
}
}
AsyncTask codes and set image :
public class ColoniesDataInfo {
private static Context mContext;
private String ServerAddress = ServerIP_colonies.getColoniesIP();
public void getColoniesDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress)
//.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("categories");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
String colID = postObject.getString("id");
String colTitle = postObject.getString("title");
String colDescription = postObject.getString("description");
final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
Log.d("Data", "Colonies ID: " + colID);
Log.d("Data", "Colonies title: " + colTitle);
Log.d("Data", "Colonies Desc: " + colDescription);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(colID, colTitle, colDescription, colImages,
Utils.createInterpolator(Utils.BOUNCE_INTERPOLATOR)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
Adapter codes and set image into adapter :
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<MainDataModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getCategory());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getCategory())
.putExtra("categoryID", model.getCategoryID()));
}
});
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages())
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
holder.colonies_description.setText(mDateSet.get(position).getCategoryDescription());
holder.expandableLayout.setInterpolator(mDateSet.get(position).getInterpolator());
holder.expandableLayout.setExpanded(expandState.get(position));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
createRotateAnimator(holder.buttonLayout, 0f, 180f).start();
expandState.put(position, true);
}
#Override
public void onPreClose() {
createRotateAnimator(holder.buttonLayout, 180f, 0f).start();
expandState.put(position, false);
}
});
holder.buttonLayout.setRotation(expandState.get(position) ? 180f : 0f);
holder.buttonLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
onClickButton(holder.expandableLayout);
}
});
}
private void onClickButton(final ExpandableLayout expandableLayout) {
expandableLayout.toggle();
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView colonies_title, colonies_description;
private ImageView colonies_image;
private ExpandableLinearLayout expandableLayout;
private RelativeLayout buttonLayout;
public ViewHolder(View itemView) {
super(itemView);
colonies_title = (TextView) itemView.findViewById(R.id.colonies_colony_title_text);
colonies_image = (ImageView) itemView.findViewById(R.id.colonies_cover_image);
colonies_description = (TextView) itemView.findViewById(R.id.colonies_expandable_description_text);
buttonLayout = (RelativeLayout) itemView.findViewById(R.id.colonies_expandable_button);
expandableLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.colonies_expandable_layout);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail()));*/
}
});
}
}
public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
animator.setDuration(300);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
}
How can i fix it?
First of all why are you loading all the array of images into a single imageView? Your method getCategoryImages() gives you an integer array of images. retrieve one by one corresponding to the position.
If the problem still persists you can refer to the below link with the same issue
https://github.com/bumptech/glide/issues/588
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages()[position])
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
You are trying to load a list of ints and that is why Glide isn't working.
As you gave one ImageView as destination, only one image can be loaded there.
What you need to do is extract the image you wish to load and then pass it to Glide.