I'm making an app that loads the images from server in gridview. I'm using Volley for Http request, glide to download image. I can load the image when app is install and open first time, but when new images are added, it cannot load new images.
URLS
there was 7 urls when app is installed, so it loaded 7 images. but after refresh or reopen app it cannot load 8th image
{"result":[{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/Desert.jpg"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/Jellyfish.jpg"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/child.png"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/clamber-512.png"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/image:52.jpg"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/image:52.jpg"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/Temp20181016_051043.jpg"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/My Children20182917_022900.jpg"},{"url":"http://smilestechno.000webhostapp.com/ImagesUpload/MyChildren1412414122.jpg"}]}
Images fregment where gridview is displayed
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_images, container, false);
View v = inflater.inflate(R.layout.fragment_images, container, false);
FloatingActionButton btnCamera = (FloatingActionButton) v.findViewById(R.id.btnCamera);
FloatingActionButton btnFolder = (FloatingActionButton) v.findViewById(R.id.btnFolder);
refreshMainGrid = (SwipeRefreshLayout) v.findViewById(R.id.refreshManGrid);
imgGrid = (GridView) v.findViewById(R.id.imgGrid);
getData();
imgGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent = new Intent(getContext(), SingleImage.class);
intent = intent.putExtra("id", (ImageObject) myGridAdapter.getItem(position));
startActivity(intent);
}
});
refreshMainGrid.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshData();
}
});
return v;
}
private void getData(){
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, IMAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.optJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
ArrayList<ImageObject> imageObjects = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonitem = jsonArray.optJSONObject(i);
imageObjects.add(new ImageObject(jsonitem));
}
myGridAdapter = new MyGridAdapter(getContext(), imageObjects);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
imgGrid.setAdapter(myGridAdapter);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
private void refreshData(){
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, IMAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.optJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
ArrayList<ImageObject> imageObjects = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonitem = jsonArray.optJSONObject(i);
imageObjects.add(new ImageObject(jsonitem));
}
myGridAdapter = new MyGridAdapter(getContext(), imageObjects);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
imgGrid.setAdapter(myGridAdapter);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
refreshMainGrid.setRefreshing(false);
}
MyGridAdapter
public class MyGridAdapter extends BaseAdapter {
private Context context;
private ArrayList<ImageObject> imageObjects;
private LayoutInflater mLayoutInflate;
public MyGridAdapter(Context context, ArrayList<ImageObject> imageObjects) {
this.context = context;
this.imageObjects = imageObjects;
this.mLayoutInflate = LayoutInflater.from(context);
}
public int getCount() {
if (imageObjects != null) return imageObjects.size();
return 0;
}
#Override
public Object getItem(int position) {
if (imageObjects != null && imageObjects.size() > position)
return imageObjects.get(position);
return null;
}
#Override
public long getItemId(int position) {
if (imageObjects != null && imageObjects.size() > position)
return imageObjects.get(position).getId();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mLayoutInflate.inflate(R.layout.imageitem, parent,
false);
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ImageObject imageObject = (ImageObject) getItem(position);
if (imageObject != null) {
Glide
.with(context)
.load(imageObject.getImageUrl())
.centerCrop()
.crossFade()
.into(viewHolder.imageView);
}
return convertView;
}
}
ImageObject
public class ImageObject implements Parcelable{
private int id;
private String imageUrl;
public ImageObject(Parcel in){
id = in.readInt();
imageUrl = in.readString();
}
public ImageObject(JSONObject jsonObject){
if(jsonObject == null) return;
this.id = jsonObject.optInt("id");
this.imageUrl = jsonObject.optString("url");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(imageUrl);
}
public static final ImageObject.Creator<ImageObject> CREATOR = new ImageObject.Creator<ImageObject>(){
#Override
public ImageObject createFromParcel(Parcel in) {
return new ImageObject(in);
}
#Override
public ImageObject[] newArray(int size) {
return new ImageObject[size];
}
};
}
Even after refresh or reopen app it does not load 8th image.
one more isuue is that it loading image from bottom not from top item.
Images xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.smiles.mychildren.Images"
android:orientation="vertical">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshManGrid"
android:layout_marginTop="110dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<GridView
android:id="#+id/imgGrid"
android:numColumns="auto_fit"
android:columnWidth="135dp"
android:layout_marginTop="110dp"
android:clipToPadding="false"
android:padding="0dp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="none"
android:stackFromBottom="false">
</GridView>
</android.support.v4.widget.SwipeRefreshLayout>
I found the solution.
The problem was with Volley cache.
stringRequest.setShouldCache(false);
By this we can stop saving cache.
Related
I have a problem, when i swipe to refresh the data, the first swipe is ok but after that every swipe reload and add the same data over and over again, by the end i have a list with same items over and over... I'm using a loader. I tried to clear before but i don't understand what's wrong with my code, if someone could explain it to me. Thank You.
Here my code :
public static final String EXTRA_URL = "imageUrl";
public static final String EXTRA_APKNAME = "apkname";
public static final String EXTRA_APKSIZE = "apksize";
public static final String EXTRA_APKFILE = "apkfile";
private RecyclerView mRecyclerView;
private MyAdapter mExampleAdapter;
private ArrayList<one_item> mExampleList;
private RequestQueue mRequestQueue;
private SwipeRefreshLayout swipeRefreshLayout;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("APK VIP CHINA");
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
swipeRefreshLayout = findViewById(R.id.refreshlayout);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void parseJSON() {
String url = "http://apkvip.net/json2.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("ten");
String creatorsize = hit.getString("apk_size");
String creatorfile = hit.getString("link_apk");
String imageUrl = hit.getString("link_img");
mExampleList.add(new one_item(imageUrl, creatorName, creatorsize, creatorfile));
}
mExampleAdapter = new MyAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener(MainActivity.this);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, activity_detail.class);
one_item clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getmImageUrl());
detailIntent.putExtra(EXTRA_APKNAME, clickedItem.getMapkname());
detailIntent.putExtra(EXTRA_APKSIZE, clickedItem.getMapksize());
detailIntent.putExtra(EXTRA_APKFILE, clickedItem.getMapkfile());
startActivity(detailIntent);
}}
My adapter:
private ArrayList<one_item> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public MyAdapter(Context context, ArrayList<one_item> exampleList) {
mContext = context;
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.one_item, parent, false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
one_item currentItem = mExampleList.get(position);
String imageUrl = currentItem.getmImageUrl();
String apkname = currentItem.getMapkname();
String apksize = currentItem.getMapksize();
String apkfile = currentItem.getMapkfile();
holder.mTextViewname.setText(apkname);
holder.mTextViewsize.setText(apksize);
holder.mTextViewfile.setText(apkfile);
Picasso.get().load(imageUrl).fit().centerInside().into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextViewname, mTextViewsize, mTextViewfile;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image);
mTextViewname = itemView.findViewById(R.id.name);
mTextViewsize = itemView.findViewById(R.id.size);
mTextViewfile = itemView.findViewById(R.id.file);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});}}}
my activitymain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Recommended Apps"
android:textColor="#000"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginBottom="10dp"
/>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/refreshlayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:padding="5dp" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Just use mExampleList.clear() at the first line of your parseJSON() function
and then you'll be able to add the "updated" items.
In addition I'd suggest that you move swipeRefreshLayout.setRefreshing(false) to the end of Volley onResponse and onError() implementation -
Right now you're telling the swipeRefreshLayout to stop refreshing before the request(that happens asynchronously) has finished
You are initializing your adapter every time you do a swipe.
Change this constructor of MyAdapter code.
public MyAdapter(Context context, ArrayList<one_item> exampleList) {
mContext = context;
mExampleList = exampleList;
}
to,
public MyAdapter(Context context) {
mContext = context;
}
public setExampleList(ArrayList<one_item> exampleList){
mExampleList = exampleList;
}
Now change your onCreate function to.
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("APK VIP CHINA");
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
swipeRefreshLayout = findViewById(R.id.refreshlayout);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
//Changed Code
mExampleAdapter = new MyAdapter(MainActivity.this);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener(MainActivity.this);
parseJSON();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void parseJSON() {
String url = "http://apkvip.net/json2.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("ten");
String creatorsize = hit.getString("apk_size");
String creatorfile = hit.getString("link_apk");
String imageUrl = hit.getString("link_img");
mExampleList.add(new one_item(imageUrl, creatorName, creatorsize, creatorfile));
}
//Changed Code
mExampleAdapter.setExampleList(mExampleList);
mExampleAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
I have added a comment of the code block where I have made the changes.
Feel free to comment in case you have any queries.
I fetch the data from my Server with Volley and put the data inside a GridView.
Now when I use swipeToRefresh, it should load the new/changed data. For this I tried everything but nothing worked.
First my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
List<getter_setter> list = new ArrayList<>();
grid_adapter grid_adapter;
GridView gridView;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = findViewById(R.id.swipeRefresh);
getData();
gridView = findViewById(R.id.gridView);
grid_adapter = new grid_adapter(getApplicationContext(),list);
gridView.setAdapter(grid_adapter);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
grid_adapter.update(list);
swipeRefreshLayout.setRefreshing(false);
}
});
}
public void getData(){
final String url = "http://*.**.***.***/";
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("userdata");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String NAME = jsonObject.getString("NAME");
String BILD = jsonObject.getString("VORSCHAUBILD");
getter_setter getter_setter = new getter_setter(NAME,"",BILD);
list.add(getter_setter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
And the BaseAdapter
public class grid_adapter extends BaseAdapter{
Context context;
List<getter_setter> list;
public grid_adapter(Context context, List<getter_setter> list) {
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public void update(List<getter_setter> listUpdate){
this.list.addAll(listUpdate);
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View gridView = view;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = inflater.inflate(R.layout.grid_design,null);
}
final getter_setter getter = list.get(i);
TextView name = gridView.findViewById(R.id.NAME);
final ImageView bild = gridView.findViewById(R.id.bild);
name.setText(getter.getNAME());
Picasso.with(context).load(getter.getVORSCHAUBILD()).into(bild);
return gridView;
}
}
Check The Updated Listener
Explanation-:
Since You Are Passing Reference Of Your List Into RecyclerView Hence Updating List In The Activity Will Update The List In Adapter Automatically
No Need To Call update Method
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
list.clear(); // Clean The List Before Adding Updated Data
grid_adapter.notifyDataSetChanged();
getData();
grid_adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
});
i have a series of items in recyclerview .i want to set on click listener and open a description page of specific item and set data from json url. i have already made an adapter for description screen and a bean class. i dont know how to set adapter on layout. is it possible to set an adapter on linear layout to show static content from json url?
My code is :
Description activity
private class MakeRequestForGetDescription extends AsyncTask<String, Void, String> {
ProgressDialog Pdialog;
private String response;
private MakeServiceClass makeServiceClass = new MakeServiceClass();
#Override
protected void onPreExecute() {
Pdialog = new ProgressDialog(getActivity());
Pdialog.setMessage("Please Wait..");
Pdialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> parms = new HashMap<String, String>();
response = makeServiceClass.makeServiceConnectionGet(ConstUrl.DESCRP_URLS);
Log.e("response ads", response);
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(response);
if (Pdialog != null) {
Pdialog.dismiss();
}
if (response != null) {
try {
JSONObject mainObject = new JSONObject(response);
if (mainObject.has("status")) {
String Status = mainObject.getString("status");
String img_url = "";
if (Status.equalsIgnoreCase("200")) {
if (mainObject.has("img_url")) {
img_url = mainObject.getString("img_url");
Log.e("img_url", img_url);
}
if (mainObject.has("details")) {
JSONArray datArray = mainObject.getJSONArray("details");
descriptionBeanArrayList = new ArrayList<>();
if (datArray.length() > 0) {
for (int i = 0; i < datArray.length(); i++) {
DescriptionBean descriptionBean = new DescriptionBean();
JSONObject internalDataObject = datArray.getJSONObject(i);
if (internalDataObject.has("id")) {
descriptionBean.setId(internalDataObject.getString("id"));
}
if (internalDataObject.has("title_en")) {
descriptionBean.setTitle_en(internalDataObject.getString("title_en"));
}
if (internalDataObject.has("ad_description_en")) {
descriptionBean.setAd_description_en(internalDataObject.getString("ad_description_en"));
}
if (internalDataObject.has("price")) {
descriptionBean.setPrice(internalDataObject.getString("price"));
}
if (internalDataObject.has("km_driven")) {
descriptionBean.setKm_driven(internalDataObject.getString("km_driven"));
}
if (internalDataObject.has("image_file")) {
descriptionBean.setImage_file("http://" + img_url + internalDataObject.getString("image_file"));
}
descriptionBeanArrayList.add(descriptionBean);
}
setAdapterForDescription();
}
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void setAdapterForDescription() {
DescriptionAdapter adapter = new DescriptionAdapter(getActivity(), descriptionBeanArrayList);
}
}
Description Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.fragment_description, parent,false);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvRate = (TextView) convertView.findViewById(R.id.tvRate);
viewHolder.tvMiles = (TextView) convertView.findViewById(R.id.tvMiles);
viewHolder.et_description = (EditText) convertView.findViewById(R.id.et_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//setdata
viewHolder.tvTitle.setText(descriptionBeanArrayList.get(position).getTitle_en());
viewHolder.tvRate.setText(descriptionBeanArrayList.get(position).getPrice());
viewHolder.tvMiles.setText(descriptionBeanArrayList.get(position).getKm_driven());
viewHolder.et_description.setText(descriptionBeanArrayList.get(position).getAd_description_en());
Log.e("s", descriptionBeanArrayList.get(position).getImage_file());
//Glide.with(mContext).load("www.apnikheti.com/upload/buysell/idea99A4.jpg").into(viewHolder.iv_picofproduct);
Picasso.with(mContext).load(descriptionBeanArrayList.get(position).getImage_file()).into(viewHolder.iv_picofproduct, new Callback() {
#Override
public void onSuccess() {
Log.e("s", "sucess");
}
#Override
public void onError() {
Log.e("s", "failed");
}
});
Picasso.with(mContext).setLoggingEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView tvTitle,tvRate,tvMiles;
private EditText et_description;
public ImageView iv_picofproduct;
}
}
This is my code which is used to retrieve data from url (Json Data) and load it into a recyclerview using adapter and passing the same values to another activity.
MyActivity
public class Video_List extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//private GridLayoutManager layoutManager;
private List<Video_Details> videodetails;
public static final String VideoID = "v_id";
public static final String ID = "id";
public static final String Title = "title";
public static final String Thumb = "thumb";
public static final String url = "http://115.115.122.10/paul/api/videos.php?start=1&count=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__list);
getdata();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
//layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
videodetails = new ArrayList<>();
}
private void getdata(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("count",response.toString());
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Log.d("infoz","777"+error.getMessage());
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
try {
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
Video_Details video = new Video_Details();
if (json.has(VideoID)) {
Log.d("has values", json.getString(VideoID));
}
video.setId(json.getString(ID));
video.setV_id(json.getString(VideoID));
video.setTitle(json.getString(Title));
video.setThumb(json.getString(VideoID));
videodetails.add(video);
if (json.has(VideoID))
{
Log.d("Video",VideoID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new DataAdapter(videodetails, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MyAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}
when I conduct onRefresh, my recyclerView adds on another copy to my current recyclerView instead of refreshing it, by looking at my code below does anyone know what the problem is?I have tried everything but nothing seems to work?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//send our volley JSON Request
//Initialize VolleySingleton
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JSONArrayRequest();
}
private void JSONArrayRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs=parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ToastTest.t(getActivity(), error.toString());
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String courseId = currentQuestions.getString("courseId");
String studentId = currentQuestions.getString("studentId");
data.append(text + "\n" + points + "\n" + courseId + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_dashboard,container,false);
mRecyclerView=(RecyclerView)view.findViewById(R.id.fragment_dashboard);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapterDashBoard=new AdapterDashBoard(getActivity());
mRecyclerView.setAdapter(mAdapterDashBoard);
mPullToRefreshView = (PullToRefreshView)view.findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
#Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
#Override
public void run() {
mPullToRefreshView.setRefreshing(false);
JSONArrayRequest();
}
}, REFRESH_DELAY);
}
});
return view;
}
}
public class AdapterDashBoard extends RecyclerView.Adapter<AdapterDashBoard.ViewDashboard>{
private LayoutInflater mLayoutInflater;
private ArrayList<Blogs> listblogs=new ArrayList<>();
public AdapterDashBoard(Context context){
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<Blogs> listBlogs){
this.listblogs=listBlogs;
notifyItemRangeChanged(0,listBlogs.size());
}
#Override
public ViewDashboard onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mLayoutInflater.inflate(R.layout.customizejson,parent,false);
ViewDashboard viewholder=new ViewDashboard(view);
return viewholder;
}
#Override
public void onBindViewHolder(ViewDashboard holder, int position) {
Blogs currentBlog=listblogs.get(position);
holder.questionText.setText(currentBlog.getMtext().toString());
holder.points.setText(currentBlog.getPoints().toString());
holder.id.setText(currentBlog.getId().toString());
}
#Override
public int getItemCount() {
return listblogs.size();
}
static class ViewDashboard extends RecyclerView.ViewHolder{
private ImageView thumbnail;
private TextView questionText;
private TextView points;
private TextView id;
public ViewDashboard (View itemView){
super(itemView);
//thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
questionText=(TextView)itemView.findViewById(R.id.questionText);
points=(TextView)itemView.findViewById(R.id.points);
id=(TextView)itemView.findViewById(R.id.ID);
}
}
}
You need to clear your listblogs list before adding new items. This is why you get duplicated values.
Also you're already adding new items to listblogs in parseJSONResponse() method, so there is no need for listblogs=parseJSONResponse(response); in onResponse() method, while its the same list.
Change your onResponse() method to:
#Override
public void onResponse(JSONArray response) {
listblogs.clear(); // here you clear the old data
parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}
I have five tabs they are 1.home 2.menu 3.cart 4.account 5.more.Here cart tab consist of list view which is having the remove button in it,when i click on that remove button it must refresh the fragment itself so that it can load new data from the Json
MainActivity.class
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Session cartsession=new Session(getApplicationContext());
if (cartsession.isLoggedIn()){
if (position==2){
((Cart) pageAdapter.getItem(position)).cartdata();
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
}
TabAdapter.class
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Cart.Java
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
SharedPreferences loginPreferences;
SharedPreferences.Editor loginPrefsEditor;
TextView cartstatus,cartempty;
LinearLayout linearlay;
RelativeLayout cartvisible;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartstatus = (TextView) cartfrag.findViewById(R.id.cartstatus);
cartempty = (TextView) cartfrag.findViewById(R.id.cartempty);
linearlay = (LinearLayout) cartfrag.findViewById(R.id.linearlay);
cartvisible = (RelativeLayout) cartfrag.findViewById(R.id.cartvisible);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged = new Session(getActivity());
if (cartlogged.isLoggedIn()) {
cartitems.clear();
cartdata();
} else {
cartstatus.setText("Please Login");
}
return cartfrag;
}
void cartdata() {
cartitems.clear();
SharedPreferences customerid = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid = customerid.getString("customerid", "");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("empty")) {
cartstatus.setVisibility(View.GONE);
cartempty.setText("Your Cart is Empty");
} else {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
linearlay.setVisibility(View.VISIBLE);
cartvisible.setVisibility(View.GONE);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
JSONObject subobj = response.getJSONObject("details");
String subtext = subobj.getString("subtotal");
loginPrefsEditor.putString("Price", subtext);
loginPrefsEditor.commit();
subtotal.setText(subtext);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
}
CartAdapter.class
public class CartAdapter extends BaseAdapter {
Context context;
TextView quantity, basenamecart, cartprice;
ImageButton delete;
private List<JSONParser> cartitems;
LayoutInflater inflater;
String removequantity, removeitemprice,removebasename;
public CartAdapter(Context context, List<JSONParser> cartitems) {
this.context = context;
this.cartitems = cartitems;
}
#Override
public int getCount() {
return cartitems.size();
}
#Override
public Object getItem(int position) {
return cartitems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart();
}
});
}
return convertView;
}
private void removecart(){
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
}
You need to remove the concerned object from the list cartitems and then call the notifyDataSetChanged() method to notify the any dependent views to refresh itself.
Documentation here
Also, this is not the correct way to implement a BaseAdapter and handle changes in it. Maybe this will help : http://androidadapternotifiydatasetchanged.blogspot.in/
Also, try using the new RecyclerView in order to implement such things. It is available in the support library and definitely a good way to display collections and also makes it easy to add remove items with default animations too. Please read through it. A starting point http://developer.android.com/training/material/lists-cards.html
see added line and updated line.
add make sure only remove item from list if removed successfully from server.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
final int pos =position; // added line
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart(pos); //updated line
}
});
}
return convertView;
}
public void updateCartitems(List<JSONParser> newCartitems) {
cartitems.clear();
cartitems.addAll(newCartitems);
this.notifyDataSetChanged();
}
private void removecart(int pos){ // updated line
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
cartitems.remove(pos); //added line
updateCartitems(cartitems);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}