repeated values are coming in listView in android - android

I'm working on a ListView with a BaseAdapter. I am showing values from a JSON file to a ListView. My problem is that I am only getting the last value in every list Items,
Activity:
public class CustomerList extends Activity {
ImageView ic_back;
ListView lv_cust;
LoadJson loadcustomers;
String customers;
ArrayList<Customer> customerList;
CustomerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
lv_cust = (ListView) findViewById(R.id.lv_customers);
ic_back = (ImageView) findViewById(R.id.ic_back);
loadcustomers = new LoadJson(CustomerList.this, "customers");
customers = loadcustomers.loadJSONFromAsset();
ic_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
//setting static data to list..
fetchCustomers();
adapter = new CustomerAdapter(CustomerList.this, customerList);
lv_cust.setAdapter(adapter);
adapter.notifyDataSetChanged();
//end
}
//void fill row data..
void fetchCustomers() {
customerList = new ArrayList<>();
customerList.clear();
try {
JSONObject mainObj = new JSONObject(customers);
JSONObject dataObj = mainObj.getJSONObject("data");
JSONArray customerArray = dataObj.getJSONArray("result");
for (int i = 0; i < customerArray.length(); i++) {
JSONObject c = customerArray.getJSONObject(i);
Customer customer = new Customer();
customer.setAccountNumber(c.getString("accountNumber"));
customer.setAccountStatus(c.getString("accountStatus"));
customer.setAccountType(c.getString("accountType"));
customer.setCustomerCategory(c.getString("customerCategory"));
customerList.add(customer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Adapter class
public class CustomerAdapter extends BaseAdapter {
private Context mContext;
private final ArrayList<Customer> customer;
Integer selected_position = -1;
public CustomerAdapter(Context c, ArrayList<Customer> customer) {
mContext = c;
this.customer = customer;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return customer.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.raw_customer, parent, false);
holder = new ViewHolder();
holder.tv_account_no = (TextView) convertView.findViewById(R.id.tv_act_no);
holder.tv_act_sts = (TextView) convertView.findViewById(R.id.tv_act_sts);
holder.tv_act_name = (TextView) convertView.findViewById(R.id.tv_act_name);
holder.tv_cust_cat = (TextView) convertView.findViewById(R.id.tv_cust_cat);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv_account_no.setText(customer.get(position).getAccountNumber());
holder.tv_act_sts.setText(customer.get(position).getAccountStatus());
holder.tv_act_name.setText(customer.get(position).getAccountType());
holder.tv_cust_cat.setText(customer.get(position).getCustomerCategory());
return convertView;
}
public static class ViewHolder {
TextView tv_account_no;
TextView tv_act_sts;
TextView tv_act_name;
TextView tv_cust_cat;
}
}
josn file
{
"code": 600,
"status": "success",
"message": null,
"data": {
"result": [
{
"accountNumber": "0000160057",
"accountStatus": "ACTIVE",
"accountType": "ACT09",
"address": "10jan2017wom1fttx5",
"mobilePhone": "1235123412",
"phone": null,
"customerCategory": "VIP"
},
{
"accountNumber": "0000160058",
"accountStatus": "DEACTIVE",
"accountType": "ACT11",
"address": "10jan2017wom1fttx5",
"mobilePhone": "33408805",
"phone": null,
"customerCategory": "VIP"
},
{
"accountNumber": "0000160059",
"accountStatus": "REGISTERED",
"accountType": "ACT19",
"address": "10jan2017wom1fttx5",
"mobilePhone": "9976878756",
"phone": null,
"customerCategory": "Default"
},
{
"accountNumber": "0000160064",
"accountStatus": "ACTIVE",
"accountType": "ACT23",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "VIP"
},
{
"accountNumber": "0000160044",
"accountStatus": "ACTIVE",
"accountType": "ACT67",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "Default"
},
{
"accountNumber": "0003460097",
"accountStatus": "REGISTERED",
"accountType": "ACT56",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "Default"
},
{
"accountNumber": "0000160099",
"accountStatus": "ACTIVE",
"accountType": "ACT46",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "Default"
},
{
"accountNumber": "0000160090",
"accountStatus": "ACTIVE",
"accountType": "ACT29",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "VIP"
},
{
"accountNumber": "0000160044",
"accountStatus": "ACTIVE",
"accountType": "ACT55",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "VIP"
},
{
"accountNumber": "0000160045",
"accountStatus": "REGISTERED",
"accountType": "ACT23",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "VIP"
},
{
"accountNumber": "0000160077",
"accountStatus": "ACTIVE",
"accountType": "ACT25",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "Default"
},
{
"accountNumber": "0000160075",
"accountStatus": "REGISTERED",
"accountType": "ACT99",
"address": "10jan2017wom1fttx5",
"mobilePhone": "3556456745",
"phone": null,
"customerCategory": "Default"
}
],
"totalRecords": 14
}
}
fetchjson
public class LoadJson {
private Context mContext;
private final String filename;
public LoadJson(Context c, String filename) {
mContext = c;
this.filename = filename;
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = mContext.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}

You should Use View holder pattern edit your getView method and also add class ViewHolder to you adapter as follows:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder mHolder;
final Customer c = getItem(position);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.raw_customer, null);
mHolder = new ViewHolder();
mHolder.tv_account_no = (TextView) v.findViewById(R.id.tv_act_no);
mHolder.tv_act_sts = (TextView) v.findViewById(R.id.tv_act_sts);
mHolder.tv_act_name = (TextView) v.findViewById(R.id.tv_act_name);
mHolder.tv_cust_cat = (TextView) v.findViewById(R.id.tv_cust_cat);
convertView.setTag(mHolder);
} else {
mHolder = (ViewHolder) convertView.getTag();
}
mHolder.tv_account_no.setText(c.getAccountNumber());
mHolder.tv_act_sts.setText(c.getAccountStatus());
mHolder.tv_act_name.setText(c.getAccountType());
mHolder.tv_cust_cat.setText(c.getCustomerCategory());
return convertView;
}
private class ViewHolder {
private TextView tv_account_no, tv_act_sts, tv_act_name, tv_cust_cat ;
}
Edit: try to do that also
#Override
public Customer getItem(int position) {
// TODO Auto-generated method stub
return customer.get(position);
}

Set your adapter in your fetchCustomers() fuction
public class CustomerList extends Activity {
ImageView ic_back;
ListView lv_cust;
LoadJson loadcustomers;
String customers;
ArrayList<Customer> customerList;
CustomerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
lv_cust = (ListView) findViewById(R.id.lv_customers);
ic_back = (ImageView) findViewById(R.id.ic_back);
loadcustomers = new LoadJson(CustomerList.this, "customers");
customers = loadcustomers.loadJSONFromAsset();
ic_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
//setting static data to list..
fetchCustomers();
//end
}
//void fill row data..
void fetchCustomers() {
customerList = new ArrayList<>();
customerList.clear();
try {
JSONObject mainObj = new JSONObject(customers);
JSONObject dataObj = mainObj.getJSONObject("data");
JSONArray customerArray = dataObj.getJSONArray("result");
for (int i = 0; i < customerArray.length(); i++) {
JSONObject c = customerArray.getJSONObject(i);
Customer customer = new Customer();
customer.setAccountNumber(c.getString("accountNumber"));
customer.setAccountStatus(c.getString("accountStatus"));
customer.setAccountType(c.getString("accountType"));
customer.setCustomerCategory(c.getString("customerCategory"));
customerList.add(customer);
}
adapter = new CustomerAdapter(CustomerList.this, customerList);
lv_cust.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}
try this and this doesn't help. Please comment me will help you

Finally...I found the solution to my problem that i have defined the string as "static" in my model classes,that is the main problem.I removed "static" and fixed the issue.
Got solution from below thread.
Repeatable values in list in android

Related

Display inner Items under Certain List Item?

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/

How to send to websites on click listview in android?

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();
}
}
});

