I have problem with recycler view and fragments? - java

I write this code but not show me anything and in logcat have no error
and I have three classes for this code Adapter, recyclertouchlistener and fragments code...
my code in below
this code for fragment :
public class VerticalRecyclerFragment extends Fragment {
RecyclerView rcVertical;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalRecyclerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical_recycler,
container, false);
showProduct();
rcVertical = view.findViewById(R.id.rcVertical);
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getActivity(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager(getActivity()));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
return view;
}
public void showProduct() {
final ProgressDialog loader = ProgressDialog.show(getActivity(),
"Get products...", "please wait",
false, false);
StringRequest request = new StringRequest(Request.Method.POST,
Config.getProductsWebApi,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loader.dismiss();
productsArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loader.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}}
and i write this code for Adapter in a single class :
public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {
ArrayList<Products> ProductsList;
Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}}
RecyclerTouchListener :
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView,
final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}}
Please if you know whats the problem help me to debug it...
thank you

You need to notifyDataSetChanged() when you get the response.
Make the adapter as a class field
public class VerticalRecyclerFragment extends Fragment {
RecyclerView rcVertical;
static ArrayList<Products> productsArrayList = new ArrayList<>();
Adapter adapter; // <<< Change here
change the initialization (and every call of the adapter to the class field)
adapter = new Adapter(productsArrayList, getContext()); // <<< Change here
rcVertical.setLayoutManager(new LinearLayoutManager(getActivity()));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
And finally call notifyDataSetChanged() when you get the response
public void showProduct() {
final ProgressDialog loader = ProgressDialog.show(getActivity(),
"Get products...", "please wait",
false, false);
StringRequest request = new StringRequest(Request.Method.POST,
Config.getProductsWebApi,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loader.dismiss();
productsArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
adapter.notifyDataSetChanged(); // <<< Change here
} catch (JSONException e) {
e.printStackTrace();
}
}
}...
...
}
UPDATE:
add attach the adapter to the RecyclerView when you receive the data
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
Adapter adapter = new Adapter(productsArrayList, getContext()); // <<< Change here
rcVertical.setAdapter(adapter); // <<< Change here

Related

Fetching image using Picasso

Here in the given below code, I am trying to display in the image in recyclerview in the imageview after fetching it using picasso, it won't show error or app won't crash either but image won't be displayed, it either shows:
"I/Choreographer: Skipped 30 frames! The application may be doing too much work on its main thread."
Or
W/RecyclerView: No adapter attached; skipping layout
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
LayoutInflater inflater;
List<Lists> lst;
private ItemClickListsner mItemListener;
public Adapter(Context ctx, List<Lists> lst, ItemClickListsner itemClickListsner) {
this.inflater = LayoutInflater.from(ctx);
this.lst = lst;
this.mItemListener = itemClickListsner;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// final Lists temp = lst.get(position);
holder.id.setText(lst.get(position).getId());
holder.name.setText(lst.get(position).getName());
holder.prc.setText(lst.get(position).getPrc());
holder.add.setText(lst.get(position).getAddress());
holder.description.setText(lst.get(position).getDes());
holder.park.setText(lst.get(position).getGarage());
holder.net.setText(lst.get(position).getNet());
holder.email.setText(lst.get(position).getMail());
holder.number.setText(lst.get(position).getPnumber());
holder.post.setText(lst.get(position).getTle());
holder.date.setText(lst.get(position).getCrt());
Picasso.with(inflater.getContext())
.load(lst.get(position).getMimage())
.placeholder(R.drawable.bed)
.fit()
.into(holder.ImgView);
holder.itemView.setOnClickListener(view -> {
mItemListener.onItemClick(lst.get(position));
});
}
#Override
public int getItemCount() {
return lst.size();
}
public interface ItemClickListsner{
void onItemClick(Lists lst);
}
public void filterList(ArrayList<Lists> filteredList) {
lst = filteredList;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView id, name, add, prc, description, park, net, post,email,number,date;
ImageView ImgView;
// CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.textViewRecy1);
name = itemView.findViewById(R.id.textViewRecy2);
prc = itemView.findViewById(R.id.textViewRecy3);
add = itemView.findViewById((R.id.textViewRecy4));
description = itemView.findViewById(R.id.textViewRecy5);
park = itemView.findViewById(R.id.textViewRecy6);
net = itemView.findViewById(R.id.textViewRecy7);
post = itemView.findViewById(R.id.textViewRecy8);
email = itemView.findViewById(R.id.textViewRecy9);
number = itemView.findViewById(R.id.textViewRecy10);
date = itemView.findViewById(R.id.textViewRecy11);
ImgView = itemView.findViewById(R.id.ImageRecy);
}
}
}
Activity Code
private void extractList() {
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
//Log.d("tags", "error: " + jsonObject);
Lists lists = new Lists();
lists.setName(jsonObject.getString("title").toString());
lists.setAddress(jsonObject.getString("location").toString());
lists.setPrc(jsonObject.getString("price").toString());
lists.setDes(jsonObject.getString("description").toString());
lists.setGarage(jsonObject.getString("parking").toString());
lists.setNet(jsonObject.getString("internet").toString());
lists.setMail(jsonObject.getString("email").toString());
lists.setPnumber(jsonObject.getString("phone_number").toString());
lists.setTle(jsonObject.getString("poster").toString());
lists.setCrt(jsonObject.getString("created").toString());
lists.setMimage(jsonObject.getString("photo1").toString());
String p = jsonObject.getString("photo1").toString();
Log.e("kk","msg"+p);
lst.add(lists);
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new Adapter(getApplicationContext(), lst, new Adapter.ItemClickListsner() {
#Override
public void onItemClick(Lists lst) {
// startActivity(new Intent(HomeActivity.this,roomsDesc.class));
Intent intent = new Intent(HomeActivity.this, roomsDesc.class);
intent.putExtra("title",lst.getName());
intent.putExtra("price",lst.getPrc());
intent.putExtra("location",lst.getAddress());
intent.putExtra("description",lst.getDes());
intent.putExtra("parking",lst.getGarage());
intent.putExtra("internet",lst.getNet());
intent.putExtra("email",lst.getMail());
intent.putExtra("phone_number",lst.getPnumber());
intent.putExtra("poster",lst.getTle());
intent.putExtra("created",lst.getCrt());
intent.putExtra("photo1",lst.getMimage());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
HomeActivity.this.startActivity(intent);
}
});
recyclerView.setAdapter(adapter);
}

