JSON parser app freezes on running - android

I am trying to create an app that parses data from a JSON parser and populates the recyclerview items with the data fetch from the JSON but whenever I run it it just freezes at loading and shows no error except adapter not attached skipping layout. I am stuck at a dead end as I am not able to get any further. How can I fix this what is the problem with the code .
MainActivity
public class MainActivity extends AppCompatActivity {
CollapsingToolbarLayout collapsingToolbarLayout;
ImageView image;
TextView personName;
TextView personProf;
RecyclerView rv;
private List<Person> personList;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
ImageView images;
RecyclerViewHeader header;
ImageView iv;
public String strurl;
URL url;
URI uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
personName= (TextView)findViewById(R.id.textView);
personProf=(TextView)findViewById(R.id.textView2);
images= (ImageView)findViewById(R.id.imageView);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("Capsule");
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
//setPalette();
strurl = "http://www.humanfox.com/capsule/assets/img/jawed_headshot.jpg";
Typeface face2 = Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Regular.ttf");
Typeface face4= Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Bold.ttf");
image = (ImageView) findViewById(R.id.image);
Picasso.with(this)
.load("http://d152j5tfobgaot.cloudfront.net/wp-content/uploads/2013/06/Javed-Habib_11.jpg")
.into(image);
//header = (RecyclerViewHeader) findViewById(R.id.header);
//header.attachTo(rv,true);
rv =(RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
personList= new ArrayList<>();
getData();
}
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(COnfig.DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
Person per = new Person();
JSONObject json = null;
try {
json = array.getJSONObject(i);
per.setImageUrl(json.getString(COnfig.TAG_IMAGE_URL));
per.setName(json.getString(COnfig.TAG_NAME));
per.setPassion(json.getString(COnfig.TAG_PROFESSION));
} catch (JSONException e) {
e.printStackTrace();
}
personList.add(per);
}
adapter = new RVAdapter(personList, this);
rv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
}
Recycler view Adapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private ImageLoader imageLoader;
Context context;
private List<Person> persons;
RVAdapter(List<Person> persons,Context context){
this.persons = persons;
this.context = context;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(persons.get(i).getImageUrl(), ImageLoader.getImageListener(personViewHolder.personPhoto, R.drawable.ic_launcher, android.R.drawable.ic_dialog_alert));
personViewHolder.personName.setText(persons.get(i).getName());
personViewHolder.personProf.setText(persons.get(i).getPassion());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return persons.size();
}
public static class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
CardView cv;
TextView personName;
TextView personProf;
ImageView personPhoto;
Context context;
PersonViewHolder(final View itemView) {
super(itemView);
context = itemView.getContext();
itemView.setClickable(true);
itemView.setOnClickListener(this);
cv = (CardView) itemView.findViewById(R.id.cv);
personName = (TextView) itemView.findViewById(R.id.textView);
personProf = (TextView) itemView.findViewById(R.id.textView2);
personPhoto=(ImageView) itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View view) {
final Intent intent;
int position =getAdapterPosition();
switch(position){
case 0:
context.startActivity(new Intent(context,caps1.class));
}
}
}
}
Custom Volley Request
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}

Make sure you have implemented send request and parse json on background thread not in Main thread. Otherwise, it will freeze because of your main thread can do one task and should do UI update not all tasks together.

Related

how can update date from adapter to recyclerView?

