Why JSON data can't reach ViewPager? - java

I want to fetch Images using Volley JSON in PagerAdapter for slider , but problem is that data fetched using JSON is reached till constructor but not reatched to InstantiateItem method.
This is my xml File.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="#dimen/_200sdp"
android:id="#+id/view_pager">
</androidx.viewpager.widget.ViewPager>
<TextView
android:layout_width="match_parent"
android:layout_height="#dimen/_50sdp"
android:text="#string/app_name"
android:textSize="#dimen/_30sdp"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/txt"/>
</LinearLayout>
MainActivity.java
package com.example.sliderwithvolleyjson;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
String slider_url="Here is my API";
ArrayList<String> image=new ArrayList<>();
RequestQueue queue;
Slider_Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(getApplicationContext());
viewPager=findViewById(R.id.view_pager);
getImageByJson();
viewPager.setAdapter(adapter);
}
public void getImageByJson(){
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, slider_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array=response.getJSONArray("slider");
for (int i=0;i<array.length();i++){
JSONArray jsonData=array.getJSONArray(i);
image.add(jsonData.getString(1));
}
String[] imageUrls=new String[image.size()];
imageUrls=image.toArray(imageUrls);
for (String s : imageUrls){
Log.d("String",s);
}
adapter=new Slider_Adapter(getApplicationContext(),imageUrls);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),String.valueOf(e),Toast.LENGTH_LONG).show();
Log.d("ath",String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),String.valueOf(error),Toast.LENGTH_LONG).show();
Log.d("Error",String.valueOf(error));
}
});
queue.add(request);
}
}
I fetch images from my server using API in mainactivity class. I use Volley JSON to do it. Then i passed this images to PagerAdapter class using viewpager.
PagerAdapter Class
package com.example.sliderwithvolleyjson;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.squareup.picasso.Picasso;
public class Slider_Adapter extends PagerAdapter {
LayoutInflater inflater;
private Context context;
private String[] imageurls;
public Slider_Adapter(Context context, String[] imageurls) {
this.context = context;
this.imageurls = imageurls;
Toast.makeText(context, String.valueOf(imageurls[1]), Toast.LENGTH_SHORT).show();
}
#Override
public int getCount() {
return imageurls.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view==object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.activity_main,container);
ImageView imageView=new ImageView(container);
TextView textView=view.findViewById(R.id.txt);
textView.setText(String.valueOf(imageurls.length));
Picasso.with(context).load(imageurls[position]).fit().into(imageView);
ViewPager pager=(ViewPager)container;
pager.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
}
That Images is arrived till constructor (I tried it using toast message) but We can't find that images/data in InstantiateItem method and other functions.
Thanks in Advance.

public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
String slider_url="Here is my API";
ArrayList<String> image=new ArrayList<>();
RequestQueue queue;
Slider_Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(getApplicationContext());
viewPager=findViewById(R.id.view_pager);
getImageByJson();
}
public void getImageByJson(){
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, slider_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array=response.getJSONArray("slider");
for (int i=0;i<array.length();i++){
JSONArray jsonData=array.getJSONArray(i);
image.add(jsonData.getString(1));
}
String[] imageUrls=new String[image.size()];
imageUrls=image.toArray(imageUrls);
for (String s : imageUrls){
Log.d("String",s);
}
adapter=new Slider_Adapter(getApplicationContext(),imageUrls);
viewPager.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),String.valueOf(e),Toast.LENGTH_LONG).show();
Log.d("ath",String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),String.valueOf(error),Toast.LENGTH_LONG).show();
Log.d("Error",String.valueOf(error));
}
});
queue.add(request);
}
}

for (String s : imageUrls){
Log.d("String",s);
}
adapter=new Slider_Adapter(getApplicationContext(),imageUrls);
After this line of codes in your onResponse method, add this code.
viewPager.setAdapter(adapter);
And remove it from onCreate because it is not necessary.

Related

Why I can't define FindViewById() on Fragment with Volley Library