How to change text in Fragment (outside recyclerVIew) from within RecyclerView viewHolder onClick

My cart
This is what i need.
Total value need to be updated when one item removed.
I managed to remove the item and get the total value as json respose in adapter viewholder . don't know how to set the update the text in Fragment.
this is my cart fragment
Cart.java
public class Cart extends Fragment {
public Cart() {
// Required empty public constructor
}
Context context;
Activity activity;
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://192.168.0.106/slbros/index.php/get/cart?p_d_id=12&lan=en";
String Total_URL = "http://192.168.0.106/slbros/index.php/get/total?p_d_id=12";
String JSON_CDID = "cart_dtl_id";
String JSON_IMG_URL = "img_url";
String JSON_QTY = "qty";
String JSON_NAME = "name";
String JSON_UNIT = "unit";
String JSON_PRICE = "price";
String JSON_P_ID = "product_id";
JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_cart, container, false);
TextView total_tv = (TextView)v.findViewById(R.id.total_payment_value);
//recycler view
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.rv_cart_list);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar2);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Cart");
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "some error....", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue = Volley.newRequestQueue(getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1));
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImg_url(json.getString(JSON_IMG_URL));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setPrice(json.getInt(JSON_PRICE));
GetDataAdapter2.setProduct_id(json.getInt(JSON_P_ID));
GetDataAdapter2.setCart_dtl_id(json.getInt(JSON_CDID));
GetDataAdapter2.setProduct_qty(json.getInt(JSON_QTY));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapterCart(GetDataAdapter1, getContext());
recyclerView.setAdapter(recyclerViewadapter);
}}
this is my adapter
RecyclerViewAdapterCart.java
public class RecyclerViewAdapterCart extends RecyclerView.Adapter<RecyclerViewAdapterCart.ViewHolder> {
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
String baseURL = "http://192.168.0.106/slbros/index.php/";
Context context;
Activity activity;
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapterCart(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImg_url(),
ImageLoader.getImageListener(
Viewholder.product_image_view,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.product_image_view.setImageUrl(getDataAdapter1.getImg_url(), imageLoader1);
Viewholder.product_name_TextView.setText(getDataAdapter1.getName()+" - "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_price_qty_TextView.setText(getDataAdapter1.getPrice()+".00 Rs X "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_t_price_TextView.setText(String.valueOf(getDataAdapter1.getProduct_qty()*getDataAdapter1.getPrice())+".00 Rs");
Viewholder.product_id_TextView.setText(String.valueOf(getDataAdapter1.getProduct_id()));
Viewholder.cart_dtl_id_TextView.setText(String.valueOf(getDataAdapter1.getCart_dtl_id()));
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public NetworkImageView product_image_view;
public TextView product_name_TextView;
public TextView product_price_qty_TextView;
public TextView product_t_price_TextView;
public TextView product_id_TextView;
public TextView cart_dtl_id_TextView;
public Button p_cancel_btn;
public ViewHolder(View itemView) {
super(itemView);
product_image_view = (NetworkImageView) itemView.findViewById(R.id.item_image1);
product_name_TextView = (TextView) itemView.findViewById(R.id.product_name);
product_price_qty_TextView = (TextView) itemView.findViewById(R.id.p_qty_price);
product_t_price_TextView = (TextView) itemView.findViewById(R.id.p_t__price);
product_id_TextView = (TextView) itemView.findViewById(R.id.product_id_tv);
cart_dtl_id_TextView = (TextView) itemView.findViewById(R.id.cart_dtl_id_tv);
p_cancel_btn = (Button)itemView.findViewById(R.id.p_cancel_btn);
// set item view
p_cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(final View v) {
String str = product_name_TextView.getText().toString();
//Toast.makeText(v.getContext(), str, Toast.LENGTH_SHORT).show();
String cart_dtl_id = cart_dtl_id_TextView.getText().toString();
String url = baseURL + "delete/select?cart_dtl_id="+cart_dtl_id;
jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
Toast.makeText(v.getContext(), "response -- " + response, Toast.LENGTH_LONG).show();
// here, I have to change the total TextView in Fragment
// Total_TextView.setText("1000rs")
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(v.getContext(), "error", Toast.LENGTH_LONG).show();
}
}
);
requestQueue = Volley.newRequestQueue(v.getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000,0,1));
requestQueue.add(jsonArrayRequest);
getDataAdapter.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(),getDataAdapter.size());
}
}}
Thanks in Advance
add to ReyclerView.
private ItemsChangedListener itemsChangedListener;
public interface ItemsChangedListener {
void onItemsChanged(int sum);
}
public void setItemsChangedListener(ItemsChangedListener listener) {
this.itemsChangedListener = listener;
}
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
// Calc here the Value if you can.
if(listener != null) listener.onItemsChanged(sum);
}
Fragment
public class Cart extends Fragment implements ItemsChangedListener
recyclerView.setItemsChangedListener(this);
#override
public void onItemsChanged(int sum) {
//Update TextView
}