when I send new data or update the info, how can to change my recycle view?
I have used a dapter.notifyDataSetChanged(); , but it's not working...
I tried more method, but it all cannot change my recycler view
in my code
recyclerView = view.findViewById(R.id.recyclerCoin);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
listCoinDiamondModel = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getActivity());
getData();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
private void sendGift(String postUserID) {
final String postUserIDD = postUserID;
final String GiftAmount = this.GiftAmount.getText().toString().trim();
final String flag = "1";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_GIFTCOIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Log.d("FID", fid);
params.put("fid", fid);
params.put("GiftAmount", GiftAmount);
params.put("flag", flag);
params.put("postUserID", postUserIDD);
params.put("uid", getID);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private JsonArrayRequest getDataFromServer(int requestCount) {
//Initializing ProgressBar
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Load...");
progressDialog.dismiss();
final String GROUP_LIST = "https://example.com/aaa.php?flag=1&fid="+ getActivity().getIntent().getStringExtra("fid") +"&page="+requestCount;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GROUP_LIST,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "No More gift Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
requestQueue.add(getDataFromServer(requestCount));
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the newFeedModel object
final CoinDiamondModel coinDiamondModel = new CoinDiamondModel();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
String TAG_Coin = "Coin";
String TAG_Diamond = "Diamond";
String TAG_UserName = "UserName";
String TAG_UserPhoto = "UserPhoto";
String TAG_UserID = "UserID";
//Log.d("NAME111", json.getString(json.getString(TAG_UserName)));
coinDiamondModel.setCoin(json.getString(TAG_Coin));
coinDiamondModel.setDiamond(json.getString(TAG_Diamond));
coinDiamondModel.setGiftFromUserName(json.getString(TAG_UserName));
coinDiamondModel.setGiftFromUserPhoto(json.getString(TAG_UserPhoto));
coinDiamondModel.setGiftFromUserID(json.getString(TAG_UserID));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the newFeedModel object to the list
listCoinDiamondModel.add(coinDiamondModel);
//adapter.addTheCoinData(coinDiamondModel);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
who knows what's happen and how can solve this?
could you told me how can I do, please?
adapter all code
public class CoinAdapter extends RecyclerView.Adapter<CoinAdapter.ViewHolder> {
private ImageLoader imageLoader;
private List<CoinDiamondModel> newcoinDiamondLists;
private RequestManager glide;
private Context context;
SessionManager sessionManager;
private String getID,memail;
public CoinAdapter(List<CoinDiamondModel> newcoinDiamondLists, Context context) {
this.newcoinDiamondLists = newcoinDiamondLists;
this.glide = Glide.with(context);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.coinlist, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
sessionManager = new SessionManager(getApplicationContext());
sessionManager.checkLogin();
HashMap<String, String> user = sessionManager.getUserDetail();
getID = user.get(sessionManager.USERID);
memail = user.get(sessionManager.EMAIL);
//String gid = getIntent.getStringExtra("xxx");
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
CoinDiamondModel newCoinDiamondModel = newcoinDiamondLists.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
holder.userName.setText(newCoinDiamondModel.getGiftFromUserName());
holder.userID.setText(newCoinDiamondModel.getGiftFromUserID());
holder.coinCount.setText(" x "+newCoinDiamondModel.getCoin());
glide.load(newCoinDiamondModel.getGiftFromUserPhoto()).into(holder.userPhoto);
}
#Override
public int getItemCount() {
return newcoinDiamondLists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView userPhoto;
TextView userName,userID,coinCount;
ImageView coinImg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
userPhoto = (CircleImageView) itemView.findViewById(R.id.userPhoto);
userName = (TextView) itemView.findViewById(R.id.userName);
coinCount = (TextView) itemView.findViewById(R.id.coinCount);
userID = (TextView) itemView.findViewById(R.id.userID);
coinImg = (ImageView) itemView.findViewById(R.id.coinImg);
}
}
public void addTheCoinData(CoinDiamondModel coinDiamondModel){
if(coinDiamondModel!=null){
newcoinDiamondLists.add(coinDiamondModel);
notifyDataSetChanged();
}else {
throw new IllegalArgumentException("無資料!");
}
}
}
you can again set the adapter to recycler view after the response of the server
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
}
solution 2:
in your adapter write a function to update you list
and call function in activity
add this function to the adapter
public void updateList(List<CoinDiamondModel> list){
newcoinDiamondLists = list;
notifyDataSetChanged();
}
and call a function updateList of when you need an update recyclerview
The RecyclerView initialization and notifyDataSetChanged() is used properly. As your question is not clear enough about the Adapter implementation of the RecyclerView, I can give you several suggestions to check.
In RecyclerView.Adapter check if getItemCount() method is properly overriden with returning the list length (not 0) like below:
#Override
public int getItemCount() {
return listdata.length;
}
In RecyclerView.Adapter check if onCreateViewHolder method is properly overriden with proper xml layout like below:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.coin_xml_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
In RecyclerView.Adapter check if RecyclerView.ViewHolder class is properly extended
and linked the UI elements from the xml with the adapter like below:
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView coinTextView;
public ViewHolder(View itemView) {
super(itemView);
this.coinTextView = (TextView) itemView.findViewById(R.id.coinTextView);
}
}
In RecyclerView.Adapter check if onBindViewHolder method is properly overridden and updated the list component UI properly like below:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyListData myListData = listdata[position];
holder.cointTextView.setText(listdata[position].getCoin());
}
Debug with a breakpoint and check if the listCoinDiamondModel.add(coinDiamondModel) is calling or not and coinDiamondModel object is not empty.
The RecyclerView is placed properly in the activity xml, like the RecyclerView is Visible, has a decent size to show list elements. As an example:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
you can update your adapter list manually like this:(write this function in your adapter)
public void updateCoinAdapterList(ArrayList<listCoinDiamondModel> recyclerItemsList) {
this.recyclerItemsList = recyclerItemsList;
this.notifyDataSetChanged();
}
you must set your adapter global variable and initialize it in OnCreate or OnResume, and call
adapter.updateCoinAdapterList(listCoinDiamondModel);
when your list changed