I am trying to define FindViewById() on Fragment with Volley Library. Also, I put FindViewById() on method OnResponse(), but I am getting an error. Do you have any solution? Here is my code.
package com.smktelkommlg.prakerinlistview;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SecondFragment extends Fragment {
private static final String BASE_URL = "Some Base URL";
private final String EndPoint = "Somr EndPoint";
List<Result> resultsLists;
ListView listView;
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second, container, false);
resultsLists = new ArrayList<>();
listView = rootView.findViewById(R.id.listView);
ProgressBar progressBar = rootView.findViewById(R.id.rolling);
loadResultsList();
// Instantiate the RequestQueue.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String idToDetail = String.valueOf(resultsLists.get(position).getId());
Intent detailIntent = new Intent(getActivity(),DetailActivity.class);
detailIntent.putExtra("idMoveIntent", idToDetail);
startActivity(detailIntent);
}
});
return rootView;
}
private void loadResultsList () {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, BASE_URL+EndPoint+"?limit=1000&offset=0", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ProgressBar progressBar = findViewById(R.id.rolling);
Log.d("Json Response", response);
try {
JSONObject obj = new JSONObject(response);
JSONArray heroArray = obj.getJSONArray("results");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
Result superHero = new Result(heroObject.getString("name"), heroObject.getInt("id"), heroObject.getJSONObject("device_role").getString("name"), heroObject.getJSONObject("status").getString("value"), heroObject.getJSONObject("device_type").getJSONObject("manufacturer").getString("slug"));
resultsLists.add(superHero);
}
ListViewAdapter adapter = new ListViewAdapter(resultsLists, getActivity().getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap header = new HashMap();
header.put("Content-Type", "application/json");
header.put("Authorization", "Token eaaa9e72d1a4f4c75aef7a7492e07785d853b6b4");
return header;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
}
#Override
public void onViewCreated (#NonNull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Results");
getContext();
}
}
I can't define this ProgressBar progressBar = findViewById(R.id.rolling);
Do I have to put ProgressBar progressBar = findViewById(R.id.rolling); in OnCreateView and use rootView? What should I do?
I meant to call progressBar before receive through the API.
(I'm sorry for my grammar. I hope you understand)
And here's my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/rolling"
style="?android:attr/progressBarStyleLarge"
android:layout_width="match_parent"
android:indeterminate="true"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Use Global Variable
In your SecondFragment:
ProgressBar progressBar;
in OnCreateView:
progressBar = rootView.findViewById(R.id.rolling);
Remove ProgressBar progressBar = findViewById(R.id.rolling); from loadResultsList() method.

Failed to parse Json data from the Api

I am trying to get the data (List of Images and Names) from an Api using Volley into a recycler View but due to some reason I am only getting the list of names but unable to fetch the images corresponding to that name, and getting File Not Found Exception
This is the Main Activity
package com.example.bks;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG ="tag";
RecyclerView recyclerView;
ProgressBar progressBar;
private List<CropModel> mList;
private cropAdapter cropAdapter;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recycleView);
progressBar=findViewById(R.id.progressBar);
cropAdapter= new cropAdapter(this, mList );
recyclerView.setLayoutManager(new LinearLayoutManager(this));
requestQueue=volleySingleton.getmInstance(this).getRequestQueue();
mList= new ArrayList<>();
fetchData();
}
private void fetchData() {
progressBar.setVisibility(View.VISIBLE);
String url= "http://bharatkrushiseva.in/api_user/getCropType";
JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray= response.getJSONArray("crop");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String name= jsonObject.getString("crop_name");
String image= jsonObject.getString("crop_image");
CropModel post = new CropModel(name,image);
mList.add(post);
}
cropAdapter adapter = new cropAdapter(MainActivity.this,mList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params= new HashMap<>();
params.put("language","en");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
}
This is the Adapter Class
package com.example.bks;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class cropAdapter extends RecyclerView.Adapter<cropAdapter.Viewholder> {
private Context context;
private List<CropModel> cropModels;
public cropAdapter(Context context, List<CropModel> cropModels) {
this.context = context;
this.cropModels = cropModels;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.crop_view,parent,false);
return new cropAdapter.Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
CropModel cropModel= cropModels.get(position);
holder.cropName.setText(cropModel.getCrop_name());
Glide.with(context).load(cropModel.getCrop_image()).into(holder.cropImage);
}
#Override
public int getItemCount() {
return cropModels.size() ;
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView cropName;
ImageView cropImage;
public Viewholder(#NonNull View itemView) {
super(itemView);
cropImage=itemView.findViewById(R.id.Cropimage);
cropName=itemView.findViewById(R.id.cropName);
}
}
}
This is my Model Class
package com.example.bks;
public class CropModel {
private String crop_name;
private String crop_image;
public CropModel(String crop_name, String crop_image) {
this.crop_name = crop_name;
this.crop_image = crop_image;
}
public String getCrop_name() {
return crop_name;
}
public void setCrop_name(String crop_name) {
this.crop_name = crop_name;
}
public String getCrop_image() {
return crop_image;
}
public void setCrop_image(String crop_image) {
this.crop_image = crop_image;
}
}
This is the Volley Singleton Class
package com.example.bks;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class volleySingleton {
private RequestQueue requestQueue;
private static volleySingleton mInstance;
private volleySingleton(Context context) {
requestQueue= Volley.newRequestQueue(context.getApplicationContext());
}
public static synchronized volleySingleton getmInstance(Context context){
if(mInstance==null){
mInstance=new volleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
return requestQueue;
}
}

Fragment, Volley and RecyclerView JSON

I hope someone there will help me solve my problem. I have an Android application that uses the fragment. I want to download data using Volley from a JSON file. The program does not throw out any errors but CardView does not display with the ordered data. I looked at other topics with a similar problem, but I sit on it for a long time and nothing good happens.
AdapterZabytki.java
package eu.aisen.kamil.miejskiprzewodnik;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import zabytki.Zabytki;
public class AdapterZabytki extends RecyclerView.Adapter<AdapterZabytki.ViewHolder> {
private List<Zabytek>list_data;
private Zabytki context;
public AdapterZabytki(List<Zabytek> list_data, Zabytki context) {
this.list_data = list_data;
this.context = context;
}
#Override
public AdapterZabytki.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView view= (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.obiectcard,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Zabytek zabytek = list_data.get(position);
Picasso.get()
.load(zabytek
.getImage_url())
.into(holder.img);
holder.txtname.setText(zabytek.getName());
}
#Override
public int getItemCount() {
return list_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView img;
private TextView txtname;
public ViewHolder(View view) {
super(view);
img=(ImageView)itemView.findViewById(R.id.info_image);
txtname=(TextView)itemView.findViewById(R.id.info_text);
}
}
}
Zabytek.java
package eu.aisen.kamil.miejskiprzewodnik;
public class Zabytek {
private String name;
private String image_url;
private String opis;
public Zabytek(String name, String image_url, String opis) {
this.name = name;
this.image_url = image_url;
this.opis = opis;
}
public String getName() {
return name;
}
public String getImage_url() {
return image_url;
}
public String getOpis() {
return opis;
}
}
Zabytki.java (fragment)
package zabytki;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import eu.aisen.kamil.miejskiprzewodnik.AdapterZabytki;
import eu.aisen.kamil.miejskiprzewodnik.R;
import eu.aisen.kamil.miejskiprzewodnik.Zabytek;
public class Zabytki extends Fragment {
private static final String HI = "https://wydzialedukacji.rzeszow.pl/testowy.json";
private ArrayList<Zabytek>list_data;
private AdapterZabytki mSensorAdapter;
private RecyclerView mRyclerView;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.zabytki_fragment, container, false);
mRyclerView = view.findViewById(R.id.main_list);
mRyclerView.setHasFixedSize(true);
mRyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
list_data = new ArrayList<>();
getData();
mSensorAdapter = new AdapterZabytki(list_data, this);
mRyclerView.setAdapter(mSensorAdapter);
mSensorAdapter.notifyDataSetChanged();
return view;
}
private void getData() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, HI, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for(int i=0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name");
String image_url = object.getString("image_url");
String opis = object.getString("opis");
list_data.add(new Zabytek(name, image_url, opis));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(getActivity()).add(request);
}
}
zabytki_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView android:id="#+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.RecyclerView>
obiectcard.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/card_view"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">
<android.support.constraint.ConstraintLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp">
<ImageView
android:id="#+id/info_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="24dp"
android:layout_weight="1.0"
android:scaleType="centerCrop"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:srcCompat="#android:drawable/sym_def_app_icon"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/info_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginEnd="16dp"
android:text="tytułzabytku"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintTop_toBottomOf="#+id/info_image" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
I have 2 concerns about your code:
1. in onResponse, after you added all items to to list_data, you must call notifyDatasetChanged on RecyclerView adapter (AdapterZabytki)
2. Also, info_image in your ViewHolder seems to have zero height, because it has no top alignment and layout_height="0dp"
I am still wondering how to transfer this data to ZabytekDetailActivity.class
I have this:
mSensorAdapter.setListener(new AdapterZabytki.Listener() {
public void onClick(int position) {
ArrayList<Zabytek> object = new ArrayList<Zabytek>();
Intent intent = new Intent(getActivity(), ZabytekDetailActivity.class);
}
});
Now the question is how to attach the results from list_data so that they can be displayed in MonumentDetailActivity.class