Converting Facebook post ID from String to int

I am making a news feed where I retrieve Facebook posts from a specific Facebook page. I retrieve those posts with help of the Facebook Graph API. I have a FeedItem which has an ID (int). The ID is also used to check which item is at the current position (Recyclerview).
The problem is that Facebook gives the posts a String ID. I have no idea how I can possibly convert this so that it will work with my application.
My Adapter:
public class FeedListAdapter extends RecyclerView.Adapter<FeedListAdapter.ViewHolder> {
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private List<FeedItem> mFeedItems;
private Context mContext;
public FeedListAdapter(List<FeedItem> pFeedItems, Context pContext) {
this.mFeedItems = pFeedItems;
this.mContext = pContext;
}
/* Create methods for further adapter use.*/
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
View feedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.feed_item, parent, false);
return new ViewHolder(feedView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.populateRow(getFeedItem(position));
}
#Override
public long getItemId(int position) {
return mFeedItems.get(position).getId();
}
#Override
public int getItemCount() {
return mFeedItems.size();
}
private FeedItem getFeedItem(int position) {
return mFeedItems.get(position);
}
class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
private ImageView mProfilePic;
private TextView mName;
private TextView mTimestamp;
private TextView mTxtStatusMsg;
private FeedImageView mFeedImage;
//initialize the variables
ViewHolder(View view) {
super(view);
mProfilePic = (ImageView) view.findViewById(R.id.feedProfilePic);
mName = (TextView) view.findViewById(R.id.feedName);
mTimestamp = (TextView) view.findViewById(R.id.feedTimestamp);
mTxtStatusMsg = (TextView) view.findViewById(R.id.feedStatusMessage);
mFeedImage = (FeedImageView) view.findViewById(R.id.feedImage);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
private void populateRow(FeedItem pFeedItem) {
getProfilePic(pFeedItem);
mName.setText(pFeedItem.getName());
mTimestamp.setText(pFeedItem.getTimeStamp());
mTxtStatusMsg.setText(pFeedItem.getStatus());
getStatusImg(pFeedItem);
}
private void getProfilePic(FeedItem pFeedItem) {
imageLoader.get(pFeedItem.getProfilePic(), new ImageListener() {
#Override
public void onResponse(ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
// load image into imageview
mProfilePic.setImageBitmap(response.getBitmap());
}
}
#Override
public void onErrorResponse(final VolleyError pVolleyError) {
}
});
}
private void getStatusImg(FeedItem pFeedItem) {
if (pFeedItem.getImage() != null) {
mFeedImage.setImageUrl(pFeedItem.getImage(), imageLoader);
mFeedImage.setVisibility(View.VISIBLE);
mFeedImage
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
mFeedImage.setVisibility(View.GONE);
}
}
}
My FeedFragment:
public class FeedFragment extends android.support.v4.app.Fragment {
private static final String TAG = FeedFragment.class.getSimpleName();
private FeedListAdapter mListAdapter;
private List<FeedItem> mFeedItems;
private RecyclerView mRecyclerView;
private String FACEBOOKURL = "**URL OF MY FB-POSTDATA**";
// newInstance constructor for creating fragment with arguments
public static FeedFragment newInstance() {
FeedFragment fragment = new FeedFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout resource file
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_feed, container, false);
initRecyclerView(view);
initCache();
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
private void initRecyclerView(View pView) {
mRecyclerView = (RecyclerView) pView.findViewById(R.id.fragment_feed_recyclerview);
LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mRecyclerView.setNestedScrollingEnabled(true);
}
mFeedItems = new ArrayList<>();
mListAdapter = new FeedListAdapter(mFeedItems, getActivity());
mRecyclerView.setAdapter(mListAdapter);
}
private void initCache() {
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(FACEBOOKURL);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
FACEBOOKURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(Integer.parseInt(feedObj.getString("id")));
item.setName("name of page");
// Image might be null sometimes
String image = feedObj.isNull("full_picture") ? null : feedObj
.getString("full_picture");
item.setImage(image);
// Status message might be null sometimes
String status = feedObj.isNull("message") ? null : feedObj
.getString("message");
item.setStatus(status);
item.setProfilePic("**profile picture url**");
item.setTimeStamp(feedObj.getString("created_time"));
mFeedItems.add(item);
}
// notify data changes to list adapter
mListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
} }
As I said; I have no idea how to handle this and I figured someone here would maybe have an idea on how to convert this, so that I can use the String that the graph api gives me, and use it as an integer.
If the id is all numeric, you should be able to do this: int id = Integer.valueOf(facebookId)
If you have an undescore you can try this:
public int getIdFromString(String postId) {
String finalId;
while (postId.indexOf("_") > 0) {
finalId = postId.substring(0, postId.indexOf("_"));
postId = finalId.concat(postId.substring(postId.indexOf("_") + 1));
}
return Integer.valueOf(postId);
}
If the value is numeric and you want an integer object, do
Integer id = Integer.valueOf(facebookId);
If you want the primitive type int, then do
int id = Integer.parseInt(facebookId);
or
int id = Integer.valueOf(facebookId);