How to use two array list in Spinner from which data is reflected in grid view on the basis of tag id

I want to reflect all refrigerator items on the basis of tagid,but size of
ArrayList is returning null, ArrayIndexOutOFBoundException. I have used selectCategory spinner which is reflecting subcategory name list, parallely I also wants to use tagid of selected category to reflect items of category selected in spinner in Gridview. I have JSON data like this.
JSON RESULT:
{
"code": "200",
"action": "success",
"message": "Your request has successfully completed",
"status": "1",
"subcategory_detail": [
{
"category_id": "113626",
"category": "Refrigerators",
"tag_id": "818415",
"type_id": "63942",
"disp_order": "0",
"shop_id": "7508"
},
{
"category_id": "113627",
"category": "Air Condition",
"tag_id": "818416",
"type_id": "63942",
"disp_order": "1",
"shop_id": "7508"
},
{
"category_id": "113628",
"category": "Kitchen Appliances",
"tag_id": "818417",
"type_id": "63942",
"disp_order": "2",
"shop_id": "7508"
},
{
"category_id": "113629",
"category": "Utilities",
"tag_id": "818418",
"type_id": "63942",
"disp_order": "3",
"shop_id": "7508"
},
{
"category_id": "113634",
"category": "Washing Machine",
"tag_id": "818434",
"type_id": "63942",
"disp_order": "4",
"shop_id": "7508"
}
]
}
OnItemSelectedListener:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
str = selectCategory.getSelectedItem().toString();
subcatIdList=new ArrayList<>();
subcattagidList = new ArrayList<>();
Log.d("categoryidid",""+subcatIdList.size());
int x=selectCategory.getSelectedItemPosition();
String y=subcatIdList.get(position+1);
Toast.makeText(getApplicationContext(),"List ID "+y,Toast.LENGTH_SHORT).show();
if (position == 0)
{
getSupportActionBar().setTitle("" + category_name);
}else {
getSupportActionBar().setTitle("" + str);
b = str;
Toast.makeText(ProductListGridView.this,"b:"+b,Toast.LENGTH_SHORT).show();
// new AsyncSearchingTask().execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
AsyncTask Class:
class SubCatList extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunction userFunction = new UserFunction();
JSONObject json = userFunction.getSubCAtList(category_id);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
JSONArray posts = json.getJSONArray("subcategory_detail");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
a=post.getString("category_id").toString();
b=post.getString("category").toString();
c = post.getString("type_id").toString();
Log.e("Response categorywise", "" + b);
Log.e("Response categoryidwise",""+a);
Log.e("Response categorytagid",""+c);
subcatIdList.add(a);
subcatNameList.add(b);
subcattagidList.add(c);
}
}else if(Integer.parseInt(res) == 0){
// Toast.makeText(getApplicationContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
}
}
Log.d("monacategoryid",""+subcatIdList.size());
Log.d("monaTagid",""+subcatIdList.size());
Toast.makeText(getApplicationContext(), "c"+c, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
you can try this way,(change in listener)
String itemId ="";
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selValue = parent.getItemAtPosition(position).toString();
for(int z= 0; z<subcatNameList.size();z++){
if(selValue.trim().equal(""+subcatNameList.get(z).trim()){
// do some changes according to
itemId = subcattagidList.get(z);
new callAsukforChanges().execute();
}
}
}
I hope this will help you. thanks

How to show other JsonArray in RecyclerView on Android

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);
}
}
}