Can't Update Recyclerview adapter with new list,new list showing blank

I want to get new updated list in Favourite activity,but instead i'm getting no items in favourite list.List getting values from sharedpreference but not updating to recycler view.
DiseaseAdapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx){
this.data=data;
notifyDataSetChanged();
this.ctx=ctx;
sharedPreference = new SharedPreference();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder {
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
}
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
simpleListView.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, simpleListView ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
SharedPreference.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class Favourite extends AppCompatActivity {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx);
diseaseAdapter.notifyDataSetChanged();
favoriteList.setAdapter(diseaseAdapter);
favoriteList.invalidate();
favoriteList.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, favoriteList ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.notifyItemRemoved(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.fav.MainActivity">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/simpleListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:textColor="#434b3e"
android:text=""/>
<ImageView
android:id="#+id/imgbtn_favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:background="#null"
/>
</RelativeLayout>
activity_favourite.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.fav.Favourite">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/favListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
You are missing setLayoutManager() in Favourite.java.
Try calling NotifyDataSetChanged() instead of NotifyItemRemoved() or NotifyItemAdded(). These methods did not work for me either. You just won't get the animations of items being added and removed but you can add your own animations to do the trick!
You should use Room Database to store lists and handle them as it is much easier and makes a lot of sense. SharedPreferences is recommended for storing values such as integers and booleans, not whole lists.

unexpected response code 401 for URL

package com.example.murarilal.volley;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="API_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description",url);
startActivity(intent);
}
});
}
public void home()
{
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
package com.example.murarilal.volley;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ArticleActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
Intent intent=getIntent();
webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
webView.loadUrl(url);
}
}
https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e
I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity
this the log error
11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
14350-14350/com.example.murarilal.volley W/System.err: at
com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
W/System.err: at
com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
/* Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description",url);
startActivity(intent);*/
}
});
}
public void home()
{
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
Log.d("title ", String.valueOf(array.getJSONObject(i).get("title")));
Log.d("urlToImage ", String.valueOf(array.getJSONObject(i).get("urlToImage")));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
Try to use URLConnection instead of volley.
401 indicates of have Unauthorized access to the given URL
I tried both api V1 And V2 with volley and got status code 200 and the data matches with the data shown when the request is made from a browser.
To help Can you add Logs and post it over here
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,error.networkResponse.toString());
error.printStackTrace();
}
});
Have you tried adding this line in your gradle file.
I've implemented your code, the data is being called properly.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Categories

Resources