When I execute the program, it shows a blank screen and in logcat it shows no adapter attached; skipping layout. When I debug the code the ArrayList is not getting the value (returning 0).
public class MainActivity extends AppCompatActivity implements Constants, NetworkOperation, URL {
LinearLayoutManager manager;
ArrayList<OfferModal> bestoffers;
RecyclerViewAdapter adapter;
RecyclerView rv;
FetchData fetchData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.recyclerview1);
fetchData = new FetchData(this, this, CLOUD_SECTION);
fetchData.fromServer();
manager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void started() {
}
#Override
public void doingBackground() {
}
#Override
public void completed(JSONObject jsonObject) {
bestoffers = new ArrayList<OfferModal>();
try {
JSONArray array_item = new JSONArray();
for (int i = 0; i < array_item.length(); i++) {
JSONObject itemobj = array_item.getJSONObject(i);
String id = itemobj.getString(ID);
String le_id = itemobj.getString(LE_ID);
String title = itemobj.getString(TITLE);
String description = itemobj.getString(DESCRIPTION);
String wid = itemobj.getString(WID);
String hgt = itemobj.getString(HGT);
String tn_path = itemobj.getString(TN_PATH);
String create_time = itemobj.getString(CREATE_TIME);
String update_time = itemobj.getString(UPDATE_TIME);
String view_count = itemobj.getString(VIEW_COUNT);
String slide_count = itemobj.getString(SLIDE_COUNT);
String shared = itemobj.getString(SHARED);
String publish_ver = itemobj.getString(PUBLISH_VER);
String publish_time = itemobj.getString(PUBLISH_TIME);
String user_name = itemobj.getString(USER_NAME);
String avatar_path = itemobj.getString(AVATAR_PATH);
String comment_count = itemobj.getString(COMMENT_COUNT);
String fav = itemobj.getString(FAV);
String fav_count = itemobj.getString(FAV_COUNT);
OfferModal off = new OfferModal(id, le_id, title, description, wid, hgt, tn_path, create_time, update_time, view_count, slide_count, shared, publish_ver, publish_time, user_name, avatar_path, comment_count, fav, fav_count);
off.setId(id);
off.setId(le_id);
off.setTitle(title);
off.setDescription(description);
off.setHgt(hgt);
off.setTn_path(tn_path);
off.setCreate_time(create_time);
off.setUpdate_time(update_time);
off.setView_count(view_count);
off.setSlide_count(slide_count);
off.setShared(shared);
off.setPublish_ver(publish_ver);
off.setPublish_time(publish_time);
off.setUser_name(user_name);
off.setAvatar_path(avatar_path);
off.setComment_count(comment_count);
off.setFav(fav);
off.setFav_count(fav_count);
bestoffers.add(off);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new RecyclerViewAdapter(getApplicationContext(), bestoffers);
rv.setAdapter(adapter);
}
}
This is my json data:
[
{
"id": "42057",
"le_id": "568fb0d29a5eb",
"title": "Bag the Big Deal Lulu Hypermarket",
"description": "",
"wid": "0",
"hgt": "0",
"tn_path": "",
"create_time": "1452257490",
"update_time": "1452332748",
"view_count": "00000000669",
"slide_count": "9",
"shared": "F",
"publish_ver": "11",
"publish_time": "1452332761",
"user_name": " Lulu Retail",
"avatar_path": null,
"comment_count": "0",
"fav": "F",
"fav_count": 0
},
{
"id": "42019",
"le_id": "568f9e45625da",
"title": "Bag the Big Deal Lulu Fashion Store",
"description": "",
"wid": "0",
"hgt": "0",
"tn_path": "",
"create_time": "1452252741",
"update_time": "1452584969",
"view_count": "00000000659",
"slide_count": "1",
"shared": "F",
"publish_ver": "5",
"publish_time": "1452584972",
"user_name": " Lulu Retail",
"avatar_path": null,
"comment_count": "0",
"fav": "F",
"fav_count": 0
},
{
"id": "42017",
"le_id": "568f9e30df0da",
"title": "Bag the Big Deal Lulu Connect",
"description": "",
"wid": "0",
"hgt": "0",
"tn_path": "",
"create_time": "1452252720",
"update_time": "1452585162",
"view_count": "00000000726",
"slide_count": "7",
"shared": "F",
"publish_ver": "7",
"publish_time": "1452275301",
"user_name": " Lulu Retail",
"avatar_path": null,
"comment_count": "0",
"fav": "F",
"fav_count": 0
}
]
This is my adapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
ArrayList<OfferModal> mBestoffers;
Context context;
// List<Offers>card_items;
RequestQueue mRequestQueue;
ImageLoader mImageLoader;
public RecyclerViewAdapter(Context context, ArrayList<OfferModal> mBestoffers) {
this.context = context;
// this.card_items = card_items;
this.mBestoffers = mBestoffers;
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
});
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardlayout, null);
RecyclerViewHolder rvh = new RecyclerViewHolder(view);
return rvh;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
// holder.imageView.setImageUrl(mBestoffers.get(position).getAvatar_path(), mImageLoader);
holder.tv1.setText(mBestoffers.get(position).getTitle());
//write code to download image and data from server and set here
}
#Override
public int getItemCount() {
return mBestoffers.size();
}
}
Please help me to solve this issue, any help will be greately appriciated.
Please paste jsonObject.toString() in completed().
Array empty reason is here.
JSONArray array_item = new JSONArray();
for (int i = 0; i < array_item.length(); i++) {
Please use this code it will help you.
public class MainActivity extends AppCompatActivity implements Constants, NetworkOperation, URL {
LinearLayoutManager manager;
ArrayList<OfferModal> bestoffers;
RecyclerViewAdapter adapter;
RecyclerView rv;
FetchData fetchData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.recyclerview1);
fetchData = new FetchData(this, this, CLOUD_SECTION);
fetchData.fromServer();
manager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void started() {
}
#Override
public void doingBackground() {
}
#Override
public void completed(JSONObject jsonObject) {
bestoffers = new ArrayList<OfferModal>();
try {
JSONArray array_item = new JSONArray();
for (int i = 0; i < array_item.length(); i++) {
JSONObject itemobj = array_item.getJSONObject(i);
String id = itemobj.getString(ID);
String le_id = itemobj.getString(LE_ID);
String title = itemobj.getString(TITLE);
String description = itemobj.getString(DESCRIPTION);
String wid = itemobj.getString(WID);
String hgt = itemobj.getString(HGT);
String tn_path = itemobj.getString(TN_PATH);
String create_time = itemobj.getString(CREATE_TIME);
String update_time = itemobj.getString(UPDATE_TIME);
String view_count = itemobj.getString(VIEW_COUNT);
String slide_count = itemobj.getString(SLIDE_COUNT);
String shared = itemobj.getString(SHARED);
String publish_ver = itemobj.getString(PUBLISH_VER);
String publish_time = itemobj.getString(PUBLISH_TIME);
String user_name = itemobj.getString(USER_NAME);
String avatar_path = itemobj.getString(AVATAR_PATH);
String comment_count = itemobj.getString(COMMENT_COUNT);
String fav = itemobj.getString(FAV);
String fav_count = itemobj.getString(FAV_COUNT);
OfferModal off = new OfferModal(id, le_id, title, description, wid, hgt, tn_path, create_time, update_time, view_count, slide_count, shared, publish_ver, publish_time, user_name, avatar_path, comment_count, fav, fav_count);
off.setId(id);
off.setId(le_id);
off.setTitle(title);
off.setDescription(description);
off.setHgt(hgt);
off.setTn_path(tn_path);
off.setCreate_time(create_time);
off.setUpdate_time(update_time);
off.setView_count(view_count);
off.setSlide_count(slide_count);
off.setShared(shared);
off.setPublish_ver(publish_ver);
off.setPublish_time(publish_time);
off.setUser_name(user_name);
off.setAvatar_path(avatar_path);
off.setComment_count(comment_count);
off.setFav(fav);
off.setFav_count(fav_count);
bestoffers.add(off);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new RecyclerViewAdapter(MainActivity.this,R.layout.cardlayout, bestoffers);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged()
}
}
Your main problem lies in the JSONArray, you are initialising to a new JSONArray, which is empty, please check what is the size of the array in the jsonArray.length(); I'm sure it is 0. That is why your arraylist is also empty.
Related
So I am using Volley to get data from Thinkspeak.com API which has limit results to display the data to JSON format.
Here are the results from the Thinkspeak.com API:
{
"channel": {
"id": "channel_id",
"name": "SISTEM FDRS",
"latitude": "lat",
"longitude": "long",
"field1": "Field Label 1",
"field2": "Field Label 2",
"field3": "Field Label 3",
"field4": "Field Label 4",
"field5": "Field Label 5",
"field6": "Field Label 6",
"created_at": "2019-01-20T02:01:36Z",
"updated_at": "2019-06-27T08:06:29Z",
"last_entry_id": 115
},
"feeds": [{
"created_at": "2019-07-05T10:36:02Z",
"entry_id": 106,
"field1": "31.20",
"field2": "64.30",
"field3": "0.00",
"field4": "2.95",
"field5": "86",
"field6": "2"
},
{
"created_at": "2019-07-05T10:36:50Z",
"entry_id": 107,
"field1": "31.20",
"field2": "64.67",
"field3": "0.00",
"field4": "2.41",
"field5": "86",
"field6": "2"
},
/* ... and so on .. */
]
}
I was able to increase the limit as the end of RecyclerView has been reached by using an addOnScrollListener method.
But the data displayed in RecyclerView are duplicated and I have no idea why.
Here's the Activity code:
public class FFMCActivity extends AppCompatActivity {
private List < Feed > feedList;
private RecyclerView recyclerView;
private String url = "https://api.thingspeak.com/channels/id/feeds.json?api_key=api_key&results=";
private int load_results = 1;
AdapterFFMC adapterFFMC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ffmc);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
feedList = new ArrayList < > ();
adapterFFMC = new AdapterFFMC(feedList);
recyclerView.setAdapter(adapterFFMC);
getData(load_results);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1) {
getData(load_results++);
Toast.makeText(FFMCActivity.this, "Data loaded: " + load_results, Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void getData(int results) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET, url + results,
null,
new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
JSONArray Jarray = null;
try {
Jarray = response.getJSONArray("feeds");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject feed = Jarray.getJSONObject(i);
feedList.add(new Feed(
feed.getString("created_at"),
feed.getString("entry_id"),
feed.getString("field1"),
feed.getString("field2"),
feed.getString("field3"),
feed.getString("field4"),
feed.getString("field5"),
feed.getString("field6")
));
}
Collections.sort(feedList, new Comparator < Feed > () {
#Override
public int compare(Feed feed1, Feed feed2) {
if (Integer.parseInt(feed1.getEntry_id()) > Integer.parseInt(feed2.getEntry_id())) {
return -1;
} else {
return 1;
}
}
});
adapterFFMC.notifyDataSetChanged();
} catch (JSONException e) {
Log.e("VolleyError", "JSON Parsing Error: " + e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyError", "JSON Response Error: " + error.getMessage());
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
}
And here's the Adapter code:
public class AdapterFFMC extends RecyclerView.Adapter < AdapterFFMC.ViewHolder > {
private List < Feed > dataFFMC;
public AdapterFFMC(List < Feed > dataFFMC) {
this.dataFFMC = dataFFMC;
}
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_ffmc, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Feed feed = dataFFMC.get(position);
holder.created_at.setText(feed.getCreated_at());
holder.created_day.setText(feed.getCreated_at());
holder.entry_id.setText(feed.getEntry_id());
holder.field_1.setText(feed.getField_1());
holder.field_2.setText(feed.getField_2());
holder.field_3.setText(feed.getField_3());
holder.field_4.setText(feed.getField_4());
holder.field_5.setText(feed.getField_5());
holder.field_6.setText(feed.getField_6());
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return dataFFMC.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView created_at, created_day, entry_id, field_1, field_2, field_3, field_4, field_5, field_6;
public ViewHolder(View itemView) {
super(itemView);
created_at = itemView.findViewById(R.id.created_at);
created_day = itemView.findViewById(R.id.created_day);
entry_id = itemView.findViewById(R.id.entry_id);
field_1 = itemView.findViewById(R.id.field_1);
field_2 = itemView.findViewById(R.id.field_2);
field_3 = itemView.findViewById(R.id.field_3);
field_4 = itemView.findViewById(R.id.field_4);
field_5 = itemView.findViewById(R.id.field_5);
field_6 = itemView.findViewById(R.id.field_6);
}
}
}
How do I prevent duplicate results from the code above?
Any help will be much appreciated
Thank you.
Change the sequence of your code to this.
feedList = new ArrayList < > ();
getData(load_results);
adapterFFMC = new AdapterFFMC(feedList);
recyclerView.setAdapter(adapterFFMC);
You are initializing array after setting it's adapter.
I am using ListView,inside listView i have used linearLayout to populate the Courses Data through JSON.I want to Display the Total sum of the Courses MarksObtained through the JSON data.I am not Able to add the Data from the JSON and to Display in the Specific Field.
StudentProgressReportAdapter
public class StudentProgressReportAdapter extends BaseAdapter {
LinearLayout coursesViewDynamic;
Context mContext;
ArrayList<StudentProgressReportPojo> student_list_courses;
String TAG = "HomeTab_adapter";
public StudentProgressReportAdapter(Context mContext, ArrayList<StudentProgressReportPojo> student_list_courses) {
super();
this.mContext = mContext;
this.student_list_courses = student_list_courses;
}
#Override
public int getCount() {
System.out.println(student_list_courses.size());
return student_list_courses.size();
}
#Override
public Object getItem(int arg0) {
return student_list_courses.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(final int postion, View convertView, ViewGroup parent) {
final StudentProgressReportAdapter.Holder viewHolder;
if (convertView == null) {
// inflate the layout
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_progress_report, parent, false);
// well set up the ViewHolder
viewHolder = new StudentProgressReportAdapter.Holder();
viewHolder.student_progress_report_termdenoter = (TextView) convertView.findViewById(R.id.progress_term_denoter);
viewHolder.student_progress_report_subjectTotal = (TextView) convertView.findViewById(R.id.student_progressreport_subject_total);
//added code
viewHolder.coursesLayout = (LinearLayout) convertView.findViewById(R.id.courses_layout);
} else {
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
viewHolder = (StudentProgressReportAdapter.Holder) convertView.getTag();
}
// Log.d(TAG, "## postion:" + postion + " getFeeDescription" + student_list.get(postion).getFeeDescription());
// Log.d(TAG, "## postion:" + postion + " getAmount" + student_list.get(postion).getAmount());
viewHolder.student_progress_report_termdenoter.setText(student_list_courses.get(postion).getTermDenoter());
viewHolder.student_progress_report_subjectTotal.setText(Integer.toString(student_list_courses.get(postion).getSubjectTotal()));
// viewHolder.receiptLinearLayout.removeAllViews();
//added code
// Fee fee=new Fee();
// JSONArray x=fee.jArray1;
viewHolder.coursesLayout.removeAllViews();
for (int i = 0; i < student_list_courses.get(postion).getCourses().size(); i++) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// reciptViewDynamic = (LinearLayout) inflater.inflate(R.layout.layout_bil_info, null);
coursesViewDynamic = (LinearLayout) inflater.inflate(R.layout.student_progress_report_courses_listitem, parent, false);
// TextView textView = (TextView) coursesViewDynamic.findViewById(R.id.student_progressreport_subject_coursename);
// textView.setText(student_list_courses.get(postion).getCourses().get(i));
viewHolder.student_progress_report_courses = (TextView) coursesViewDynamic.findViewById(R.id.student_progressreport_subject_coursename);
viewHolder.student_progress_report_courses.setText(student_list_courses.get(postion).getCourses().get(i));
viewHolder.student_progress_report_subjectwise_obtainedmarks = (TextView) coursesViewDynamic.findViewById(R.id.student_progressreport_subject_course_obtainedTerminalmarks);
viewHolder.student_progress_report_subjectwise_obtainedmarks.setText(student_list_courses.get(postion).getStudentProgressReportMarksObtained().get(i));
viewHolder.student_progress_report_subjectwise_fullmarks = (TextView) coursesViewDynamic.findViewById(R.id.student_progressreport_subject_terminal_fullmarks);
viewHolder.student_progress_report_subjectwise_fullmarks.setText(student_list_courses.get(postion).getStudentProgressReportTerminalFullMarks().get(i));
// Log.d(TAG, "## wrong information:" + student_list.get(postion).getFeeDescription());
viewHolder.coursesLayout.addView(coursesViewDynamic);
}
// (reciptViewDynamic).removeView(convertView);
convertView.setTag(viewHolder);
return convertView;
}
class Holder {
TextView student_progress_report_courses;
TextView student_progress_report_termdenoter;
TextView student_progress_report_subjectwise_obtainedmarks;
TextView student_progress_report_subjectwise_fullmarks;
TextView student_progress_report_subjectTotal;
LinearLayout coursesLayout;
}
}
StudentProgressReportPojo
public class StudentProgressReportPojo {
String TermDenoter;
String SubjectObtainedMarks;
String TerminalFullMarks;
Integer SubjectTotal;
public StudentProgressReportPojo(String termDenoter, String subjectObtainedMarks, String terminalfullmarks, int total) {
TermDenoter = termDenoter;
SubjectObtainedMarks = subjectObtainedMarks;
TerminalFullMarks = terminalfullmarks;
SubjectTotal = total;
}
public StudentProgressReportPojo(Integer subjectTotal) {
SubjectTotal = subjectTotal;
}
public String getTermDenoter() {
return TermDenoter;
}
public Integer getSubjectTotal() {
return SubjectTotal;
//SubjectTotal = total;
}
public void setSubjectTotal(Integer subjectTotal) {
SubjectTotal = subjectTotal;
}
public ArrayList<String> Courses = new ArrayList<String>();
public ArrayList<String> getCourses() {
return Courses;
}
public void setTermDenoter(String termDenoter) {
TermDenoter = termDenoter;
}
public void addCourses(String courses) {
Courses.add(courses);
}
//added
public ArrayList<String> StudentProgressReportMarksObtained = new ArrayList<String>();
public ArrayList<String> getStudentProgressReportMarksObtained() {
return StudentProgressReportMarksObtained;
}
public void setStudentProgressReportMarksObtained(ArrayList<String> studentProgressReportMarksObtained) {
StudentProgressReportMarksObtained = studentProgressReportMarksObtained;
}
public String getSubjectObtainedMarks() {
return SubjectObtainedMarks;
}
public void addObtainedMarksSubjectWise(String studentProgressReportMarksObtained) {
StudentProgressReportMarksObtained.add(studentProgressReportMarksObtained);
}
//added
public ArrayList<String> StudentProgressReportTerminalFullMarks = new ArrayList<String>();
public ArrayList<String> getStudentProgressReportTerminalFullMarks() {
return StudentProgressReportTerminalFullMarks;
}
public void addTerminalFullMarksSubjectWise(String studentProgressReportTerminalFullMarks) {
StudentProgressReportTerminalFullMarks.add(studentProgressReportTerminalFullMarks);
}
public String getTerminalFullMarks() {
return TerminalFullMarks;
}
}
getUserProgressData method
public void getUserProgressData() {
String URL = Navigation_URL + "?StdID=" + master_id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
ArrayList<StudentProgressReportPojo> student_list_courses = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
int x = 0;
// studentFeeInformation = new StudentFeeInformation(response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
System.out.println(i);
String course = jsonObject.getString("CourseName");
String examDescription = jsonObject.getString("examDescription");
String ObtainedMaks = jsonObject.getString("Marks");
// System.out.println("the Obtained Marks is =" + ObtainedMaks);
x = (x + Integer.parseInt(ObtainedMaks));
String TerminalFullmarks = jsonObject.getString("Terminal_FM");
if (arrayList.contains(examDescription)) {
student_list_courses.get(arrayList.indexOf(examDescription)).addCourses(course);
student_list_courses.get(arrayList.indexOf(examDescription)).addObtainedMarksSubjectWise(ObtainedMaks);
student_list_courses.get(arrayList.indexOf(examDescription)).addTerminalFullMarksSubjectWise(TerminalFullmarks);
//student_list_courses.get(arrayList.indexOf(examDescription)).getSubjectTotal();
} else {
StudentProgressReportPojo progressReportPojo = new StudentProgressReportPojo(examDescription, ObtainedMaks, TerminalFullmarks, x);
progressReportPojo.addCourses(course);
progressReportPojo.addObtainedMarksSubjectWise(ObtainedMaks);
progressReportPojo.addTerminalFullMarksSubjectWise(TerminalFullmarks);
arrayList.add(examDescription);
student_list_courses.add(progressReportPojo);
System.out.println("the Total number of x=" + x);
}
// System.out.println("the Sum=" + ObtainedMaks);
// I am going to add the information Within this Section.
// StudentProgressReportPojo StudentProgressReportPojo = new StudentProgressReportPojo(x);
//StudentProgressReportPojo.getSubjectTotal(x);
// StudentProgressReportPojo.setSubjectTotal(x);
}
System.out.println("Total Marks Obtainedis equal to" + x);
//StudentProgressReportPojo progressReportPojo1 = new StudentProgressReportPojo(x);
// progressReportPojo1.getSubjectTotal();
System.out.println("student_list size:" + student_list_courses.size());
StudentProgressReportAdapter studentProgressReportAdapter = new StudentProgressReportAdapter(getActivity(), student_list_courses);
listView.setAdapter(studentProgressReportAdapter);
} catch (JSONException e) {
System.out.println("This is not good");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(view.Fee.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
Json
[
{
"CLASSNO": "1",
"CLASS_ID": 2021,
"CourseID": 5034,
"Marks": 9,
"Sno": 1082,
"StdID": 95,
"TermID": 6014,
"CourseName": "Math",
"Terminal_FM": 100,
"Terminal_PM": 40,
"UT_FM": 50,
"UT_PM": 20,
"examDescription": "First Term",
"type": "Terminal",
"transferRate": 18,
"NAME": "Calvin Patterson"
},
{
"CLASSNO": "1",
"CLASS_ID": 2021,
"CourseID": 5035,
"Marks": 10.8,
"Sno": 1083,
"StdID": 95,
"TermID": 6014,
"CourseName": "English",
"Terminal_FM": 100,
"Terminal_PM": 40,
"UT_FM": 50,
"UT_PM": 20,
"examDescription": "First Term",
"type": "Terminal",
"transferRate": 18,
"NAME": "Calvin Patterson"
}
]
I suppose, i am able to add the subject marks but When i Display the
Sum on the TextView.The First Item ObtainedMarks is Displayed Rather
than that of the Total Sum.How can this issue be Solved?
Maybe add getter to adapter:
public int getSumOfSubjectObtainedMarks(){
int sum;
foreach(StudentProgressReportPojo course: student_list_courses){
sum += Integer.parseInt(course.getSubjectObtainedMarks());
}
return sum;
}
And then use studentProgressReportAdapter.getSumOfSubjectObtainedMarks() to display proper data.
One more thing: fields should be lowercase, so subjectObtainedMarks not SubjectObtainedMarks etc.
I am still not confident working with android and I have 2 problems here, I would like to make Multi level recyclerView with 3 levels. 1st level is categories RecyclerView, 2nd is ListView with list of exercises and 3rd level is details. So now I made a 1st level recyclerView which is not clickable. Another problem is how to fetch Listview in 2nd level to the details of the 3rd level? Here is my code of 1st level fragment:
public class BallTrainingFragment extends Fragment {
View mRootView;
String URL_TO_HIT = "https://gist.githubusercontent.com/tomasmaks/afbf3e836dabd72c95c4b3ec90e291ed/raw/7ba41948865f78f1ccb4058c61f8c6e06c601300/BasketballTraining.json";
BallTrainingAdapter adapter;
RecyclerView mRecyclerView;
private List<BallTrainingModel> ballTraining;
GridLayoutManager mGridLayoutManager;
public BallTrainingFragment() {
// Required empty public constructor
}
public static BallTrainingFragment newInstance(int sectionNumber) {
BallTrainingFragment fragment = new BallTrainingFragment();
Bundle args = new Bundle();
args.putInt(Constants.ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mRootView = inflater.inflate(R.layout.fragment_balltraining, container, false);
mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.balltraining_list);
mRecyclerView.setHasFixedSize(true);
// Display under one column
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
// Set orientation
mGridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mGridLayoutManager);
return mRootView;
}
#Override
public void onStart() {
super.onStart();
new FetchBallTask().execute(URL_TO_HIT);
}
public class FetchBallTask extends AsyncTask<String, String, List<BallTrainingModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<BallTrainingModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.optJSONArray("BasketballTraining");
List<BallTrainingModel> ballTrainingModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
BallTrainingModel ballTrainingModel = gson.fromJson(finalObject.toString(), BallTrainingModel.class);
ballTrainingModel.setCategory(finalObject.getString("category"));
ballTrainingModel.setThumbnail(finalObject.getString("thumb"));
List<BallTrainingModel.Cast> castList = new ArrayList<>();
for(int j=0; j<finalObject.getJSONArray("cast").length(); j++){
BallTrainingModel.Cast cast = new BallTrainingModel.Cast();
cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
ballTrainingModel.setCastList(castList);
// adding the final object in the list
ballTrainingModelList.add(ballTrainingModel);
}
return ballTrainingModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final List<BallTrainingModel> result) {
super.onPostExecute(result);
if(result != null) {
adapter = new BallTrainingAdapter(getActivity().getApplicationContext(), R.layout.fragment_balltraining_content, result);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View v) {
int position = mRecyclerView.indexOfChild(v);
BallTrainingModel ballTrainingModel = result.get(position);
Intent intent = new Intent(getActivity(), BallTrainingDetailsActivity.class);
intent.putExtra("ballTrainingModel", new Gson().toJson(ballTrainingModel));
getActivity().startActivity(intent);
}
});
} else {
Toast.makeText(getActivity().getApplicationContext(), "Not able to fetch data from server, please check url.", Toast.LENGTH_SHORT).show();
}
}
}
public class BallTrainingAdapter extends RecyclerView.Adapter<CustomViewHolder> {
private List<BallTrainingModel> ballTrainingList;
private int resource;
private LayoutInflater inflater;
public BallTrainingAdapter(Context context,int resource, List<BallTrainingModel> objects) {
ballTrainingList = objects;
this.resource = resource;
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_balltraining_content, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int position) {
BallTrainingModel ballTraining = ballTrainingList.get(position);
ImageLoader.getInstance().displayImage(ballTrainingList.get(position).getThumbnail(), customViewHolder.thumbnail);
//Setting text view title
customViewHolder.textView.setText(ballTrainingList.get(position).getCategory());
}
#Override
public int getItemCount() {
return (null != ballTrainingList ? ballTrainingList.size() : 0);
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder{
protected TextView textView;
protected ImageView thumbnail;
public CustomViewHolder(View view) {
super(view);
this.textView = (TextView) view.findViewById(R.id.category);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
}
}
}
I think that not clickable problem is on this line of code:
mRecyclerView.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View v) {
And here is 2nd level fragment, which should render ListView and be clickable to 3rd level of details. Can someone give any example of how to make this?
public class BallTrainingDetailsActivity extends ActionBarActivity {
private TextView name;
private TextView tvCast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_balltraining_list);
// Showing and Enabling clicks on the Home/Up button
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
// setting up text views and stuff
setUpUIViews();
// recovering data from MainActivity, sent via intent
Bundle bundle = getIntent().getExtras();
if(bundle != null){
String json = bundle.getString("ballTrainingModel");
BallTrainingModel ballTrainingModel = new Gson().fromJson(json, BallTrainingModel.class);
StringBuffer stringBuffer = new StringBuffer();
for(BallTrainingModel.Cast cast : ballTrainingModel.getCastList()){
stringBuffer.append(cast.getName() + ", ");
}
tvCast.setText(stringBuffer);
//tvStory.setText(movieModel.getStory());
}
}
private void setUpUIViews() {
name = (TextView)findViewById(R.id.Name);
}
}
Here is JSON file:
{
"BasketballTraining": [
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Ball Handling",
"cast": [
{
"name": "Robert Downey Jr."
},
{
"name": "Chris Evans"
},
{
"name": "Mark Ruffalo"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Shooting",
"cast": [
{
"name": "Matthew McConaughey"
},
{
"name": "Anne Hathaway"
},
{
"name": "Jessica Chastain"
},
{
"name": "Wes Bentley"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Post Moves",
"cast": [
{
"name": "Miles Teller"
},
{
"name": "Kate Mara"
},
{
"name": "Michael B. Jordan"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Defense",
"cast": [
{
"name": "Christian Bale"
},
{
"name": "Heath Ledger"
},
{
"name": "Aaron Eckhart"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Scoring",
"cast": [
{
"name": "Viggo Mortensen"
},
{
"name": "Ian McKellen"
},
{
"name": "Elijah Wood"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Others",
"cast": [
{
"name": "Roberto Benigni"
},
{
"name": "Nicoletta Braschi"
},
{
"name": "Giorgio Cantarini"
}
]
}
]
}
and here is my model:
public class BallTrainingModel {
private String thumbnail;
private String category;
#SerializedName("cast")
private List<Cast> castList;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public List<Cast> getCastList() {
return castList;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public void setCastList(List<Cast> castList) {
this.castList = castList;
}
public static class Cast {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Any examples or help would appreciated. Thank you in advance.
In RecyclerView Adapter there is a method onBindView
you have to apply there setOnClickListener :
For example :
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your Code
});
}
}
For ref : check this link
I m creating dynamic tabs in android in which the data for the tabs is populated from the json
Following is the json response
{
"shop_details": [
{
"id": "36",
"shop_name": "All in One Mart",
"shop_no": "23223",
"shop_address": "Tinkune",
"phone": "9804966595",
"email": "arjundangal4#gmail.com",
"user_name": "arjun",
"address": "",
"tel": "",
"fax": "",
"facebook": "",
"twitter": "",
"googleplus": "",
"image": "",
"featured_image": ""
}
],
"category": [
{
"category_id": "35",
"category_name": "Skirt",
"product": [
{
"product_id": "49",
"product_name": "Skirt",
"category_id": "35",
"subcategory_id": "37",
"product_color": "blue",
"description": "Skirt for girls",
"price": "301",
"discount": "0",
"service_charge": "0",
"user_id": "36",
"image_name": "6baab8a5308b7e821f5b6387794979a4.jpeg",
"created_at": "2016-07-04 03:54:54"
}
]
},
{
"category_id": "36",
"category_name": "Men",
"product": [
{
"product_id": "48",
"product_name": "Glasses",
"category_id": "36",
"subcategory_id": "39",
"product_color": "red",
"description": "Glasses of Rayban",
"price": "594",
"discount": "23",
"service_charge": "22",
"user_id": "36",
"image_name": "fce01420a9021fdb159226b4bdc5b591.jpg",
"created_at": "2016-07-04 03:52:58"
}
]
},
{
"category_id": "37",
"category_name": "Bags",
"product": [
{
"product_id": "50",
"product_name": "Laptop bag",
"category_id": "37",
"subcategory_id": "41",
"product_color": "black",
"description": "Bag to carry laptop",
"price": "190",
"discount": "2",
"service_charge": "3",
"user_id": "36",
"image_name": "e836e090a54cd2b6b594fa0a3382bb38.jpg",
"created_at": "2016-07-04 04:14:08"
}
]
}
]
}
Following is the code to fetch in which i add the tabs dynamically
private void getShopDetails() {
coordinatorLayout.setVisibility(View.GONE);
new ProgressDialog(this);
ProgressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ProgressDialog.dismiss();
coordinatorLayout.setVisibility(View.VISIBLE);
try {
JSONArray shopDetailsArray = response.getJSONArray("shop_details");
JSONObject shopDetailsObj = shopDetailsArray.getJSONObject(0);
shopName = shopDetailsObj.getString("shop_name");
phone = shopDetailsObj.getString("tel");
shopNum = shopDetailsObj.getString("shop_no");
shopAddress = shopDetailsObj.getString("shop_address");
shopImage = shopDetailsObj.getString("featured_image");
Glide.with(getApplicationContext()).load("http://allmartapp.com/appapi/uploads/" + shopImage).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(backdrop);
colLayout.setTitle(shopName);
address.setText("Address - Shop no -" + shopNum + ", " + shopAddress);
JSONArray tabsArray = response.getJSONArray("category");
categoryId = new int[tabsArray.length()];
for (int i = 0; i < tabsArray.length(); i++) {
JSONObject tabsObj = tabsArray.getJSONObject(i);
tabLayout.addTab(tabLayout.newTab().setText(tabsObj.getString("category_name")));
categoryId[i] = tabsObj.getInt("category_id");
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
ShopDetailsTabsFragment.sgetid(categoryId[tab.getPosition()]);
Log.d("CATIID", categoryId[tab.getPosition()] + "");
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ProgressDialog.dismissWithError();
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
In ontabselected() i assigned the category id according to the position of the tabs and call the sgetid() function which is in the fragment
My pageradapter returns only one Fragment with the recyclerview.
Following is the Fragment code
public class ShopDetailsTabsFragment extends Fragment {
RecyclerView recyclerView;
boolean isViewShown = false;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
public ShopDetailsTabsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
return v;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
getShopCat();
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
} else {
isViewShown = false;
}
}
public static void sgetid(int cat) {
catid = cat;
}
private void getShopCat() {
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
for (int i = 0; i < categoryArray.length(); i++) {
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("product_id");
CategoryItemsListModel shopListRvModels = new CategoryItemsListModel(id, image, name, price);
arrayList.add(shopListRvModels);
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
shopListRvAdapters.notifyDataSetChanged();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}
}
My problem is that, the tabs are showing strange behaviors. I know that the logic to fetch the category lists is correct. But I think there is problem in the state of the fragment. When i switch the tabs, the data loaded in the tabs are sometimes duplicated and even the data are loaded twice sometimes. Any suggestions are appreciated as im facing the problem for couple of days. I want to know the easy way to load the data in the tabs.
Try below code if it helps:
public class ShopDetailsTabsFragment extends Fragment {
RecyclerView recyclerView;
boolean isViewShown = false;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
public ShopDetailsTabsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
return v;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
getShopCat();
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
} else {
isViewShown = false;
}
}
public static void sgetid(int cat) {
catid = cat;
}
private void getShopCat() {
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
if(arrayList!=null){
if(arrayList.size()>0)
arrayList.clear();
}
for (int i = 0; i < categoryArray.length(); i++) {
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("product_id");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
}
shopListRvAdapters.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}
I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3 and RecyclerView!
I want show title from categories in textview, but i don't know how to show this?!
My Json :
{
"status": "ok",
"count": 10,
"count_total": 28,
"pages": 3,
"posts": [{
"id": 145,
"type": "post",
"slug": "english-post-2",
"url": "http:\/\/tellfa.com\/tafrihgah\/?p=145",
"status": "publish",
"title": "English Post",
"title_plain": "English Post",
"content": "<p>This post is test for show Text and Image<\/p>\n<p><img class=\"alignnone size-medium wp-image-79\" src=\"http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-300x240.jpg\" alt=\"[WallpapersMania]_vol49-027\" width=\"300\" height=\"240\" srcset=\"http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-300x240.jpg 300w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-768x614.jpg 768w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-1024x819.jpg 1024w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027.jpg 1280w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>This is image in Text<\/p>\n",
"excerpt": "<p>This post is test for show Text and Image<\/p>\n<p>This is image in Text<\/p>\n",
"date": "2016-05-01 08:20:39",
"modified": "2016-05-01 08:20:39",
"categories": [{
"id": 1,
"slug": "%d8%af%d8%b3%d8%aa%d9%87%e2%80%8c%d8%a8%d9%86%d8%af%db%8c-%d9%86%d8%b4%d8%af%d9%87",
"title": "\u062f\u0633\u062a\u0647\u200c\u0628\u0646\u062f\u06cc \u0646\u0634\u062f\u0647",
"description": "",
"parent": 0,
"post_count": 24
}],
"tags": [],
"author": {
"id": 1,
"slug": "tellfa",
"name": "\u0645\u062d\u0645\u062f",
"first_name": "",
"last_name": "",
"nickname": "\u0645\u062d\u0645\u062f",
"url": "http:\/\/codesaz.com",
"description": "\u0627\u06cc\u0646 \u0632\u0646\u062f\u06af\u06cc \u0646\u0627\u0645\u0647 \u0645\u0646 \u0627\u0633\u062a",
"avatar": "76"
},
"comments": [],
"attachments": [{
"id": 146,
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
"slug": "wallpapersmania_vol33-031",
"title": "WallpapersMania_vol33-031",
"description": "",
"caption": "",
"parent": 145,
"mime_type": "image\/jpeg",
"images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
"width": 1600,
"height": 1200
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x225.jpg",
"width": 300,
"height": 225
},
"mediaphase-frontpage-news": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x220.jpg",
"width": 300,
"height": 220
},
"mediaphase-blog-large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-700x313.jpg",
"width": 700,
"height": 313
}
}
}],
"comment_count": 0,
"comment_status": "open",
"thumbnail": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
"custom_fields": {},
"thumbnail_size": "thumbnail",
"thumbnail_images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
"width": 1600,
"height": 1200
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x225.jpg",
"width": 300,
"height": 225
},
"mediaphase-frontpage-news": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x220.jpg",
"width": 300,
"height": 220
},
"mediaphase-blog-large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-700x313.jpg",
"width": 700,
"height": 313
}
}
}
I read this title from this Array :
"categories": [{
"id": 1,
"slug": "%d8%af%d8%b3%d8%aa%d9%87%e2%80%8c%d8%a8%d9%86%d8%af%db%8c-%d9%86%d8%b4%d8%af%d9%87",
"title": "\u062f\u0633\u062a\u0647\u200c\u0628\u0646\u062f\u06cc \u0646\u0634\u062f\u0647",
"description": "",
"parent": 0,
"post_count": 24
}],
My AsyncTask codes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
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 + "page=1")
.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("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
// Thumbnail
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
// Author
JSONObject Author = postObject.optJSONObject("author");
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String dateTime = postObject.getString("date");
String thumbnail = imagesPair.getString("url");
String authorShow = Author.getString("name");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + thumbnail);
Log.d("Data", "Post category: " + authorShow);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, thumbnail));
}
} 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);
}
}
}
}
MainActivity code:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image, toolbar_refresh;
private RecyclerView main_recyclerView;
private MainAdapter_loadMore mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
private int pageCount = 1;
String ServerAddress = ServerIP.getIP();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
// Initializing
handler = new Handler();
context = getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
mLayoutManager = new LinearLayoutManager(this);
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
toolbar_refresh = (ImageView) toolbar.findViewById(R.id.toolbar_update);
// Toolbar
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
// Load First Data
LoadData();
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
// Load More data
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
LoadMoreData(pageCount);
}
});
// Refresh Data
toolbar_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), PostShow_page.class));
}
});
}
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
mAdaper.setLoaded();
}
mAdaper.add(mainInfoModels);
mAdaper.notifyDataSetChanged();
pageCount++;
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
private void LoadData() {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this);
}
private void LoadMoreData(int pageNumber) {
MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
// here getMainDataInfo() should return the server response
dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
}
}
Attention : Please don't give me negative points, i am amateur and i really need you helps! thanks all <3
add RecyclerView in layout
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
add dependencies
compile 'com.android.support:recyclerview-v7:23.1.1'
create a layout for each row of RecyclerView and name it list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
create a JAVA file Model.java
public class Model {
public String title;
}
now create java file named as Adapter.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
private ArrayList<Model> modelArrayList=new ArrayList<>();
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public Adapter(ArrayList<Model> modelArrayList) {
this.modelArrayList = modelArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Movie movie = moviesList.get(position);
holder.title.setText(modelArrayList.get(position).title);
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
}
in MainActivity.java
create a Arrylist of type Model
ArrayList<Model> modelArrayList=new ArrayList<>();
RecyclerView recyclerView;
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
prase data
JSONObject jsonObject = new JSONObject(ou_response);
JSONArray message = jsonObject.getJSONArray("categories");
for (int i = 0; i < message.length(); i++) {
Model model = new Model();
JSONObject temp = message.getJSONObject(i);
model.tittle = temp.getString("tittle");
modelArrayList.add(model);
}
create Adapter and set it to recyclerView
Adapter madapter = new Adapter(modelArrayList);
recyclerView.setAdapter(mAdapter);
creating RecyclerView in your xml file:
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Declare the RecyclerView and JsonArray in your Activity class :
VolleyClass volleyClass;
JSONArray jsonArray = new JSONArray();
RecyclerAdapter recyclerAdapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_head_two_head);
volleyClass = VolleyClass.getInstance(this);
//volleyClass=new VolleyClass(this);
recyclerAdapter = new RecyclerAdapter();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(HeadToHeadRandom.this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recyclerAdapter);
Retrieve Json data :
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL.HEADTOHEAD_LIST.getURL(), urlObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("onResponse", response.toString());
try {
jsonArray = response.getJSONArray("Categories");
if (jsonArray != null) {
recyclerAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
mDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
mDialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", System.getProperty("http.agent"));
return headers;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
volleyClass.addToRequestQueue(jsObjRequest);
Adapter Class like this:
class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.HaderView> {
#Override
public HaderView onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_head_to_head, parent, false);
lastItem = recyclerView.getChildAdapterPosition(view);
return new HaderView(view);
}
#Override
public void onBindViewHolder(HaderView holder, int position) {
try {
holder.tv_category.setText(jsonArray.getJSONObject(position).getString("title"));
String image_path = jsonArray.getJSONObject(position).getString("icon");
if (image_path != null) {
imageLoader.displayImage(image_path, holder.img_head_to_head, options);
}
} catch (JSONException e) {
e.printStackTrace();
}
final int posi = position;
holder.tv_category.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String category_id = jsonArray.getJSONObject(posi).getString("id");
startActivity(new Intent(HeadToHead.this, HTHActivity.class).putExtra("category_id", category_id).putExtra("friend_userId", friend_Id));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public int getItemCount() {
return jsonArray.length();
}
class HaderView extends RecyclerView.ViewHolder {
TextView tv_category;
ImageView img_head_to_head;
HaderView(View v) {
super(v);
tv_category = (TextView) v.findViewById(R.id.tv_category);
img_head_to_head = (ImageView) v.findViewById(R.id.img_head_to_head);
}
}
}