I want show 3 fragments in my Activity and load data from json in any fragments! I show websites data into Recyclerview with OkHTTP v3 library.
I want show this datas for offline, my mean is if user turn off data/wifi show this datas for offline. but i do not want use SQLite Database!
Can i use OkHTTP cache? i don't know how to use okhttp cache.
AsyncTask code:
public class freeDataInfo {
private Context mContext;
private String ServerAddress = freeServer_IP.getFreeIP();
public void getFreeDataInfo(Context context) {
mContext = context;
//new getInfo().execute(ServerAddress + "limit=10");
new getInfo().execute(ServerAddress);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels = new ArrayList<>();
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
//infoModels = new ArrayList<>();
// Initiate Progress
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
infoModels.clear();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
//.url(ServerAddress + "limit=10")
.url(ServerAddress)
.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("result");
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("full_description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("date");
String url = postObject.getString("url");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "Post url: " + url);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, url, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
//Stop Progress
if (dialog.isShowing()) {
dialog.dismiss();
}
if (result != null) {
bus.post(new MyEvent("forfragment1", infoModels));
} else {
Toast.makeText(mContext, "اتصال اینترنت خود را بررسی کنید", Toast.LENGTH_LONG).show();
}
}
}
}
Adapter codes:
public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
private List<DataModel> mDateSet;
private Context context;
// Provide a suitable constructor (depends on the kind of dataset)
public free_recycler_adapter(Context context, List<DataModel> dataSet) {
this.context = context;
this.mDateSet = dataSet;
}
// Create new views (invoked by the layout manager)
#Override
public free_recycler_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_card_layout, parent, false);
// create ViewHolder
return new ViewHolder(view);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.free_titleText.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
Glide.with(context)
.load(mDateSet.get(position).getImage())
.placeholder(R.drawable.ic_download_image)
.crossFade()
.into(viewHolder.free_avatarImage);
viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));
viewHolder.free_descText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<DataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<DataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView free_titleText, free_descText;
public ImageView free_avatarImage;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
free_titleText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_title);
free_descText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_content);
free_avatarImage = (ImageView) itemLayoutView.findViewById(R.id.pdf_card_image);
}
}
}
Fragment codes:
public class free_fragment extends Fragment {
private RecyclerView mRecyclerView;
private free_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();
private Context context;
private boolean isDataFetched;
private boolean mIsVisibleToUser;
private View view;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_free_layout, container, false);
context = getContext();
if (mIsVisibleToUser) {
LoadData();
}
///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new free_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
/* if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/
if (event.fragmentTag.equals("forfragment1")) {
mAdapter.add(dataModels);
isDataFetched = true;
mAdapter.notifyDataSetChanged();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
mIsVisibleToUser = isVisibleToUser;
if (isVisibleToUser && !isDataFetched && getContext() != null) {
context = getContext();
LoadData(); //Remove this call from onCreateView
}
}
private void LoadData() {
freeDataInfo dataInfo = new freeDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getFreeDataInfo(context);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
How can i show data for offline without Sqlite DataBase? Thanks all <3
if (isNetworkStatusAvialable(ctx)) {
//Here your normal parsing while network available
SharedPreferences app_preferences1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = app_preferences1.edit();
editor.putString("jsonresponse", "yourjsonresponse");
editor.commit();
} else {
final SharedPreferences app_preferences1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String response= app_preferences1.getString("jsonresponse", "");
try {
JSONObject postObj = new JSONObject(response);
JSONArray postsArray = postObj.optJSONArray("result");
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("full_description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("date");
String url = postObject.getString("url");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "Post url: " + url);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, url, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
if (netInfos.isAvailable())
return true;
}
return false;
}
Here is a good example for how to use JsonWriter
And here is the documentation for JsonWriter.
This should do it for writing into a json file.
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("messages", list);
try {
FileWriter file = new FileWriter("c:\\test.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
And when you want to read this again use this code:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Related
I hope someone out there can help me solve my problem. I have android app that have 3 tabs, i use fragment, first tab is recyclerView list, second tabs is map. the problem is in tabs 1, i need to fetch data with volley to recyclerView on tabs 1, if run fine but i cannot see the data on first app start, but when i change tab and back to tab 1 again it will refresh the data and show the data on recyclerView.
Adapter.java
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Warkop> mWarkop;
private LayoutInflater inflater;
public CustomListAdapterWarkop(Context context, List<Warkop> mWarkop) {
this.context=context;
inflater= LayoutInflater.from(context);
this.mWarkop = mWarkop;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_warkop_row, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder viewHolder = (ItemViewHolder) holder;
Warkop current = mWarkop.get(position);
viewHolder.tvNamaWarkop.setText(current.getNamaWarkop());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage)
.showImageOnLoading(R.drawable.noimage).build();
imageLoader.displayImage(current.getFotoWarkop(), viewHolder.ivFotoWarkop, options);
}
#Override
public int getItemCount() {
return mWarkop.size();
}
}
ItemHolder.java
package com.andylah.warkopedia;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by andylah on 11/3/2017.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public ImageView ivFotoWarkop;
public TextView tvNamaWarkop;
public ItemViewHolder(View itemView) {
super(itemView);
tvNamaWarkop = itemView.findViewById(R.id.nama_warkop);
ivFotoWarkop = itemView.findViewById(R.id.image_warkop);
}
}
Tab 1.java
public class tabSatu extends Fragment {
private static final String TAG = tabDua.class.getSimpleName();
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private boolean isFragmentLoaded = false;
View vTabSatu;
private RecyclerView recyclerView;
public static List<Warkop> warkopList = new ArrayList<Warkop>();
private CustomListAdapterWarkop warkopAdapter;
public tabSatu(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new AsyncFetch().execute();
vTabSatu = inflater.inflate(R.layout.tabsatu_view, container, false);
recyclerView = vTabSatu.findViewById(R.id.warkop_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
Log.d("LOG : ", "onCreatedView Run");
// Inflate the layout for this fragment
return vTabSatu;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
Log.d("LOG : ", "onViewCreated Run");
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded ) {
// Load your data here or do network operations here
isFragmentLoaded = true;
//new AsyncFetch().execute();
}else{
isFragmentLoaded = false;
Log.d("LOG : ", "isFragmentLoaded = false");
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading list warkop ...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL(AppConfig.LOAD_WARKOP);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try{
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if(!error){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
warkop.setNamaWarkop(jsonObject.getString("nama_warkop"));
warkop.setAlamatWrkop(jsonObject.getString("alamat_warkop"));
warkop.setKotaWarkop(jsonObject.getString("kota_warkop"));
warkop.setLatWarkop(Double.parseDouble(jsonObject.getString("lat_warkop")));
warkop.setLangWarkop(Double.parseDouble(jsonObject.getString("long_warkop")));
warkop.setIsWifi(Integer.parseInt(jsonObject.getString("is_wifi")));
warkop.setIsToilet(Integer.parseInt(jsonObject.getString("is_toilet")));
warkop.setIsTv(Integer.parseInt(jsonObject.getString("is_tv")));
warkop.setIsColokan(Integer.parseInt(jsonObject.getString("is_colokan")));
warkop.setIsParkir(Integer.parseInt(jsonObject.getString("is_parkir")));
warkop.setFotoWarkop(jsonObject.getString("foto_warkop"));
warkopList.add(warkop);
}
}else{
String errorMsg = object.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Problem: Even you call notifyDataSetChanged() but there are no data in Adapter.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
}
So you need to set and notify warkopList to Adapter after API call. It will help you.
tabSatu:
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try {
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if (!error) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
...
warkopList.add(warkop);
adapter.setItems(warkopList);
}
}
...
}
CustomListAdapterWarkop: add setItem() method to Adapter
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
public void setItems(List<WarkopList> warkopList) {
mWarkop = warkopList;
notifyDataSetChanged();
}
...
}
I want to retrieve json recycler image gallery data and display in RecyclerView manner, anyone help me
like Instagram click image gallery open in RecyclerView with image name
Currently I am displaying in a grid manner I don't no how to pass from this recycler to another recycler :
ProfilActivity:
public class ProfilActivity extends AppCompatActivity {
private RecyclerView recyclerView;
ArtistAdapterGallary artistAdapterGallary;
ArrayList < DataArtist > data = new ArrayList < > (); //its in progress dialog arraylist to retrieve array data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask < String, String, String > {
ProgressDialog pdLoading = new ProgressDialog(ProfilActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String...params) {
try {
url = new URL("http://exxxxxxxxxxxxxx");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataArtist artistPic = new DataArtist();
artistPic.artistName = json_data.getString("name");
artistPic.artistImage = json_data.getString("profile_image");
data.add(artistPic);
}
// Setup and Handover data to recyclerview
recyclerView = (RecyclerView) findViewById(R.id.profileGride);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 3);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
artistAdapterGallary = new ArtistAdapterGallary(ProfilActivity.this, data);
// recyclerView.setLayoutManager(new LinearLayoutManager(ProfileGrideActivity.this));
recyclerView.setAdapter(artistAdapterGallary);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Custom Adatpter
public class ArtistAdapterGallary extends RecyclerView.Adapter < ArtistAdapterGallary.MyViewHolder > {
private Context context;
private LayoutInflater inflater;
List < DataArtist > data = new ArrayList < > ();
public ArtistAdapterGallary(ProfilActivity context, List < DataArtist > data1) {
this.context = context;
this.data = data1;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gallary_layout, parent, false);
return new ArtistAdapterGallary.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ArtistAdapterGallary.MyViewHolder holder, int position) {
final DataArtist current = data.get(position);
holder.artistname.setText(current.artistName);
Glide.with(context).load(data.get(position).getArtistImage()).into(holder.artistImage);
holder.artistImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Main2Activity.class);
intent.putExtra("link", current.getArtistImage());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView artistImage;
TextView artistname;
private View view;
public MyViewHolder(View itemView) {
super(itemView);
artistImage = (ImageView) itemView.findViewById(R.id.imageGride);
artistname = (TextView) itemView.findViewById(R.id.artistName);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Main2Activity.class);
DataArtist artistData = (DataArtist) view.getTag();
String strUrl = artistData.getArtistImage();
String product1 = artistData.getArtistName();
intent.putExtra("ARTIST_IMG", strUrl);
intent.putExtra("ARTIST_NAME", product1);
// intent.putExtra("Your string key",product1);
context.startActivity(intent);
}
}
}
DataArtist :
public class DataArtist {
public String artistImage;
public String artistName;
public String artistId;
private boolean isSelected = false;
public DataArtist() {
this.artistImage = artistImage;
this.artistName = artistName;
}
public String getArtistId() {
return artistId;
}
public void setArtistId(String artistId) {
this.artistId = artistId;
}
public String getArtistImage() {
return artistImage;
}
public void setArtistImage(String artistImage) {
this.artistImage = artistImage;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getArtistName() {
return artistName;
}
public void setSelected(boolean selected) {
boolean isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
and I want to know how I can call this data into another recycler
I want show 3 fragments in my Activity and load data from json in any fragments! I want show each json data into one fragment, but in my application copy duplicate json data in fragment one !
For example : when running application show 1 post in any fragment but when swipe between tabs copy json data below posts!
myEvent (custom eventBus code) :
public class MyEvent {
public String fragmentTag ;
private List<DataModel> infoModels = new ArrayList();
public MyEvent (String tag,List<DataModel> models){
this.fragmentTag = tag;
this.infoModels = models;
}
public List<DataModel> getInfoModels() {
return infoModels;
}
}
Fragment 1 codes:
public class free_fragment extends Fragment {
private RecyclerView mRecyclerView;
private free_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();
private Context context;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_free_layout, container, false);
context = getContext();
LoadData();
///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new free_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
if (event.fragmentTag.equals("forfragment1")) {
mAdapter.add(dataModels);
mAdapter.notifyDataSetChanged();
}
}
private void LoadData() {
freeDataInfo dataInfo = new freeDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getFreeDataInfo(context);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
Fragment 1 AsyncTask codes:
public class freeDataInfo {
private Context mContext;
private String ServerAddress = freeServer_IP.getFreeIP();
public void getFreeDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "limit=10");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels = new ArrayList<>();
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "limit=10")
.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("result");
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("publishDate");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
//Stop Progress
if (dialog.isShowing()) {
dialog.dismiss();
}
if (result != null) {
bus.post(new MyEvent("forfragment1", infoModels));
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
Other fragments codes such as fragment one code!
How to fix this problem and not copy (duplicate) json datas below posts??! Thanks all <3
First You Clear ArrayList Than Add Data In ArrayList in Every Call of AsyncTask
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
infoModels.clear();
}
I have 2 recycler view adapter, the first is working perfect , the second one I am having the below error,
E/RecyclerView: No adapter attached; skipping layout
is it possible this is the mistake ?
if (mListener != null)
mListener.myMethod(Listitem);
both have different adapter
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView mRecyclerView1;
private RecyclerView.Adapter mAdapter1;
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false));
RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
mAdapter = new MyAdapter(result,Search.this);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter );
}
});
handler.execute();
//second recycler
mRecyclerView1 = (RecyclerView) findViewById(R.id.my_recycler_view1);
mRecyclerView1.setHasFixedSize(true);
mRecyclerView1.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false));
RecyclerOkHttpHandler1 handler1 = new RecyclerOkHttpHandler1( this, new RecyclerOkHttpHandler1.MyInterface() {
#Override
public void myMethod(ArrayList result1) {
mAdapter1 = new MyAdapter1(result1,Search.this);
mAdapter1.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter1);
}
});
handler1.execute();
this is RecyclerOkHttpHandler
public class RecyclerOkHttpHandler extends AsyncTask<String, Void, String> {
private Context mContext;
private MyInterface mListener;
public RecyclerOkHttpHandler (Context context, MyInterface mListener){
mContext = context;
this.mListener = mListener;
}
public interface MyInterface {
public void myMethod(ArrayList result);
}
private final String Fetch_URL = "http://je.com/getdata.php";
// ArrayList<Listitem> Listitem;
ArrayList<CategoryList> Listitem;
int resulta;
OkHttpClient httpClient = new OkHttpClient();
ListView list;
String myJSON;
JSONArray peoples = null;
InputStream inputStream = null;
#Override
protected String doInBackground(String... params) {
Log.d("okhttp Fetch_URL", Fetch_URL);
Request.Builder builder = new Request.Builder();
builder.url(Fetch_URL);
Request request = builder.build();
String result = null;
try {
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
inputStream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
resulta = 1; //"Success
// return response.body().bytes();
} catch (Exception e) {
Toast.makeText(mContext, "Connection failed, check your connection",
Toast.LENGTH_LONG).show();
e.printStackTrace(); }
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
if( resulta ==1){
myJSON=result;
Log.e("result",result);
showList();
}
else{
Log.e("d","there is an error on postexecute in okhhttphandler.java");
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println("Length:"+peoples.length());
int J_length=peoples.length()-1;
//JSONObject maxj = peoples.getJSONObject(peoples.length() - 1);
// max of arrray
jsonObj= peoples.getJSONObject(J_length);
String j_id= jsonObj.getString("id");
int _id = Integer.parseInt(j_id);
// if (_id < d_id) {
System.out.println("Getting json result ");
Listitem = new ArrayList<CategoryList>();
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
// String id ="2";
String id = c.getString("id");
String url = c.getString("url");
int intid = 0;
try {
intid = Integer.parseInt(id.toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
// DatabaseHandler db = new DatabaseHandler(mContext);
Log.d("Insert: ", "Inserting ..");
//db.addObjects(new Objects(intid, "Image1", url, "IMAGES", "Leb Funny"));
Listitem.add(new CategoryList(id, url));
System.out.println(Listitem);
}
//}
if (mListener != null)
mListener.myMethod(Listitem);
// GridViewAdapter adapter = new GridViewAdapter(mContext, R.layout.grid_item_layout, Listitem);
// gridView.setAdapter(gridAdapter);
// adapter.notifyDataSetChanged();
// list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
RecyclerOkHttpHandler1 class
public class RecyclerOkHttpHandler1 extends AsyncTask<String, Void, String> {
private Context mContext;
private MyInterface mListener;
public RecyclerOkHttpHandler1(Context context, MyInterface mListener){
mContext = context;
this.mListener = mListener;
}
public interface MyInterface {
public void myMethod(ArrayList result);
}
private final String Fetch_URL = "http://je.com/getdata.php";
// ArrayList<Listitem> Listitem;
ArrayList<CategoryList> Listitem;
int resulta;
OkHttpClient httpClient = new OkHttpClient();
ListView list;
String myJSON;
JSONArray peoples = null;
InputStream inputStream = null;
#Override
protected String doInBackground(String... params) {
Log.d("okhttp Fetch_URL", Fetch_URL);
Request.Builder builder = new Request.Builder();
builder.url(Fetch_URL);
Request request = builder.build();
String result = null;
try {
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
inputStream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
resulta = 1; //"Success
// return response.body().bytes();
} catch (Exception e) {
Toast.makeText(mContext, "Connection failed, check your connection",
Toast.LENGTH_LONG).show();
e.printStackTrace(); }
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
if( resulta ==1){
myJSON=result;
Log.e("result",result);
showList();
}
else{
Log.e("d","there is an error on postexecute in okhhttphandler.java");
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println("Length:"+peoples.length());
int J_length=peoples.length()-1;
//JSONObject maxj = peoples.getJSONObject(peoples.length() - 1);
// max of arrray
jsonObj= peoples.getJSONObject(J_length);
String j_id= jsonObj.getString("id");
int _id = Integer.parseInt(j_id);
System.out.println(j_id);
//max of
// if (_id < d_id) {
System.out.println("Getting json result ");
Listitem = new ArrayList<CategoryList>();
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
// String id ="2";
String id = c.getString("id");
String url = c.getString("url");
int intid = 0;
try {
intid = Integer.parseInt(id.toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
// DatabaseHandler db = new DatabaseHandler(mContext);
Log.d("Insert: ", "Inserting ..");
//db.addObjects(new Objects(intid, "Image1", url, "IMAGES", "Leb Funny"));
Listitem.add(new CategoryList(id, url));
System.out.println(Listitem);
}
//}
if (mListener != null)
mListener.myMethod(Listitem);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
my adapter
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<CategoryList> mDataset;
Context mContext;
public class ImageViewHolder extends RecyclerView.ViewHolder {
//ImageView mImage;
public TextView txtHeader;
public TextView txtFooter;
public ImageView image;
public ImageViewHolder(View itemView) {
super (itemView);
txtHeader = (TextView) itemView.findViewById(R.id.firstLine);
txtFooter = (TextView) itemView.findViewById(R.id.secondLine);
image = (ImageView) itemView.findViewById(R.id.imagecateg);
}
}
public void add(int position, CategoryList item) { //changed from string to listitem
mDataset.add(position, item);
notifyItemInserted(position);
}
public void remove(String item) {
int position = mDataset.indexOf(item);
mDataset.remove(position);
notifyItemRemoved(position);
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<CategoryList> myDataset, Context context) {
mDataset = myDataset;
mContext = context;
}
// Create new views (invoked by the layout manager)
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_search, parent, false);
// set the view's size, margins, paddings and layout parameters
ImageViewHolder vh = new ImageViewHolder(v);
return vh;
}
private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;
#Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder TextViewHolder, int position) {
ImageViewHolder viewHolder = (ImageViewHolder) TextViewHolder;
// viewHolder.txtHeader.setText(...)
final CategoryList item;
// final String name = mDataset.get(position);
item = mDataset.get(position);
// viewHolder.txtHeader.setText(mDataset.get(position));
// this to be removed when added text
// viewHolder.txtHeader.setText(mDataset.get(position).getUrl());
Picasso.with(mContext)
.load(item.getUrl())
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(viewHolder.image);
/* viewHolder.txtFooter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(item);
}
});*/
// viewHolder.txtFooter.setText("Footer: " + mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
my adapter 1
public class MyAdapter1 extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<CategoryList> mDataset;
Context mContext;
public class ImageViewHolder extends RecyclerView.ViewHolder {
//ImageView mImage;
public TextView txtHeader;
public TextView txtFooter;
public ImageView image;
public ImageViewHolder(View itemView) {
super (itemView);
txtHeader = (TextView) itemView.findViewById(R.id.firstLine);
txtFooter = (TextView) itemView.findViewById(R.id.secondLine);
image = (ImageView) itemView.findViewById(R.id.imagecateg);
}
}
public void add(int position, CategoryList item) { //changed from string to listitem
mDataset.add(position, item);
notifyItemInserted(position);
}
public void remove(String item) {
int position = mDataset.indexOf(item);
mDataset.remove(position);
notifyItemRemoved(position);
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter1(ArrayList<CategoryList> myDataset, Context context) {
mDataset = myDataset;
mContext = context;
}
// Create new views (invoked by the layout manager)
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_search, parent, false);
// set the view's size, margins, paddings and layout parameters
ImageViewHolder vh = new ImageViewHolder(v);
return vh;
}
private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;
#Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder TextViewHolder, int position) {
ImageViewHolder viewHolder = (ImageViewHolder) TextViewHolder;
// viewHolder.txtHeader.setText(...)
final CategoryList item;
// final String name = mDataset.get(position);
item = mDataset.get(position);
// viewHolder.txtHeader.setText(mDataset.get(position));
// this to be removed when added text
// viewHolder.txtHeader.setText(mDataset.get(position).getUrl());
Picasso.with(mContext)
.load(item.getUrl())
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(viewHolder.image);
/* viewHolder.txtFooter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(item);
}
});*/
// viewHolder.txtFooter.setText("Footer: " + mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
Here you are setting adapter for mRecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false));
RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
mAdapter = new MyAdapter(result,Search.this);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter );
}
});
handler.execute();
And here again you are setting adapter for same mRecyclerView, not for mRecyclerView1
//second recycler
mRecyclerView1 = (RecyclerView) findViewById(R.id.my_recycler_view1);
mRecyclerView1.setHasFixedSize(true);
mRecyclerView1.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false));
RecyclerOkHttpHandler1 handler1 = new RecyclerOkHttpHandler1( this, new RecyclerOkHttpHandler1.MyInterface() {
#Override
public void myMethod(ArrayList result1) {
mAdapter1 = new MyAdapter1(result1,Search.this);
mAdapter1.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter1);
}
});
handler1.execute();
This is the reason for the issue (E/RecyclerView: No adapter attached; skipping layout).
I have Custom Adapter class, in which on button click we make Asynchronous call to server. So in the onPostExecute() method i want to delete particular Row on which button is clicked. Here is My Adapter class
public class CartAdapter extends BaseAdapter {
private List<Products> cartList;
private LayoutInflater inflater;
Context context;
public static final String URLL ="http://192.168.1.3/wordpress/upmeapi/class-woocommerce.php?function=remove_cart_api";
RequestObject requestObject;
public CartAdapter(Context ctx,List<Products> list){
this.context = ctx;
this.cartList = list;
}
#Override
public int getCount() {
return cartList.size();
}
#Override
public Object getItem(int position) {
return cartList.get(position);
}
#Override
public long getItemId(int position) {
Products c = cartList.get(position);
long id = c.getProductId();
return id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
CartHolder holder = null;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.cartview_helper,parent,false);
holder = new CartHolder(row);
row.setTag(holder);
}
else {
holder =(CartHolder)row.getTag();
}
Products c = cartList.get(position);
Picasso.Builder builder = new Picasso.Builder(context);
Picasso picasso = builder.build();
picasso.with(context).cancelRequest(holder.myImage);
picasso.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100,100)
.into(holder.myImage);
/* Picasso.with(context)
.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100, 75)
.into(holder.myImage);*/
holder.title.setText(c.getTitle());
String stringdouble= Double.toString(c.getPrice());
holder.price.setText(stringdouble);
holder.quantity.setText(String.valueOf(c.getProductQuantity()));
holder.totalPrice.setText(c.getTotalPrice());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long productId = getItemId(position);
//holder.button.setTag(position);
try {
ProductHelper productHelper = new ProductHelper();
productHelper.setProductId(productId);
ObjectMapper objectMapper = new ObjectMapper();
String req = objectMapper.writeValueAsString(productHelper);
requestObject = ExceptionRequest.generateRequest(req);
requestObject.setUrl(URLL);
new RemovefromList().execute(requestObject);
}catch (Exception e) {
e.printStackTrace();
}
}
});
return row;
}
static class CartHolder {
ImageView myImage;
TextView title;
//TextView descriptions;
TextView price;
TextView quantity;
TextView totalPrice;
Button button;
public CartHolder(View v){
myImage =(ImageView)v.findViewById(R.id.imageView2);
title =(TextView)v.findViewById(R.id.carttitle);
// descriptions =(TextView)v.findViewById(R.id.product_description);
price =(TextView)v.findViewById(R.id.cart_price);
quantity =(TextView)v.findViewById(R.id.item_quantity);
totalPrice =(TextView)v.findViewById(R.id.sub_total);
button =(Button)v.findViewById(R.id.remove_cart);
}
}
private class RemovefromList extends AsyncTask<RequestObject, Void,JSONObject> {
#Override
protected JSONObject doInBackground(RequestObject... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// RequestObject requestObject = new RequestObject();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(arg0[0], ServiceHandler.POST);
JSONObject products = new JSONObject();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
products = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return products;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result!=null){
String status = result.getString("status");
// cartList.remove();
// notifyDataSetChanged();
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
}
inside onPostExecute() if i get status success this means on server side that particular product has been removed.but At our side we still see that products.
so i want to remove that row and also want to update count of cartitem.
Any help would be Appreciated in advanced.
please check this
send position in Async task constructor when button is clicked
private List<Products> cartList;
private LayoutInflater inflater;
Context context;
public static final String URLL ="http://192.168.1.3/wordpress/upmeapi/class-woocommerce.php?function=remove_cart_api";
RequestObject requestObject;
public CartAdapter(Context ctx,List<Products> list){
this.context = ctx;
this.cartList = list;
}
#Override
public int getCount() {
return cartList.size();
}
#Override
public Object getItem(int position) {
return cartList.get(position);
}
#Override
public long getItemId(int position) {
Products c = cartList.get(position);
long id = c.getProductId();
return id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
CartHolder holder = null;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.cartview_helper,parent,false);
holder = new CartHolder(row);
row.setTag(holder);
}
else {
holder =(CartHolder)row.getTag();
}
Products c = cartList.get(position);
Picasso.Builder builder = new Picasso.Builder(context);
Picasso picasso = builder.build();
picasso.with(context).cancelRequest(holder.myImage);
picasso.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100,100)
.into(holder.myImage);
/* Picasso.with(context)
.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100, 75)
.into(holder.myImage);*/
holder.title.setText(c.getTitle());
String stringdouble= Double.toString(c.getPrice());
holder.price.setText(stringdouble);
holder.quantity.setText(String.valueOf(c.getProductQuantity()));
holder.totalPrice.setText(c.getTotalPrice());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long productId = getItemId(position);
//holder.button.setTag(position);
try {
ProductHelper productHelper = new ProductHelper();
productHelper.setProductId(productId);
ObjectMapper objectMapper = new ObjectMapper();
String req = objectMapper.writeValueAsString(productHelper);
requestObject = ExceptionRequest.generateRequest(req);
requestObject.setUrl(URLL);
new RemovefromList(position).execute(requestObject);
}catch (Exception e) {
e.printStackTrace();
}
}
});
return row;
}
static class CartHolder {
ImageView myImage;
TextView title;
//TextView descriptions;
TextView price;
TextView quantity;
TextView totalPrice;
Button button;
public CartHolder(View v){
myImage =(ImageView)v.findViewById(R.id.imageView2);
title =(TextView)v.findViewById(R.id.carttitle);
// descriptions =(TextView)v.findViewById(R.id.product_description);
price =(TextView)v.findViewById(R.id.cart_price);
quantity =(TextView)v.findViewById(R.id.item_quantity);
totalPrice =(TextView)v.findViewById(R.id.sub_total);
button =(Button)v.findViewById(R.id.remove_cart);
}
}
private class RemovefromList extends AsyncTask<RequestObject, Void,JSONObject> {
int selectedPos;
public RemovefromList(int pos){
selectedPos = pos;
}
#Override
protected JSONObject doInBackground(RequestObject... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// RequestObject requestObject = new RequestObject();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(arg0[0], ServiceHandler.POST);
JSONObject products = new JSONObject();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
products = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return products;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result!=null){
String status = result.getString("status");
cartList.remove(selectedPos);
notifyDataSetChanged();
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
}
You send the position also in asynctask parameter
new RemovefromList().execute(requestObject,position);
private class RemovefromList extends AsyncTask<String, Void,JSONObject> {
public RemovefromList(RequestObject obj, int pos) {
super();
RequestObject robj = obj;
int position= pos;
}
#Override
protected JSONObject doInBackground(String... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// RequestObject requestObject = new RequestObject();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(robj, ServiceHandler.POST);
JSONObject products = new JSONObject();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
products = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return products;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result!=null){
String status = result.getString("status");
cartList.remove(position);
notifyDataSetChanged();
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
Remove that particular item from ur List list and then call adapter.notifyDataSetChanged();
// For Delete from list
new AsynceTaskDeleteData().execute(position);
listData.remove(position);
// In your AsyncTask
private class AsynceTaskDeleteData extends AsyncTask<Integer, String, String> {
int position;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Integer... arg0) {
// Creating service handler class instance
position = arg0[0];
// Now pass position for delete
}
#Override
protected void onPostExecute(String result) {
notifyDataSetChanged();
}
}