error when i display my data in recycler view :RecyclerView: No adapter attached; skipping layout

I'm traying to get data from my mysql database and display them in a list view but the probleme is that the list view show only one attribut and for the others i have an error:RecyclerView: No adapter attached; skipping layout
this is my adapter :
public class DerpAdapter extends RecyclerView.Adapter<DerpAdapter.DerpHolder>{
private List<ListItem> ListData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback{
void onItemClick(int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback){
this.itemClickCallback = itemClickCallback;
}
public DerpAdapter(List<ListItem> listData, Context c){
this.inflater = LayoutInflater.from(c);
this.ListData = listData;
}
#Override
public DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row,parent,false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
ListItem item = ListData.get(position);
holder.title.setText(item.getTitle());
holder.subtitle.setText(item.getSubtitle());
holder.gaga.setText(item.getGaga());
}
#Override
public int getItemCount() {
return ListData.size();
}
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView title;
private TextView subtitle;
private TextView gaga;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.lbl_item_text);
subtitle = (TextView) itemView.findViewById(R.id.lbl_item_sub_title);
gaga = (TextView) itemView.findViewById(R.id.gaga);
}
#Override
public void onClick(View view) {
/* if(view.getId() == R.id.cont_item_root){
}else{
}*/
}
}
this is my list item:
public class ListItem {
private String title;
private String subtitle;
private String gaga;
public String getGaga() {
return gaga;
}
public void setGaga(String gaga) {
this.gaga = gaga;
}
public ListItem(String title, String subtitle, String gaga) {
this.title = title;
this.subtitle = subtitle;
this.gaga = gaga;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getSubtitle() {
return subtitle;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
and finally this is my mainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DerpAdapter adapter;
private final String url_Data = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
List<ListItem> data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.drawarlist);
//Layout Manager: GridLayoutManager or StaggerdeGridLayoutManager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
loadData();
}
public void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_Data,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("soucat");
data = new ArrayList<>();
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(o.getString("soucat"),"hello","fefe");
data.add(item);
}
adapter = new DerpAdapter(data,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
First, your initial setting of the adapter variable is commented out:
//adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
This will always set the adapter to null, you need to change it to this:
adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
Also, I don't see a call to start the Volley RequestQueue, make sure you are calling requestQueue.start(); before adding the stringRequest.
Then verify that that code for setting the adapter is being executed. You may always be hitting the ErrorListener which never sets the adapter.
You are trying to set null reference adapter to the RecyclerView, firstly you initialize adapter then set into the RecyclerView.
#Bobbake4 this is the code:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DerpAdapter adapter;
private final String url_Data = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
List<ListItem> data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.drawarlist);
//Layout Manager: GridLayoutManager or StaggerdeGridLayoutManager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
loadData();
}
public void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_Data,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("soucat");
data = new ArrayList<>();
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(o.getString("soucat"),"hello","fefe");
data.add(item);
}
adapter = new DerpAdapter(data,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.start();
requestQueue.add(stringRequest);
}

