My listview is showing the last item twice.
I want to show the members from database with volley and MySQL, sending request from android to API which is programmed in PHP and the API returns
JSON data.
Here is my code:
String email, member_id, member_type;
ListView community_member_list;
Context context = this;
MemberAdapter memberAdapter;
List<Model> modelList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_community);
SharedPreferences SP = getSharedPreferences("MemberSession", MODE_PRIVATE);
Boolean member_logged_in = SP.getBoolean("member_logged_in", false);
email = SP.getString("email", null);
member_id = SP.getString("member_id", null);
member_type = SP.getString("member_type", null);
if (!member_logged_in)
{
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}else{
community_member_list = (ListView) findViewById(R.id.community_members_list);
memberAdapter = new MemberAdapter(getApplicationContext(), R.layout.community_list_item, modelList);
community_member_list.setAdapter(memberAdapter);
get_community_members();
}
}
public void get_community_members()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, new Login().site_url+"community",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("members");
Model model = null;
for(int i=0; i<jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
model = new Model();
model.setMember_id(finalObject.getInt("physician_id"));
model.setProfile_photo(finalObject.getString("profile_photo"));
model.setFirst_name(finalObject.getString("first_name"));
model.setLast_name(finalObject.getString("last_name"));
model.setDesignation(finalObject.getString("designation"));
model.setOrganization(finalObject.getString("organization"));
modelList.add(model);
}
memberAdapter.add(model);
memberAdapter.setNotifyOnChange(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error "+error, Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("member_id", member_id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private class MemberAdapter extends ArrayAdapter {
private List<Model> memberList;
private int resource;
private LayoutInflater inflater;
MemberAdapter(Context context, int resource, List<Model> objects) {
super(context, resource, objects);
memberList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
if(convertView == null)
{
convertView = inflater.inflate(resource, null);
}
final ImageView imageView;
TextView textView, textView2;
imageView = (ImageView)convertView.findViewById(R.id.imageView);
textView = (TextView)convertView.findViewById(R.id.textView);
textView2 = (TextView) convertView.findViewById(R.id.textView2);
com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("http://www.plexusd.com/uploads/specialist/" + memberList.get(position).getProfile_photo(), imageView, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
imageView.setImageResource(R.mipmap.avatar);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
imageView.setImageResource(R.mipmap.avatar);
}
});
textView.setText("Dr. "+memberList.get(position).getFirst_name()+" "+memberList.get(position).getLast_name());
textView2.setText(""+memberList.get(position).getDesignation()+",\n"+memberList.get(position).getOrganization());
return convertView;
}
}
Here is the picture of list from mobile.
Remove memberAdapter.add(model); inside onResponse after for loop. model object holds the last object and you are adding that in adapter again so last object showing 2 times.
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("members");
Model model = null;
for(int i=0; i<jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
model = new Model();
model.setMember_id(finalObject.getInt("physician_id"));
model.setProfile_photo(finalObject.getString("profile_photo"));
model.setFirst_name(finalObject.getString("first_name"));
model.setLast_name(finalObject.getString("last_name"));
model.setDesignation(finalObject.getString("designation"));
model.setOrganization(finalObject.getString("organization"));
modelList.add(model);
}
memberAdapter.add(model); // remove this.
memberAdapter.setNotifyOnChange(true);
} catch (JSONException e) {
e.printStackTrace();
}
you added model twice , one of it in the loop ,not of it after the loop
Related
I get data in JSON from API, and there are id and url. Now, i need to create a button "Add to favorites" for each image that i display. When i try to set adapter.setListener(this);, i get an error, because i can't use string format.
How can i resolve this problem? I spend 5 hours on this, and can't resolve it :(
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listItem);
favorites = findViewById(R.id.buttonFav);
catDetailsArrayList = new ArrayList<>();
myAdapter = new MyAdapter(MainActivity.this ,catDetailsArrayList);
searchbtn = findViewById(R.id.buttonSearch);
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
catDetailsArrayList.clear();
myAdapter.notifyDataSetChanged();
displayCats();
}
});
});
}
private void displayCats() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String jsonCatUrl2 = jsonObject1.getString("url");
String jsonCatId2 = jsonObject1.getString("id");
CatDetails catDetails = new CatDetails();
catDetails.setUrl(jsonCatUrl2);
catDetails.setId(jsonCatId2);
catDetailsArrayList.add(catDetails);
}
listView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
MyAdapter:
public class MyAdapter extends BaseAdapter {
public Activity activity;
public ArrayList<CatDetails> catDetailsArrayList;
public LayoutInflater inflater;
Button btn;
TextView idnr;
public MyAdapter(Activity activity, ArrayList<CatDetails> catDetailsArrayList) {
this.activity = activity;
this.catDetailsArrayList = catDetailsArrayList;
}
#Override
public Object getItem(int position) {
return catDetailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (inflater == null) {
inflater = this.activity.getLayoutInflater();
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
}
ImageView imageView = convertView.findViewById(R.id.ImageView);
final CatDetails catDetails = this.catDetailsArrayList.get(position);
Picasso.get().load(catDetails.getUrl()).into(imageView);
idnr =convertView.findViewById(R.id.textView);
btn = convertView.findViewById(R.id.buttonFav);
final String id = catDetails.getId();
idnr.setText(catDetails.getId());
return convertView;
}
#Override
public int getCount() {
return this.catDetailsArrayList.size();
}
I display the id that i receive from server for each item, it's ok, but i don't know how to set the button "add to favorites" to works fine. It must receive item id (that i received from server) as a param, but id is in string format.
final String id = catDetails.getId();
change it to
final String id = Integer.toString(catDetails.getId());
The array "ary" receives the data from the server and the Adapter, but doesn't show the data in the ListView. Is there a problem with receiving the data after the onCreate() method?
Does anyone have an idea/solution?
public class ScheduleActivity extends AppCompatActivity {
public ListView list;
public ScheduleViewAdapter mSVAdapter;
public JSONArray ary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
buildList();
}
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter.notifyDataSetChanged();
}
private void buildList() {
final RequestQueue requestQueue = Volley.newRequestQueue(this);
// String URL1 = "http://10.0.2.2:3000/users/:userId/offers/";
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// vorläufiger hardcode
String userID = "5b2f9f3cd56ff67974d2f58e";
/* userID = settings.getString("userID", "");*/
String URL1 = "http://10.0.2.2:3000/orders/?buyerID=".concat(userID).concat("/userorder");
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("ConsoleText", response);
try {
JSONArray ary2 = new JSONArray(response);
setListView(ary2);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ConsoleText", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
requestQueue.add(stringRequest);
}
}
Okay, so this is an edit.
That's the adapter. maybe you can find the error here. Thanks:
public class ScheduleViewAdapter extends BaseAdapter{
private Context mContext;
private JSONArray orders;
public ScheduleViewAdapter() {
}
public ScheduleViewAdapter(Context mContext, JSONArray orders) {
this.mContext = mContext;
this.orders = orders;
}
#Override
public int getCount() {
if(orders == null){
return 0;
}else{
return orders.length();
}
}
#Override
public JSONObject getItem(int position) {
if(orders == null){
return null;
}else{
return orders.optJSONObject(position);
}
}
#Override
public long getItemId(int position) {
JSONObject object = getItem(position);
return object.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
//Only creates new view when recycling isn't possible
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_schedule, parent, false);
}
TextView tvItem =(TextView)convertView.findViewById(R.id.tvItem);
// TextView tvUserName =(TextView)convertView.findViewById(R.id.tvUserName);
// TextView tvAddress =(TextView)convertView.findViewById(R.id.tvAddress);
JSONObject json_data = getItem(position);
if(json_data != null){
try {
String type = json_data.getString("title");
// tvItem.append("" + json_data.getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
return convertView;
}
}
Change your method to this,
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
}
and onCreate to this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
buildList();
}
I want to make a List View from a JSON Array from a database,but i cant implement the method to put the array in a list,i got some idea about the method from this tutorial: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView
and this video:https://www.youtube.com/watch?v=u8iyFEZaHLU
this is my main code:
public class ViewDosen extends AppCompatActivity {
TextView tvWelcome;
ListView listView;
List<Publikasi> lstPublikasi;
JSONArray jsonArray;
String namaDosen,kodeDosen;
PublikasiAdapter publikasiAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_dosen);
SharedPreferences DataDosen = getSharedPreferences("Dosen", Context.MODE_PRIVATE);
kodeDosen = DataDosen.getString("kodeDosen","");
namaDosen = DataDosen.getString("namaDosen","");
tvWelcome = (TextView) findViewById(R.id.tvWelcome);
tvWelcome.setText("Welcome "+namaDosen+"("+kodeDosen+")");
listView = (ListView) findViewById(R.id.lstPublikasi);
lstPublikasi = new ArrayList<Publikasi>();
publikasiAdapter = new PublikasiAdapter(lstPublikasi,getApplicationContext());
listView.setAdapter(publikasiAdapter);
}
String uri = String.format(Utils.viewURL,kodeDosen);
private void showList(){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//this is where i will put the JSON Array
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
this is my model:
public class Publikasi {
public String namaJurnal,tipePublikasi,status,periode;
public Publikasi(JSONObject object) {
try{
this.namaJurnal =object.getString("namaJurnal");
this.tipePublikasi = object.getString("tipePublikasi");;
this.status = object.getString("status");;
this.periode = object.getString("periode");;
}catch (JSONException e){
e.printStackTrace();
}
public static ArrayList<Publikasi> fromJSON(JSONArray jsonObjects){
ArrayList<Publikasi> publikasi = new ArrayList<Publikasi>();
for(int i = 0;i<jsonObjects.length();i++){
try{
}catch (){
}
}
return publikasi;
}
}
}
this is my adapter:
public class PublikasiAdapter extends ArrayAdapter<Publikasi>{
private List<Publikasi> lstPublikasi;
private Context mCtx;
public PublikasiAdapter(List<Publikasi> P,Context c){
super(c, R.layout.list_publikasi,P);
this.lstPublikasi = P;
this.mCtx = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_publikasi, parent, false);
}
TextView textNama = (TextView) convertView.findViewById(R.id.textNama);
TextView textDetail = (TextView) convertView.findViewById(R.id.textDetail);
TextView textStatus = (TextView) convertView.findViewById(R.id.textStatus);
TextView textPeriode = (TextView) convertView.findViewById(R.id.textPeriode);
Publikasi publikasi = lstPublikasi.get(position);
textNama.setText(publikasi.namaJurnal);
textDetail.setText(publikasi.tipePublikasi);
textStatus.setText(publikasi.status);
textPeriode.setText(publikasi.periode);
return convertView;
}
}
this is the JSON format:
[{"idPublikasi":"62","kodeDosen":"D0001","gambar":"uploaddosen/D0001_0.50622400
1523420013.jpg","namaJurnal":"pizza","tipePublikasi":"Scopus","status":"Submit","periode":"Genap
2018"},{"idPublikasi":"64","kodeDosen":"D0001","gambar":"uploaddosen/D0001_0.94649000
1523432053.jpg","namaJurnal":"SPAS 12","tipePublikasi":"Scopus","status":"On Review","periode":"Sebelum
2015"}]
You are creating an empty list and you're giving it to the adapter. So, there is not a list to display.
listView = (ListView) findViewById(R.id.lstPublikasi);
lstPublikasi = new ArrayList<Publikasi>();
publikasiAdapter = new PublikasiAdapter(lstPublikasi,getApplicationContext());
You must fill the list when the response come successfully. After that you must give the list to the adapter's method such as "updateList();"
Here is the sample:
private void showList() {
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null, new Response.Listener < JSONArray > () {#
Override
public void onResponse(JSONArray response) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
lstPublikasi.add(new Publikasi(jsonArray.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
publikasiAdapter.updateList(lstPublikasi);
}
}, new Response.ErrorListener() {#
Override
public void onErrorResponse(VolleyError error) {}
});
}
public class PublikasiAdapter extends ArrayAdapter < Publikasi > {
private List < Publikasi > lstPublikasi;
private Context mCtx;
public PublikasiAdapter(List < Publikasi > P, Context c) {
super(c, R.layout.list_publikasi, P);
this.lstPublikasi = P;
this.mCtx = c;
}#
Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_publikasi, parent, false);
}
TextView textNama = (TextView) convertView.findViewById(R.id.textNama);
TextView textDetail = (TextView) convertView.findViewById(R.id.textDetail);
TextView textStatus = (TextView) convertView.findViewById(R.id.textStatus);
TextView textPeriode = (TextView) convertView.findViewById(R.id.textPeriode);
Publikasi publikasi = lstPublikasi.get(position);
textNama.setText(publikasi.namaJurnal);
textDetail.setText(publikasi.tipePublikasi);
textStatus.setText(publikasi.status);
textPeriode.setText(publikasi.periode);
return convertView;
}
public void updateList(List < Publikasi > mlstPublikasi) {
lstPublikasi = mlstPublikasi;
notifyDataSetChanged();
}
}
Try this code for showList()
private void showList(){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ArrayList<Publikasi> publikasis=new ArrayList<>();
for(int i=0;i<response.length();i++){
try {
publikasis.add(new Publikasi(response.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
publikasiAdapter = new PublikasiAdapter(publikasis,getApplicationContext());
listView.setAdapter(publikasiAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonArrayRequest);
}
I've a listview which shows values from web service. Its fine when it loads the listview. But when I click on any item to open a new fragment (which shows details of the item) and get back to the same listview, its items doubles everytime. For example, if I have (in original) 5 items in total. Then when I get back from the fragment, the total count will be 10, then 15 and so on. It means the app is adding all items again and again. I searched for the solution and did what were the general solution like adapter.notifyDataSetChanged() but its still gets duplicated. If anyone can show me the problem, I would be grateful.
public class CustomListAdapter extends ArrayAdapter<Model> {
private Context mContext;
int resource;
private ArrayList<Model> mListData = new ArrayList<Model>();
public CustomListAdapter(Context mContext, int resource, ArrayList<Model> mListData) {
super(mContext, resource, mListData);
this.resource = resource;
this.mContext = mContext;
this.mListData = mListData;
}
public void setListData(ArrayList<Model> mListData) {
this.mListData = mListData;
notifyDataSetChanged();
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
holder = new ViewHolder();
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
v = inflater.inflate(resource, parent, false);
holder.custname = (TextView) v.findViewById(R.id.cust_name);
holder.date = (TextView) v.findViewById(R.id.date);
holder.staffname = (TextView) v.findViewById(R.id.staff_name);
holder.time = (TextView) v.findViewById(R.id.time);
holder.service = (TextView) v.findViewById(R.id.service);
holder.refid = (TextView) v.findViewById(R.id.refid);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Model item = mListData.get(position);
holder.custname.setText(item.getCustname());
holder.date.setText(item.getDate());
holder.staffname.setText(item.getStaffname());
holder.time.setText(item.getTime());
holder.service.setText(item.getService());
holder.refid.setText(item.getRefid());
return v;
}
class ViewHolder {
TextView custname, date, staffname, time, service, refid;
}
}
public class ListFrag extends Fragment{
private SwipeMenuListView listView;
private CustomListAdapter adapter;
private CShowProgress cShowProgress;
private SQLiteHandler db;
private String uid, bookingId;
private ArrayList<Model> arrayList = new ArrayList<>();
private static final String BOOKED_LIST = "http://192.168.220.13/android/showbookinglist";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.listfrag, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (SwipeMenuListView)view.findViewById(R.id.list);
db = new SQLiteHandler(getActivity());
cShowProgress = CShowProgress.getInstance();
fetchDetails();
adapter = new CustomListAdapter(getActivity(), R.layout.listitem, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String a = arrayList.get(i).getCustname();
String b = arrayList.get(i).getStaffname();
String c = arrayList.get(i).getService();
String d = arrayList.get(i).getDate();
String e = arrayList.get(i).getTime();
String f = arrayList.get(i).getRefid();
String g = arrayList.get(i).getEmail();
String h = arrayList.get(i).getServprice();
String j = arrayList.get(i).getSpeclprice();
String k = arrayList.get(i).getStatus();
db.addDetails(a, b, c, d, e, f, g, h, j, k);
DetailsView details = new DetailsView();
((Bookings)getActivity()).replaceFragment(details);
}
});
}
private void fetchDetails() {
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, BOOKED_LIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
Model model = new Model();
model.setCustname(obj.getString("customername"));
model.setDate(obj.getString("staffdate"));
model.setStaffname(obj.getString("staffname")+"(Staff)");
model.setTime(obj.getString("stafftime"));
model.setService(obj.getString("servicename"));
model.setRefid(obj.getString("booking_referenceid"));
model.setEmail(obj.getString("customeremail"));
model.setServprice(obj.getString("serviceprice"));
model.setSpeclprice(obj.getString("specialprice"));
model.setStatus(obj.getString("status"));
model.setBookid(obj.getString("bookingid"));
arrayList.add(model);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
try to change it as.. B'coz you are adding the elements in previously created list.. So you have to clear it.
private void fetchDetails() {
if(arrayList!=null )arrayList.clear(); // this line
cShowProgress.showProgress(getActivity());
The thing is that when you get back to the fragment it is recreated and onViewCreated is called again. From there you call again fetchDetails() and then your are adding the whole List for a second time to the adapter. So you can clear the list before fetchDetails() or just if you have to fetch them again.
change your try - catch block of onResponse method by below.
try {
JSONArray jsonArray = new JSONArray(response);
arrayList = new ArrayList<>();
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
Model model = new Model();
model.setCustname(obj.getString("customername"));
model.setDate(obj.getString("staffdate"));
model.setStaffname(obj.getString("staffname")+"(Staff)");
model.setTime(obj.getString("stafftime"));
model.setService(obj.getString("servicename"));
model.setRefid(obj.getString("booking_referenceid"));
model.setEmail(obj.getString("customeremail"));
model.setServprice(obj.getString("serviceprice"));
model.setSpeclprice(obj.getString("specialprice"));
model.setStatus(obj.getString("status"));
model.setBookid(obj.getString("bookingid"));
arrayList.add(model);
}
adapter.notifyDataSetChanged();
This is happening because you are not clearing the arrayList. Due to this every time that you construct the array and the adapter, you are adding the elements into an array that already has elements.
That why you have 5, then 10, then 15 and so on..
Clear the array before adding new elements
arrayList.clear();
Or program another strategy like:
Not populate the array every time you return to the fragment.
Check if he element existe before add it into the array.
I have a fragment for a tab which displays JSON parsed results in GridView. The results are not displayed when scrolled to that tab for first time. But after switching tabs, results are displayed in second visit.
public class StoresFragment extends Fragment {
private ProgressBar loading;
private ArrayList<String> storenamefinal = new ArrayList<String>();
private ArrayList<Integer> imagelinksfinal = new ArrayList<Integer>();
private GridView gridview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.stores_layout,null);
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridview = (GridView) getActivity().findViewById(R.id.grid_stores);
loading = (ProgressBar) getActivity().findViewById(R.id.proStores);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
new getData(getActivity()).execute();
}
}
private class getData extends AsyncTask<Void, Void, Void> {
private Context context;
public getData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
String url = Config1.DATA_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return null;
}
private void showJSON(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
int i = result.length();
Log.i("Result", result.toString());
for (int j = 0; j < i; j++) {
storenamefinal.add(null);
imagelinksfinal.add(null);
}
String temp;
for (int j = 0; j < i; j++) {
JSONObject Data = result.getJSONObject(j);
Log.i("Data", Data.toString());
temp = (Data.getString("mainpriority"));
Log.i("temp", temp.toString());
storenamefinal.set(Integer.parseInt(temp) - 1, Data.getString("storename"));
Log.i("Result Length", storenamefinal.toString());
imagelinksfinal.add(R.drawable.sg1);
}
Log.i("Result Length", storenamefinal.toString());
Toast.makeText(getActivity(), storenamefinal.get(0), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result)
{
loading.setVisibility(View.GONE);
gridview.setVisibility(View.VISIBLE);
if (storenamefinal != null) {
final GridAdapterStores gridadapter = new GridAdapterStores(getActivity(), storenamefinal, imagelinksfinal);
gridview.setAdapter(gridadapter);
}
}
}
}
Adapter.
public class GridAdapterStores extends BaseAdapter {
private Context context;
private ArrayList<String> storename = new ArrayList<String>();
private ArrayList<Integer> imagelinks = new ArrayList<Integer>();
public GridAdapterStores(Context c, ArrayList<String> storename, ArrayList<Integer> imagelinks) {
context = c;
this.imagelinks = imagelinks;
this.storename = storename;
}
#Override
public int getCount() {
return storename.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
if (convertView == null) {
grid = new View(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.grid_stores, parent, false);
} else {
grid = (View) convertView;
}
TextView textViewStoreName = (TextView) grid.findViewById(R.id.store_name);
// ImageView imageViewStoreImage = (ImageView) grid.findViewById(R.id.store_image);
textViewStoreName.setText(storename.get(position));
// Integer x=imagelinks.get(position);
// imageViewStoreImage.setImageResource(x);
return grid;
}
}
And also, everytime tab is switched, gridview gets added, but data is displayed in only one gridview.