Can't use Volley to display two custom ListView

I am a beginner in android, and i am trying to use Volley to create a custom list which contains list of images and text description for each. There are two activities as list view, downloaded json data using volley, use OnItemClickListener to start other activity. the first activity is complete to run, when i click the other one, the Logcat got nothing to show, but the second Listview activity is blank only have title...
This is Logcat i don't it has usefully or not.
All my Logcat
05-22 16:09:32.549: V/Monotype(14980): SetAppTypeFace- try to flip, app = com.wangjian.klmeet_sightseeing
05-22 16:09:32.550: V/Monotype(14980): Typeface getFontPathFlipFont - systemFont = default
05-22 16:09:33.378: D/Volley(14980): [1] 2.onErrorResponse: MainActivity
my code look like this:
The first activity SightseeingActivity.java
public class SightseeingActivity extends Activity {
//Log tag
private static final String TAG = SightseeingActivity.class.getSimpleName();
//Sightseeing json url
private static final String url = "http://wangjian.site90.net/json/api_klmeet_sightseeing.json";
private ProgressDialog pDialog;
private List<Sight> sightList = new ArrayList<Sight>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sightseeing_activity);
listView = (ListView) findViewById(R.id.sight_list);
adapter = new CustomListAdapter(this, sightList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
//changing action bar color
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b")));
//Creating volley request obj
JsonArrayRequest sightReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response){
Log.d(TAG, response.toString());
pDialog.dismiss();
for (int i = 0; i < response.length(); i++){
try{
JSONObject obj = response.getJSONObject(i);
Sight sight = new Sight();
sight.setTitle(obj.getString("title"));
sight.setThumbnailUrl(obj.getString("image"));
sight.setReadmore(obj.getString("readmore"));
sight.setPreintroduce(obj.getString("preintroduce"));
sight.setTag(obj.getString("tag"));
sightList.add(sight);
} catch (JSONException e) {
e.printStackTrace();
}
}
//notifying list adapter about data changes
//so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(sightReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Class<? extends Activity> activityToSrart = null;
switch (position){
case 0:
activityToSrart = MainActivity.class;
break;
case 1:
activityToSrart = MerdekaSquare.class;
break;
}
Intent i = new Intent(getApplicationContext(), activityToSrart);
startActivity(i);
}
});
}
}
The second activity MainActivity
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://wangjian.site90.net/json/api_klmeet_sightseeing_face.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
i will upload more code if needed.
FeedListAdapter.java
#SuppressLint("InflateParams")
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
FeedIteam
package com.wangjian.klmeet_sightseeing.model;
public class FeedItem {
private int id;
private String name, status, image, profilePic, timeStamp, url;
public FeedItem() {
}
public FeedItem(int id, String name, String image, String status,
String profilePic, String timeStamp, String url) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profilePic = profilePic;
this.timeStamp = timeStamp;
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
i upload XML file if needed
feed_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/feed_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="#dimen/feed_item_margin"
android:layout_marginRight="#dimen/feed_item_margin"
android:layout_marginTop="#dimen/feed_item_margin"
android:background="#drawable/bg_parent_rounded_corner"
android:orientation="vertical"
android:paddingBottom="#dimen/feed_item_padding_top_bottom"
android:paddingTop="#dimen/feed_item_padding_top_bottom" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="#dimen/feed_item_padding_left_right"
android:paddingRight="#dimen/feed_item_padding_left_right" >
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/profilePic"
android:layout_width="#dimen/feed_item_profile_pic"
android:layout_height="#dimen/feed_item_profile_pic"
android:scaleType="fitCenter" >
</com.android.volley.toolbox.NetworkImageView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/feed_item_profile_info_padd" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
<TextView
android:id="#+id/timestamp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/timestamp"
android:textSize="#dimen/feed_item_timestamp" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/txtStatusMsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="#dimen/feed_item_status_pad_left_right"
android:paddingRight="#dimen/feed_item_status_pad_left_right"
android:paddingTop="#dimen/feed_item_status_pad_top" />
<TextView
android:id="#+id/txtUrl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:linksClickable="true"
android:paddingBottom="10dp"
android:paddingLeft="#dimen/feed_item_status_pad_left_right"
android:paddingRight="#dimen/feed_item_status_pad_left_right"
android:textColorLink="#color/link" />
<info.androidhive.listviewfeed.FeedImageView
android:id="#+id/feedImage1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:scaleType="fitXY"
android:visibility="visible" />
</LinearLayout>
</LinearLayout>
This is my first activity
the second one should be like this
But
JSON
{
"feed": [
{
"id": 1,
"name": "National Geographic Channel",
"image": "http://api.androidhive.info/feed/img/cosmos.jpg",
"status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 2,
"name": "TIME",
"image": "http://api.androidhive.info/feed/img/time_best.jpg",
"status": "30 years of Cirque du Soleil's best photos",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg,
"timeStamp": "1403375851930",
"url": "http://ti.me/1qW8MLB"
},
{
"id": 5,
"name": "Abraham Lincoln",
"image": null,
"status": "That some achieve great success, is proof to all that others can achieve it as well",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 3,
"name": "Discovery",
"image": "http://api.androidhive.info/feed/img/discovery_mos.jpg",
"status": "A team of Austrian scientists has developed a laser system that causes fruit flies to dance.",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://dsc.tv/xmMxD"
},
{
"id": 4,
"name": "Ravi Tamada",
"image": "http://api.androidhive.info/feed/img/nav_drawer.jpg",
"status": "Android Sliding Menu using Navigation Drawer",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/"
},
{
"id": 6,
"name": "KTM",
"image": "http://api.androidhive.info/feed/img/ktm_1290.jpg",
"status": "\"The Beast\" KTM 1290 Super Duke",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
},
{
"id": 7,
"name": "Harley-Davidson",
"image": "http://api.androidhive.info/feed/img/harley_bike.jpg",
"status": "We’re assembling riders of every style, bike, and passion. If you ride with conviction, ride with us. You have 24 days to get ready for World Ride. Prepare by visiting:",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://bit.ly/1wmBWaN"
},
{
"id": 8,
"name": "Rock & Girl",
"image": "http://api.androidhive.info/feed/img/rock.jpg",
"status": "A long time back...",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
},
{
"id": 8,
"name": "Gandhi",
"image": null,
"status": "An eye for an eye will make the whole world blind.",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
},
{
"id": 9,
"name": "LIFE",
"image": "http://api.androidhive.info/feed/img/life_photo.jpg",
"status": "In 1965, LIFE photographer Bill Ray spent weeks with the Hells Angels, but his amazing photos never ran in the magazine",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://ti.me/1rfcQa4"
},
{
"id": 10,
"name": "Shakira",
"image": "http://api.androidhive.info/feed/img/shakira_la_la.png",
"status": "Download La La La (Brazil 2014) from iTunes:",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://smarturl.it/FWCalbum?IQid=sh"
},
{
"id": 11,
"name": "A. R. rahman",
"image": "http://api.androidhive.info/feed/img/ar_bw.jpg",
"status": "",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
}
]
}
I'm a newbie at this stuff so any help will be appreciated. Thanks in Advance.!
Firstly, private String URL_FEED = "http://wangjian.site90.net/json/api_klmeet_sightseeing_face.json"; in your MainActivity doesn't exist and when I tried it in AdvanceRestClient I got this:
So I tried looking more into directory structure of your WS and found there isn't any such URL you have mentioned as above.
Further more, I got security issues while trying to access your directory:
I am not sure what you are looking for seriously, but you could try with a valid URL in MainActivity and it should work fine.
Security issue creep me out literaly. :(

Categories

Resources