how to set on click listener on recyclerview and open a static page and get content from json url

i have a series of items in recyclerview .i want to set on click listener and open a description page of specific item and set data from json url. i have already made an adapter for description screen and a bean class. i dont know how to set adapter on layout. is it possible to set an adapter on linear layout to show static content from json url?
My code is :
Description activity
private class MakeRequestForGetDescription extends AsyncTask<String, Void, String> {
ProgressDialog Pdialog;
private String response;
private MakeServiceClass makeServiceClass = new MakeServiceClass();
#Override
protected void onPreExecute() {
Pdialog = new ProgressDialog(getActivity());
Pdialog.setMessage("Please Wait..");
Pdialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> parms = new HashMap<String, String>();
response = makeServiceClass.makeServiceConnectionGet(ConstUrl.DESCRP_URLS);
Log.e("response ads", response);
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(response);
if (Pdialog != null) {
Pdialog.dismiss();
}
if (response != null) {
try {
JSONObject mainObject = new JSONObject(response);
if (mainObject.has("status")) {
String Status = mainObject.getString("status");
String img_url = "";
if (Status.equalsIgnoreCase("200")) {
if (mainObject.has("img_url")) {
img_url = mainObject.getString("img_url");
Log.e("img_url", img_url);
}
if (mainObject.has("details")) {
JSONArray datArray = mainObject.getJSONArray("details");
descriptionBeanArrayList = new ArrayList<>();
if (datArray.length() > 0) {
for (int i = 0; i < datArray.length(); i++) {
DescriptionBean descriptionBean = new DescriptionBean();
JSONObject internalDataObject = datArray.getJSONObject(i);
if (internalDataObject.has("id")) {
descriptionBean.setId(internalDataObject.getString("id"));
}
if (internalDataObject.has("title_en")) {
descriptionBean.setTitle_en(internalDataObject.getString("title_en"));
}
if (internalDataObject.has("ad_description_en")) {
descriptionBean.setAd_description_en(internalDataObject.getString("ad_description_en"));
}
if (internalDataObject.has("price")) {
descriptionBean.setPrice(internalDataObject.getString("price"));
}
if (internalDataObject.has("km_driven")) {
descriptionBean.setKm_driven(internalDataObject.getString("km_driven"));
}
if (internalDataObject.has("image_file")) {
descriptionBean.setImage_file("http://" + img_url + internalDataObject.getString("image_file"));
}
descriptionBeanArrayList.add(descriptionBean);
}
setAdapterForDescription();
}
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void setAdapterForDescription() {
DescriptionAdapter adapter = new DescriptionAdapter(getActivity(), descriptionBeanArrayList);
}
}
Description Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.fragment_description, parent,false);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvRate = (TextView) convertView.findViewById(R.id.tvRate);
viewHolder.tvMiles = (TextView) convertView.findViewById(R.id.tvMiles);
viewHolder.et_description = (EditText) convertView.findViewById(R.id.et_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//setdata
viewHolder.tvTitle.setText(descriptionBeanArrayList.get(position).getTitle_en());
viewHolder.tvRate.setText(descriptionBeanArrayList.get(position).getPrice());
viewHolder.tvMiles.setText(descriptionBeanArrayList.get(position).getKm_driven());
viewHolder.et_description.setText(descriptionBeanArrayList.get(position).getAd_description_en());
Log.e("s", descriptionBeanArrayList.get(position).getImage_file());
//Glide.with(mContext).load("www.apnikheti.com/upload/buysell/idea99A4.jpg").into(viewHolder.iv_picofproduct);
Picasso.with(mContext).load(descriptionBeanArrayList.get(position).getImage_file()).into(viewHolder.iv_picofproduct, new Callback() {
#Override
public void onSuccess() {
Log.e("s", "sucess");
}
#Override
public void onError() {
Log.e("s", "failed");
}
});
Picasso.with(mContext).setLoggingEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView tvTitle,tvRate,tvMiles;
private EditText et_description;
public ImageView iv_picofproduct;
}
}
This is my code which is used to retrieve data from url (Json Data) and load it into a recyclerview using adapter and passing the same values to another activity.
MyActivity
public class Video_List extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//private GridLayoutManager layoutManager;
private List<Video_Details> videodetails;
public static final String VideoID = "v_id";
public static final String ID = "id";
public static final String Title = "title";
public static final String Thumb = "thumb";
public static final String url = "http://115.115.122.10/paul/api/videos.php?start=1&count=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__list);
getdata();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
//layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
videodetails = new ArrayList<>();
}
private void getdata(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("count",response.toString());
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Log.d("infoz","777"+error.getMessage());
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
try {
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
Video_Details video = new Video_Details();
if (json.has(VideoID)) {
Log.d("has values", json.getString(VideoID));
}
video.setId(json.getString(ID));
video.setV_id(json.getString(VideoID));
video.setTitle(json.getString(Title));
video.setThumb(json.getString(VideoID));
videodetails.add(video);
if (json.has(VideoID))
{
Log.d("Video",VideoID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new DataAdapter(videodetails, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MyAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}

How to fetch data from json in android and display in RecyclerView?

I am making an android app to fetch JSON data from URL and then showing it in a RecyclerView.
My JSON data
[{"email":"abc#gmail.com","photo":"http:\/\/www.example.com\/x.jpg","bookname":"one","price":"30","num":"3","avg":"3.9","author":"none"}]
but only bookname and photo keys values are fetching. Other parameters are empty but my code is correct because if it is wrong than even bookname shouldn't fetch.
My code is:
public class dashBoard extends AppCompatActivity {
private List<myDash> dash;
private Toolbar mToolbar;
Button read;
//Creating Views
int temp=0;
float starts=0;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public String ratenumS,numberS;
public String bookName,price,rating;
private RequestQueue requestQueue;
String mail_one;
private int requestCount = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_bord);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
dash = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
getDash();
//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
getDash();
}
});
//initializing our adapter
adapter = new dashCard(dash, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private JsonArrayRequest getDataFromDash(int requestCount) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar3);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
setProgressBarIndeterminateVisibility(true);
SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(dashBoard.this);
mail_one = pre.getString("mail2", "DEFAULT VALUE");
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("http://www.example.com/getDash.php?page="+ String.valueOf(requestCount )+"&email="+mail_one,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
if(temp==0) {
Toast.makeText(dashBoard.this, "No More Items Available "+bookName+"book "+price+" "+ratenumS+" "+numberS+" "+mail_one, Toast.LENGTH_SHORT).show();
temp++;
}
}
}
//Returning the request
return jsonArrayRequest;
}
private void getDash() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromDash(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
myDash dash1 = new myDash();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
dash1.setImageUrl(json.getString("photo"));
dash1.setBook_name(json.getString("bookname"));
dash1.setNo_down(json.getString("download"));
dash1.setBook_price(json.getString("price"));
dash1.setStar_num(json.getString("num"));
dash1.setAvg_rate(Float.parseFloat(json.getString("avg")));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
dash.add(dash1);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
Does anybody have any idea why this code is not working?
My dashCard Activity.
public class dashCard extends RecyclerView.Adapter<dashCard.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
//List to store all superheroes
List<myDash> secDash1;
//Constructor of this class
public dashCard(List<myDash> secDash1, Context context){
super();
//Getting all superheroes
this.secDash1 = secDash1;
this.context = context;
}
//In
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.dash_bord, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final myDash secDash = secDash1.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(secDash.getImageUrl(),ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(secDash.getImageUrl(), imageLoader);
holder.bookName.setText(secDash.getBook_name());
holder.price.setText(secDash.getBook_price());
holder.numberD.setText(secDash.getStar_num());
//holder.rate.setText(Float.toString(secDash.getAvg_rate()));
holder.download.setText(secDash.getNo_down());
// holder.star.setRating(secDash.getAvg_rate());
}
public int getItemCount() {
return secDash1.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
//Views
public NetworkImageView imageView;
public TextView bookName;
public TextView price;
public TextView numberD;
public TextView rate;
RatingBar star;
public TextView download;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.dashImage);
bookName = (TextView) itemView.findViewById(R.id.bookName4);
price = (TextView) itemView.findViewById(R.id.priceDash);
numberD = (TextView) itemView.findViewById(R.id.numberDash);
rate = (TextView) itemView.findViewById(R.id.ratenumDash);
star = (RatingBar) itemView.findViewById(R.id.rateDash);
download = (TextView) itemView.findViewById(R.id.download);
}
}
}
I think problem at:
dash1.setNo_down(json.getString("download"));
Your json has not download key for get value. When code run over this line, an exception has occurred and program go to catch block, other properties will never be assigned data.
I recommend that check json key are exist before get its value.
You dont have "download" as key in json because of that an exception is thrown which causes other keys to not assigned