Tabs refresh when baseadapter button is clicked

i am new to the concept of the fragments i am using the tab layout where one of the tab consists of the list view in that i had used the base adapter to describe the list row where i want to refresh the second tab when button from the first tab is clicked.i had tried the fragment transaction method but its not doing the work that i want please help here
this is the baseadapter
public class Second_adapter extends BaseAdapter {
Context context;
Activity activity;
TextView basename, SubItemprice, itemdesc, SubItemdesc;
LayoutInflater inflater;
ImageView order;
private List<JSONParser> items;
String itembasename, itemde, subtmsub, subitempri;
SharedPreferences.Editor loginPrefsEditor;
public Second_adapter(Context context, List<JSONParser> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_clicked, viewGroup, false);
basename = (TextView) view.findViewById(R.id.basename);
SubItemprice = (TextView) view.findViewById(R.id.SubItemprice);
itemdesc = (TextView) view.findViewById(R.id.itemdesc);
SubItemdesc = (TextView) view.findViewById(R.id.SubItemdesc);
order = (ImageView) view.findViewById(R.id.order);
final JSONParser setdata = items.get(i);
basename.setText(setdata.getBaseName());
itemdesc.setText(setdata.getItemdesc());
SubItemdesc.setText(setdata.getSubItemdesc());
SubItemprice.setText(setdata.getSubItemprice());
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itembasename = setdata.getBaseName();
itemde = setdata.getItemdesc();
subtmsub = setdata.getSubItemdesc();
subitempri = setdata.getSubItemprice();
Session userloggedin = new Session(context);
if (userloggedin.isLoggedIn()) {
addcart();
Cart cart = new Cart();
FragmentManager fragmentManager = activity.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.cartfragment, cart);
Toast.makeText(context, "LoggedIn"+ itembasename+itemde+subtmsub+subitempri, Toast.LENGTH_SHORT).show( );
}else{
Toast.makeText(context,"Please Login", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void addcart() {
SharedPreferences customerid=context.getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String addcarturl = "http://standardtakeaway.co.uk/json/cart_ p rocess.p h p?userid = "+customid+" & Item=" + itembasename+itemde+subtmsub+" & Itemcount=1&price="+subitempri;
Log.d("Cart",addcarturl);
JsonArrayRequest cartreq=new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0; i<response.length();i++){
try {
JSONObject cartobj=response.getJSONObject(i);
// String count=cartobj.getString("count");
// loginPrefsEditor.putString("Badge",count);
// loginPrefsEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(cartreq);
}
}
This is the Another tab where i want it to refresh
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
#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);
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);
}
});
cartdata();
return cartfrag;
}
void cartdata() {
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 {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
}
JSONObject subobj=response.getJSONObject("details");
String subtext=subobj.getString("subtotal");
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;
}
}

