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.
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.
There is a ListView within which I have used a Dynamic Linear Layout to add inner elements. I want to display all the Specific Term wise inner data within a specific list (i.e. Only Specific Term Name to be displayed and all the information within the TermName). However, I am getting the inner item as Another List Item, i.e is not what I am expecting.
JSON
[
{
"CLASSNO": "1",
"CLASS_ID": 2021,
"CourseID": 4032,
"Marks": 45,
"Sno": 35,
"StdID": 95,
"TermID": 6014,
"CourseName": "History",
"Terminal_FM": 50,
"Terminal_PM": 20,
"UT_FM": 100,
"UT_PM": 40,
"examDescription": "First Term",
"type": "Terminal",
"NAME": "Calvin Patterson"
},
{
"CLASSNO": "1",
"CLASS_ID": 2021,
"CourseID": 4033,
"Marks": 35,
"Sno": 36,
"StdID": 95,
"TermID": 6014,
"CourseName": "Science",
"Terminal_FM": 50,
"Terminal_PM": 20,
"UT_FM": 100,
"UT_PM": 40,
"examDescription": "First Term",
"type": "Terminal",
"NAME": "Calvin Patterson"
},
{
"CLASSNO": "1",
"CLASS_ID": 2021,
"CourseID": 4032,
"Marks": 45,
"Sno": 37,
"StdID": 95,
"TermID": 6015,
"CourseName": "History",
"Terminal_FM": 50,
"Terminal_PM": 20,
"UT_FM": 100,
"UT_PM": 40,
"examDescription": "Second Term",
"type": "Terminal",
"NAME": "Calvin Patterson"
},
{
"CLASSNO": "1",
"CLASS_ID": 2021,
"CourseID": 4033,
"Marks": 30,
"Sno": 38,
"StdID": 95,
"TermID": 6015,
"CourseName": "Science",
"Terminal_FM": 50,
"Terminal_PM": 20,
"UT_FM": 100,
"UT_PM": 40,
"examDescription": "Second Term",
"type": "Terminal",
"NAME": "Calvin Patterson"
}
]
StudentProgressReportPojo
public class StudentProgressReportPojo {
String TermDenoter;
public StudentProgressReportPojo(String termDenoter) {
TermDenoter = termDenoter;
}
public ArrayList<String> Courses = new ArrayList<String>();
public ArrayList<String> getCourses() {
return Courses;
}
public void setCourses(ArrayList<String> courses) {
Courses = courses;
}
public String getTermDenoter() {
return TermDenoter;
}
public void setTermDenoter(String termDenoter) {
TermDenoter = termDenoter;
}
public void addCourses(String courses) {
Courses.add(courses);
}
}
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);
//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.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(Integer.parseInt(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));
// 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;
LinearLayout coursesLayout;
}
}
ProgressFragment
public class ProgressFragment extends Fragment {
ListView listView;
String master_id;
String Navigation_URL = "http://192.168.100.5:84/api/academics/getSingleStudentsMarks";
ArrayList arrayList = new ArrayList();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.student_progressreport_listview, container, false);
setHasOptionsMenu(true);
SessionManagement sessionManagement = new SessionManagement(getContext());
master_id = sessionManagement.getMasterId();
listView = (ListView) view.findViewById(R.id.list_student_progress_report);
getUserProgressData();
return view;
}
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);
// 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");
// progressReportPojo.setCourses(course);
// progressReportPojo.getCourses();
StudentProgressReportPojo progressReportPojo = new StudentProgressReportPojo(examDescription);
arrayList.add(examDescription);
// arrayList.add(course);
System.out.println("course" + arrayList);
progressReportPojo.addCourses(course);
// progressReportPojo.getCourses(course);
student_list_courses.add(progressReportPojo);
}
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);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I want Specific Term under which the all Courses to be Displayed.
Can't I Display all the Courses under the same Specific Term Name?
Change your for loop to add similar items to same object
,
change it to
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");
if(arrayList.contains(examDescription))) {
student_list_courses.get(arrayList
.indexOf(examDescription)).addCourses(course);
}
else{
StudentProgressReportPojo progressReportPojo = new StudentProgressReportPojo(examDescription);
progressReportPojo.addCourses(course);
arrayList.add(examDescription);
student_list_courses.add(progressReportPojo);
}
}
also you need to change
viewHolder.student_progress_report_courses
.setText(student_list_courses.get(postion).getCourses().get(i));
in your getView() function to display all Courses not just getCourses().get(i))
you need to add textviews for each item getCourses returns.
something like this
for(int x=0;x<student_list_courses.get(postion).getCourses().size();x++){
LinearLayout 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.coursesLayout.addView(coursesViewDynamic);
}
Hope this helps.
You can use GSON/ Jackson to parse your JSON objects. You will find plenty of annotations to exclude EMPTY, NULL etc. etc. in these libraries. Also they provide a much easier code to read
An example for using GSON is given here
https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
I am making Expandable RecyclerView. The problem is I have Data in ArrayList but Adapter is not getting set.
I have tried by setting adapter after arrayListNotiTypes.add(new NotiTypes("About SMS", addNotiToParticularNotiType(jaSms, ""))); this line, but same error occurs. I have made this type of Expandable RecyclerView for different module. There it is working fine.
Below is what I have tried..
Notification_Activity.java
public class Notification_Activity extends AppCompatActivity {
// Widgets
private ProgressDialog progressDialog;
private RecyclerView recyclerView_Noti;
// Variables
private String url = "notification.php";
private ArrayList<NotiTypes> arrayListNotiTypes;
private ArrayList<ActualNotis> arrayListActualNotis;
// Others
private AdapterNotification adapterNoti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
find_view_by_id();
init();
if (Commom_Methods.isNetworkAvailable(this)) {
fetchData();
} else {
Toast.makeText(this, "Please, Coonect to internet!!", Toast.LENGTH_SHORT).show();
}
// Setting Adapter for Notification
adapterNoti = new AdapterNotification(Notification_Activity.this, arrayListNotiTypes);
recyclerView_Noti.setAdapter(adapterNoti);
recyclerView_Noti.setLayoutManager(new LinearLayoutManager(Notification_Activity.this));
}
private void find_view_by_id() {
recyclerView_Noti = (RecyclerView) findViewById(R.id.recycle_noti);
}
private void init() {
arrayListNotiTypes = new ArrayList<>();
}
private void fetchData() {
StringRequest stringReq = new StringRequest(Request.Method.POST, Constants.base_url + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse: ", response);
progressDialog.dismiss();
if (response != null) {
try {
JSONObject jo = new JSONObject(response);
if (jo.has("success")) {
JSONObject joNoti = jo.getJSONObject("notification");
/*JSONArray jaStu = joNoti.getJSONArray("noti_student");
arrayListNotiTypes.add(new NotiTypes("About Student", addNotiToParticularNotiType(jaStu, "")));*/
JSONArray jaBatch = joNoti.getJSONArray("noti_batch");
arrayListNotiTypes.add(new NotiTypes("About Batch", addNotiToParticularNotiType(jaBatch, "")));
JSONArray jaInst = joNoti.getJSONArray("noti_institute");
arrayListNotiTypes.add(new NotiTypes("About Institute", addNotiToParticularNotiType(jaInst, "attach")));
JSONArray jaFee = joNoti.getJSONArray("noti_fee");
arrayListNotiTypes.add(new NotiTypes("About Fees", addNotiToParticularNotiType(jaFee, "attach")));
JSONArray jaSms = joNoti.getJSONArray("noti_sms");
arrayListNotiTypes.add(new NotiTypes("About SMS", addNotiToParticularNotiType(jaSms, "")));
} else {
Toast.makeText(getApplicationContext(), jo.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Server error! Don't get Data from server. Try again later.", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Preferences.readString(getApplicationContext(), Preferences.KEY_SL_ID, ""));
params.put("tution_center_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_TUTION_CENTER_SL, ""));
params.put("batch_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_BATCH_SL, ""));
params.put("batch_grup_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_BATCH_GRUP_SL, ""));
params.put("co_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_CO_SL, ""));
params.put("drange_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_DRANGE_SL, ""));
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-Apikey", Preferences.readString(getApplicationContext(), Preferences.KEY_USER_XAPIKEY, ""));
return headers;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringReq);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
private ArrayList<ActualNotis> addNotiToParticularNotiType(JSONArray jsonArray, String attachments) throws JSONException {
arrayListActualNotis = new ArrayList<>();
if (jsonArray.length() > 0) {
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject joInner = jsonArray.getJSONObject(j);
String notiTitle = joInner.getString("title");
String notiDesc = joInner.getString("decription");
String attach = "";
if (!attachments.equals(""))
attach = joInner.getString("attach");
arrayListActualNotis.add(new ActualNotis(notiTitle, notiDesc, attach));
}
} else {
arrayListActualNotis.add(new ActualNotis("No Notifications!!", "", ""));
}
return arrayListActualNotis;
}
}
AdapterNotification.java
public class AdapterNotification extends ExpandableRecyclerViewAdapter<AdapterNotification.NotiTypesViewHolder, AdapterNotification.ActualNotisViewHolder> {
private Activity mActivity;
public AdapterNotification(Activity activity, List<? extends ExpandableGroup> groups) {
super(groups);
this.mActivity = activity;
}
#Override
public NotiTypesViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.noti_type_group_view_holder, parent, false);
return new NotiTypesViewHolder(view);
}
#Override
public ActualNotisViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.actual_notis_child_view_holder, parent, false);
return new ActualNotisViewHolder(view);
}
#Override
public void onBindGroupViewHolder(NotiTypesViewHolder holder, int flatPosition, ExpandableGroup group) {
holder.setGroupName(group);
}
#Override
public void onBindChildViewHolder(ActualNotisViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
final ActualNotis notis = ((NotiTypes) group).getItems().get(childIndex);
holder.onBind(notis, group);
}
public class NotiTypesViewHolder extends GroupViewHolder {
private TextView txt_noti_type;
public NotiTypesViewHolder(View itemView) {
super(itemView);
txt_noti_type = (TextView) itemView.findViewById(R.id.txt_noti_type);
}
#Override
public void expand() {
txt_noti_type.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up_arrow, 0);
Log.e("Adapter", "Expand");
}
#Override
public void collapse() {
txt_noti_type.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down_arrow, 0);
Log.e("Adapter", "collapse");
}
public void setGroupName(ExpandableGroup group) {
txt_noti_type.setText(group.getTitle());
}
}
public class ActualNotisViewHolder extends ChildViewHolder {
private TextView txt_noti, txt_noti_desc;
public ActualNotisViewHolder(View itemView) {
super(itemView);
txt_noti = (TextView) itemView.findViewById(R.id.txt_noti);
txt_noti_desc = (TextView) itemView.findViewById(R.id.txt_noti_desc);
}
public void onBind(ActualNotis actualNotis, ExpandableGroup group) {
switch (actualNotis.getmNotiTitle()) {
case "noti_student":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_batch":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_institute":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_fee":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_sms":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
default:
break;
}
}
}
}
JSON Response From Server
{
"notification": {
"noti_batch": [
{
"title": "testtest",
"decription": "testtest"
}
],
"noti_institute": [
{
"title": "test",
"decription": "testtest",
"attach": ""
}
],
"noti_fee": [
{
"title": "test",
"decription": "test",
"attach": ""
}
],
"noti_sms": [
{
"title": "2016-11-03 00:00:00",
"decription": ""
}
]
},
"success": true
}
Thanks in advance!
setAdapter after getting data from the server i.e. inside onResponse() Or you have to notify adapter after changing data in List
I am getting list of data from json in which a parameter named as click_url is also there I fetch data in ListView .what I want when on click ListView I want to go to website that click_url contain .how can I do that.
jsons response:-
{
"offers": [{
"offer_id": 97245,
"name": "Earn Talktime & Data Android App",
"description": "Download and install",
"requirements": null,
"credit_delay": "0",
"featured_global": 0,
"epc": "0.00",
"conversion_rate": "0.016",
"testing_status": 0,
"testing_time": "0000-00-00 00:00:00",
"creative_id": 164789,
"creative_filename": "97245-164789.gif",
"creative_url": "https:\/\/asmclk.com\/creat\/97245-164789.gif",
"payout": 0.14,
"payout_custom": 0,
"stats_pending_ce": 0,
"currency_count": 70,
"target_system": 40,
"featured_profile": 0,
"click_url": "https:\/\/asmclk.com\/click.php?aff=105639&camp=97245&from=6453&prod=4&sub1=9555517491&prod_channel=1&device=fb772712-deff-4cc6-9365-41451ed33976&xt=Cb0xo807sNVx8ARZai%2B9dbKYSSBS2XZ23KjB3UGchmL3f8zjm8TT4okSW1ypbTqJ%3A6Jncp2Gx4KZjhM3JqeDoKQ%3D%3D",
"image_url": "\/\/adscendmedia.com\/creat\/97245-164789.gif",
"category_id": [17, 18],
"matches_target_system_detected": true,
"mobile_app": {
"store_id": "info.earntalktime",
"platform": 1
}
}, {
"offer_id": 107027,
"name": "Speak Up - Share Your Thoughts",
"description": "Take part in a survey and get rewarded",
"requirements": null,
"credit_delay": "0",
"featured_global": 0,
"epc": "0.00",
"conversion_rate": "0.006",
"testing_status": 0,
"testing_time": "0000-00-00 00:00:00",
"creative_id": 176235,
"creative_filename": "106989-176199.jpg",
"creative_url": "https:\/\/asmclk.com\/creat\/106989-176199.jpg",
"payout": 0.14,
"payout_custom": 0,
"stats_pending_ce": 0,
"currency_count": 70,
"target_system": 0,
"featured_profile": 0,
"click_url": "https:\/\/asmclk.com\/click.php?aff=105639&camp=107027&from=6453&prod=4&sub1=9555517491&prod_channel=1&device=fb772712-deff-4cc6-9365-41451ed33976&xt=udTdOoT4NSeWh53J%2FJaAf8UGzlJtpd9ZqLvy3TrPf53fPSmCqhaQpWu35HmDYP4V%3Apgx2an3HDsf7Za5dwjSA2A%3D%3D",
"image_url": "\/\/adscendmedia.com\/creat\/106989-176199.jpg",
"category_id": [20],
"matches_target_system_detected": true
}, {
"offer_id": 136497,
"name": "Pockets By ICICI Bank Android App",
"description": "Install and Launch",
"requirements": null,
"credit_delay": "0",
"featured_global": 0,
"epc": "0.00",
"conversion_rate": "0.021",
"testing_status": 0,
"testing_time": "0000-00-00 00:00:00",
"creative_id": 207101,
"creative_filename": "136497-207101.png",
"creative_url": "https:\/\/asmclk.com\/creat\/136497-207101.png",
"payout": 0.14,
"payout_custom": 0,
"stats_pending_ce": 0,
"currency_count": 70,
"target_system": 40,
"featured_profile": 0,
"click_url": "https:\/\/asmclk.com\/click.php?aff=105639&camp=136497&from=6453&prod=4&sub1=9555517491&prod_channel=1&device=fb772712-deff-4cc6-9365-41451ed33976&xt=TFkQXE6w185fT4sagQsrrkcdTd5LJrFe9K2pGZgJ3reXPR0MSVpvsMrjbcd9oShQ%3AaFy%2BGFW2OkHdvEvYmcIfsw%3D%3D",
"image_url": "\/\/adscendmedia.com\/creat\/136497-207101.png",
"category_id": [17, 18],
"matches_target_system_detected": true,
"mobile_app": {
"store_id": "com.icicibank.pockets",
"platform": 1
}
}]
}
listView Code:-
public void getAdscendDeal() {
String url = "http://ads.com/adwall/api/publisher/" + pubId + "/profile/" + aswallId + "/offers.json?subid1=" + m_szMobileNumber;
JSONObject jsonObject = new JSONObject();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response::" + response);
try {
JSONArray post = response.optJSONArray("offers");
for (int i = 0; i < post.length(); i++) {
JSONObject obj = post.getJSONObject(i);
m_Item = new CAdscenMediaDealStorage();
m_Item.setM_szHeaderText(obj.getString("name"));
m_Item.setM_szsubHeaderText(obj.getString("description"));
m_Item.setM_szDealValue(obj.getString("currency_count"));
m_Item.setM_szImageView(obj.getString("creative_url"));
m_Item.setM_Link(obj.getString("click_url"));
s_oDataset.add(m_Item);
}
if (!s_oDataset.isEmpty()) {
m_oAdapter = new CADscendDealAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error::" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
}
ListView Adapter
private class CADscendDealAdapter extends ArrayAdapter {
private final Context m_Context;// declaring context variable
private final ArrayList<CAdscenMediaDealStorage> s_oDataset;// declaring array list ariable
public CADscendDealAdapter(Context m_Context, ArrayList<CAdscenMediaDealStorage> mDataList) {
this.m_Context = m_Context;
s_oDataset = mDataList;
}
#Override
public int getCount() {// get total arraylist size
return s_oDataset.size();
}
#Override
public Object getItem(int position) {// get item position in array list
return s_oDataset.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("SetTextI18n")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = View.inflate(m_Context, R.layout.sooper_sonic, null);
viewHolder.m_Header = (TextView) convertView.findViewById(R.id.headingText);
viewHolder.m_Subheader = (TextView) convertView.findViewById(R.id.subHeaderText);
viewHolder.m_logoImage = (ImageView) convertView.findViewById(R.id.appImage);
viewHolder.m_getBtn = (Button) convertView.findViewById(R.id.getDealBtn);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.m_getBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
#Override
public void onClick(View v) {//send to deal detail page onclick getDeal Btn
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
i.putExtra("DealCode", s_oDataset.get(position).getM_szsubHeaderText());// get deal code from deal data storage
i.putExtra("headerText", s_oDataset.get(position).getM_szHeaderText());// get deal name from deal dta storage
v.getContext().startActivity(i);
}
});
CAdscenMediaDealStorage m = s_oDataset.get(position);
viewHolder.m_Header.setText(m.getM_szHeaderText());
viewHolder.m_Subheader.setText(m.getM_szsubHeaderText());
viewHolder.m_getBtn.setText("GET " + m.getM_szDealValue() + " POINTS");// set deal button text
Picasso.with(m_Context).load(m.getM_szImageView()).placeholder(R.drawable.placeholder).into(viewHolder.m_logoImage);
Picasso.with(m_Context).load(m.getM_szImageView()).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
width = width * 2;
height = height * 2;
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
viewHolder.m_logoImage.setImageBitmap(bitmap);
viewHolder.m_logoImage.requestLayout();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
// set deal logo
return convertView;
}
private class ViewHolder {
public TextView m_Header, m_Subheader, m_DummyText;
public ImageView m_logoImage;
public Button m_getBtn;
}
}
Set an OnItemClickListener on the ListView. The link will open in a browser if it is installed.
Try this code in your Activity,
m_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
String url = s_oDataset.get(position).getM_Link();
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(About.this, "No application can handle this request."
+ " Please install a webbrowser", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
I am facing problem in the list view where, when I click the plus button increment is happening but when I scroll the list view the text has been reset and increment value is updated in the other items too, and I am using the getter and setter method to save the data of the incremented value and also I am using interface to update the text from the fragment class, but it's not updating
Otc_Fragment.Java
public class Otc_Fragment extends Fragment implements CartNumber {
ArrayList<MobiData> otcdatalist;
ListView otc_list;
Otc_Fragment_Adapter otcFragmentAdapter;
TextView cart;
static TextView cartnumber;
RelativeLayout cartbox;
public Otc_Fragment() {
}
public static Fragment getInstance(int position) {
Otc_Fragment otcFragment = new Otc_Fragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
otcFragment.setArguments(bundle);
return otcFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View otcview = inflater.inflate(R.layout.fragments_otc, container, false);
otc_list = (ListView) otcview.findViewById(R.id.otc_list);
cartnumber = (TextView) otcview.findViewById(R.id.cartnumber);
cart = (TextView) otcview.findViewById(R.id.cart);
cartbox= (RelativeLayout) otcview.findViewById(R.id.cartbox);
Typeface cartface = Typeface.createFromAsset(getContext().getAssets(), "fonts/fontawesome.ttf");
cart.setTypeface(cartface);
otcdatalist = new ArrayList<MobiData>();
otcFragmentAdapter = new Otc_Fragment_Adapter(getActivity(), otcdatalist, this);
otc_list.setAdapter(otcFragmentAdapter);
catitems();
return otcview;
}
private void catitems() {
String medurl = getResources().getString(R.string.CommonUrl) + "medicines_catwise.php";
final int position = getArguments().getInt("position", 0);
JsonObjectRequest medobjreq = new JsonObjectRequest(Request.Method.GET, medurl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject orderobj1 = response.getJSONObject("orders");
JSONArray orderarray = orderobj1.getJSONArray("menu1");
JSONObject orderobj = orderarray.getJSONObject(position);
JSONArray itemsarray = orderobj.getJSONArray("items");
for (int i = 0; i < itemsarray.length(); i++) {
JSONObject itemsobj = itemsarray.getJSONObject(i);
MobiData itemsdata = new MobiData();
itemsdata.setProductidotc(itemsobj.getString("id"));
itemsdata.setProductnameotc(itemsobj.getString("medicine_name"));
itemsdata.setProductpriceotc(itemsobj.getString("price"));
otcdatalist.add(itemsdata);
}
} catch (JSONException e) {
e.printStackTrace();
}
otcFragmentAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("OtcTabError", String.valueOf(error));
}
});
medobjreq.setRetryPolicy(new DefaultRetryPolicy(5000000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(medobjreq);
}
#Override
public void setcount(String count) {
Toast.makeText(getActivity(), count, Toast.LENGTH_LONG).show();
cartnumber.setText(count);
}
}
Otc_Fragment_Adapter.Java
public class Otc_Fragment_Adapter extends ArrayAdapter<MobiData> {
ArrayList<MobiData> otcproducrlist;
CartNumber cartNumber;
String tid;
SharedPreferences preferences;
SharedPreferences.Editor editorpref;
public Otc_Fragment_Adapter(Context context, ArrayList<MobiData> otcproducrlist, CartNumber cartNumber) {
super(context, R.layout.fragment_otc_row, otcproducrlist);
this.otcproducrlist = otcproducrlist;
this.cartNumber = cartNumber;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Productholder productholder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.fragment_otc_row, parent, false);
productholder = new Productholder();
productholder.productdecrement = (TextView) convertView.findViewById(R.id.productdecrement);
productholder.productsingle = (TextView) convertView.findViewById(R.id.productsingle);
productholder.productincrement = (TextView) convertView.findViewById(R.id.productincrement);
productholder.productname = (TextView) convertView.findViewById(R.id.productname);
productholder.product_price = (TextView) convertView.findViewById(R.id.product_price);
convertView.setTag(productholder);
} else {
productholder = (Productholder) convertView.getTag();
}
Typeface otctext = Typeface.createFromAsset(getContext().getAssets(), "fonts/fontawesome.ttf");
productholder.productdecrement.setTypeface(otctext);
productholder.productincrement.setTypeface(otctext);
final MobiData productdata = otcproducrlist.get(position);
productholder.productname.setText(productdata.getProductnameotc());
productholder.product_price.setText(productdata.getProductpriceotc());
productdata.setSinglelist(productholder.productsingle.getText().toString());
productholder.productsingle.setText(productdata.getSinglelist());
final String proids = productdata.getProductidotc();
SharedPreferences tempvalue = getContext().getSharedPreferences("datapref", Context.MODE_PRIVATE);
String tempid = tempvalue.getString("tempid", "");
if (tempid != "") {
tid = tempid;
} else {
int min = 65;
int max = 8000;
Random r = new Random();
tid = String.valueOf(r.nextInt(max - min + 1) + min);
preferences = getContext().getSharedPreferences("datapref", Context.MODE_PRIVATE);
editorpref = preferences.edit();
editorpref.putString("tempid", tid);
editorpref.apply();
}
productholder.productincrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int plus = Integer.parseInt(productholder.productsingle.getText().toString());
plus++;
productholder.productsingle.setText(String.valueOf(plus));
productdata.setSinglelist(String.valueOf(plus));
SharedPreferences uid = getContext().getSharedPreferences("datapref", Context.MODE_PRIVATE);
String userid = uid.getString("uid", "");
String addcarturl = getContext().getResources().getString(R.string.CommonUrl) + "add_to_cart.php?userid=" + userid + "&mid=" + proids + "&quantity=" + String.valueOf(plus) + "&tempid=" + tid;
Log.d("Addcart", addcarturl);
JsonObjectRequest addreq = new JsonObjectRequest(Request.Method.GET, addcarturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String count = response.getString("count");
cartNumber.setcount(count);
} catch (JSONException e) {
Log.d("OtcAddCart", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("AddCart", String.valueOf(error));
}
});
addreq.setRetryPolicy(new DefaultRetryPolicy(10000000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
});
productholder.productdecrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int minus = Integer.parseInt(productholder.productsingle.getText().toString());
if (minus <= 0) {
Toast.makeText(getContext(), "Minimum Quantity is 1", Toast.LENGTH_SHORT).show();
productholder.productsingle.setText(String.valueOf(minus));
productdata.setSinglelist(String.valueOf(minus));
} else {
minus--;
productholder.productsingle.setText(String.valueOf(minus));
productdata.setSinglelist(String.valueOf(minus));
SharedPreferences viewpref = getContext().getSharedPreferences("datapref", Context.MODE_PRIVATE);
String cartduid = viewpref.getString("uid", "");
String cartdtempid = viewpref.getString("tempid", "");
String decremnturl = getContext().getResources().getString(R.string.CommonUrl) + "del_cartitems.php?mid=" + proids + "&userid=" + cartduid + "&tempid=" + cartdtempid;
Log.d("Decremnturl", decremnturl);
JsonObjectRequest decrementreq = new JsonObjectRequest(Request.Method.GET, decremnturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response decremnet", String.valueOf(response));
try {
JSONArray decarray = response.getJSONArray("items");
Log.d("Cartdecrement", String.valueOf(decarray));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("DecrementError", String.valueOf(error));
}
});
decrementreq.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(decrementreq);
}
}
});
return convertView;
}
static class Productholder {
private TextView productname;
private TextView product_price;
private TextView productdecrement;
private TextView productsingle;
private TextView productincrement;
}
}
CartNumber.java
public interface CartNumber {
public void setcount(String count);
}