Android MySql Volley RecyclerView NetworkImage

I saw this tutorial : https://www.simplifiedcoding.net/android-custom-listview-with-images-using-recyclerview-and-volley/
But, I am getting some problem. Here's my code :
Config.java
public class Config {
//URL of my API
public static final String DATA_URL = "http://192.168.10.7/connection.php";
//Tags for my JSON
public static final String TAG_IMAGE_URL = "image";
public static final String TAG_NAME = "name";
public static final String TAG_PRICE = "price";
}
connection.php
<?php
$host="localhost";
$username="root";
$password="";
$db_name="datatest";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from news";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['news'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<TheMain> listTheMain;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listTheMain = new ArrayList<>();
//Calling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
TheMain themaina = new TheMain();
JSONObject json = null;
try {
json = array.getJSONObject(i);
themaina.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
themaina.setName(json.getString(Config.TAG_NAME));
themaina.setPrice(json.getString(Config.TAG_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
listTheMain.add(themaina);
}
//Finally initializing our adapter
adapter = new CardAdapter(listTheMain, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
List<TheMain> themain;
public CardAdapter(List<TheMain>themain, Context context){
super();
this.themain = themain;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
TheMain themaina = themain.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(themaina.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(themaina.getImageUrl(), imageLoader);
holder.textViewName.setText(themaina.getName());
holder.textViewPrice.setText(themaina.getPrice());
}
#Override
public int getItemCount() {
return themain.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public NetworkImageView imageView;
public TextView textViewName;
public TextView textViewPrice;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.newsOne);
textViewName = (TextView) itemView.findViewById(R.id.title);
textViewPrice= (TextView) itemView.findViewById(R.id.price);
}
}
}
CustomVolleyRequest.java
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
TheMain.java
public class TheMain {
//Data Variables
private String imageUrl;
private String name;
private String price;
//Getters and Setters
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
I'm not getting any result. The ProgressDialog just starts. Nothing then.
Thanks in advance.

Categories

Resources