Json parse returning null arrays in Android

I'm trying to parse a json and return its values in an array, then I want to show it in a listview, the log shows me the result that I want, but it is not showing in my cellphone, I'm missing something that I don't know.
The function that make the SyncTask:
public class SincronizarTask {
private Activity ctx;
public SincronizarTask(Activity applicationContext) {
this.ctx = applicationContext;
}
public void inicia(){
this.syncClientes();
}
private void syncClientes() {
ClientRest mClientesRest = new ClientRest(ctx);
mClientesRest.getClientes(new ClientRest.ClientesRestListener() {
public void clientesReceived(List<ClientesModel> clientes) {
for (int i = 0; i < clientes.size(); i++) {
System.out.println(clientes.get(i).getNome());
}
}
});
}
}
ClienteActivity:
public class ClienteActivity extends SherlockFragment {
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cliente, container, false);
try {
ClienteViewAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item);
ListView lv = (ListView) view.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TextView clienteId = (TextView) view.findViewById(R.id.clienteId);
TextView clienteNome = (TextView) view.findViewById(R.id.clienteNome);
TextView clienteTipoPessoa = (TextView) view.findViewById(R.id.clienteTipo);
Intent intent = new Intent(getActivity(), ContatosView.class);
//intent.putExtra("id_cliente", clienteId.getText()); // envia o id do cliente para a tela de detalhes
intent.putExtra("nome", clienteNome.getText());
intent.putExtra("tipo_pessoa", clienteTipoPessoa.getText());
startActivity(intent);
}
});
lv.setAdapter(ad);
} catch (Exception e) {
new AlertDialog.Builder(getActivity()).setTitle("Erro").setMessage(e.getMessage()).setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).show();
}
return view;
}
ClienteViewAdapter:
public class ClienteViewAdapter extends ArrayAdapter<ClientesModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(FragmentActivity context, int resource) {
super(context, resource);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ClientesModel cliente = getItem(position);
view = inflater.inflate(resourceId, parent, false);
//TextView tvId = (TextView) view.findViewById(R.id.txtTitle);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
//tvId.setText(String.valueOf(cliente.ge()));
tvNome.setText(cliente.getNome());
tvTipo.setText(cliente.getTipo_pessoa());
return view;
}
}
ClientRest:
JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
List<ClientesModel> clientes = null;
try {
clientes = parseJSON(response);
pDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
listener.clientesReceived(clientes);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (pDialog.isShowing()) {
pDialog.hide();
}
error.printStackTrace();
}
}
)
mRequestQueue.add(mJsonObjectRequest);
}
private List<ClientesModel> parseJSON(JSONObject json) throws JSONException {
try {
JSONArray dados = json.getJSONArray("dados");
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
ClientesModel mClientesModel = new ClientesModel();
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
/* cadastra os dados necessários no objeto no modelo */
mClientesModel.setId(item.optInt("id"));
mClientesModel.setNome(item.optString("nome"));
mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
mClientesModel.setCpf(item.optString("cpf"));
mClientesModel.setCnpj(item.optString("cnpj"));
JSONArray contatos = item.getJSONArray("contatos");
for (int j = 0; j < contatos.length(); j++) {
JSONObject data = contatos.getJSONObject(j);
mClientesContatoModel.setNome(data.optString("nome"));
mClientesContatoModel.setCargo(data.optString("cargo"));
}
arrNews.add(mClientesModel);
arrContatos.add(mClientesContatoModel);
}
} catch (Exception e) {
e.printStackTrace();
}
return arrNews;
}
}

Categories