I am trying to display json array which is inside a json object but nothing is displaying on the text view. I debugged and found that info.java class is working fine. If i am passing the simple string value(after removing the json parsing java code) in the info.java class it's working but i am unable to pass json data.
Singleton.java
package com.example.osama.recyclerthug;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class Singleton {
private static Singleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private Singleton(Context context){
mCtx = context;
mRequestQueue =getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
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 Singleton getInstance(Context context){
if (mInstance == null){
mInstance = new Singleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
if (mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> request){
getRequestQueue().add(request);
}
public ImageLoader getmImageLoader(){
return mImageLoader;
}
}
...................................................................
ThugAdapter.java
package com.example.osama.recyclerthug;
import android.net.Uri;
import android.support.annotation.NonNull;
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 java.util.ArrayList;
public class ThugAdapter extends RecyclerView.Adapter<ThugAdapter.ThugHolder> {
ArrayList<Info> arrayList1;
public ThugAdapter(ArrayList<Info> arrayList){
this.arrayList1 = arrayList;
}
#NonNull
#Override
public ThugHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.appearance, viewGroup, false);
ThugHolder thugHolder = new ThugHolder(view);
return thugHolder;
}
#Override
public void onBindViewHolder(#NonNull ThugHolder thugHolder, int i) {
thugHolder.text.setText(arrayList1.get(i).getTxt1());
thugHolder.text2.setText(arrayList1.get(i).getTxt2());
/* thugHolder.image.setImageURI(arrayList.get(i).getImageUri());*/
}
#Override
public int getItemCount() {
return arrayList1.size();
}
public class ThugHolder extends RecyclerView.ViewHolder{
TextView text,text2;
ImageView image;
public ThugHolder(#NonNull View itemView) {
super(itemView);
text = itemView.findViewById(R.id.textView);
text2 = itemView.findViewById(R.id.textView2);
image = itemView.findViewById(R.id.imageView);
}
}
}
............................................................................
Info.java
package com.example.osama.recyclerthug;
import android.net.Uri;
public class Info {
private String txt1,txt2;
// private Uri imageuri;
public Info(String txt1, String txt2/*, Uri imageuri*/){
this.setTxt1(txt1);
this.setTxt2(txt2);
/* this.setImageUri(imageuri);*/
}
public String getTxt1() {
return txt1;
}
public void setTxt1(String txt1) {
this.txt1 = txt1;
}
public String getTxt2() {
return txt2;
}
public void setTxt2(String txt2) {
this.txt2 = txt2;
}
/*public Uri getImageUri() {
return imageuri;
}
public void setImageUri(Uri imageuri) {
this.imageuri = imageuri;
}*/
}
........................................................
BackgroundTask.java
package com.example.osama.recyclerthug;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class BackgroundTask {
Context context;
ArrayList<Info> arrayList;
String json_url = "http://cc97cf60.ngrok.io/api/note/";
public BackgroundTask(Context context){
this.context = context;
}
public ArrayList<Info> getArrayList(){
arrayList = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray ;
try {
jsonArray = response.getJSONArray("objects");
int i;
for (i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
/* Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
String a = jsonObject.getString("title");
String b = jsonObject.getString("body");
Info info = new Info(a,b);
arrayList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
return arrayList;
}
}
..............................................
MainActivity.java
package com.example.osama.recyclerthug;
import android.app.DownloadManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
ThugAdapter thugAdapter;
BackgroundTask backgroundTask;
ArrayList<Info> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
backgroundTask = new BackgroundTask(this);
arrayList = new ArrayList<>();
arrayList= backgroundTask.getArrayList();
thugAdapter = new ThugAdapter(arrayList);
recyclerView.setAdapter(thugAdapter);
}
}
Edit: Below is the json data:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 2
},
"objects": [
{
"body": "Breaking News:\r\nOsama Abrar is Iron Man.",
"created_at": "2018-12-08T08:40:59.949776",
"id": 1,
"image": "https://wonderfulengineering.com/wp-content/uploads/2016/01/iron-man-wallpaper-6.jpg",
"resource_uri": "/api/note/1/",
"title": "Iron Man"
},
{
"body": "Will Iron Man aka Osama Abrar survive?",
"created_at": "2018-12-08T08:41:40.279677",
"id": 2,
"image": "https://marciokenobi.files.wordpress.com/2013/03/iron_man.jpg",
"resource_uri": "/api/note/2/",
"title": "End Game"
}
]
}
JSON parsing is OK but you can't retrieve your data like this because you used Volley in asynchronous mode. It means that you can't assume that data will be retrieved as soon as you put the request in the queue. Maybe the queue is very long and your request can be sent later. So, when you tried to retrieve your data, you've seen that your arrayList is null, and it's normal. To deal with the asynchronous way, you have to tell Volley : "tell me when you've retrieved data". And you can do this with a listener.
Here is an example.
public interface Listener {
void onDataReceived(ArrayList<Info> list);
void onError(int error);
}
BackgroundTask
public class BackgroundTask {
Context context;
ArrayList<Info> arrayList;
Listener mListener; // listener to retrieve data
String json_url = "http://cc97cf60.ngrok.io/api/note/";
public BackgroundTask(Context context, Listener listener) {
this.context = context;
mListener = listener;
}
public void getArrayList() { // no return needed
arrayList = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray;
try {
jsonArray = response.getJSONArray("objects");
int i;
for (i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
/* Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
String a = jsonObject.getString("title");
String b = jsonObject.getString("body");
Info info = new Info(a, b);
arrayList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
// if listener has been set, send data
if (mListener != null) {
mListener.onDataReceived(arrayList);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// if listener has been set, send error
if (mListener != null) {
mListener.onError(error.networkResponse.statusCode);
}
}
});
Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
}
}
In your MainActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
backgroundTask = new BackgroundTask(this, new Listener() {
#Override
public void onDataReceived(ArrayList<Info> list) {
thugAdapter = new ThugAdapter(list);
recyclerView.setAdapter(thugAdapter);
}
#Override
public void onError(int error) {
}
});
backgroundTask.getArrayList();
}
And that is !
Related
I was trying to load the data dynamically from the api's response onto the recycler views and I keep getting this error. I got the response and I don't think it's the problem with async code because when I debugged I got the response and the array is not empty before text in the array is inflated onto a view. Any help would be Appreciated.
Card_List_View_Admins.java
package com.craftofcode.amrita_event;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.Network;
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.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.JsonArrayRequest;
import com.craftofcode.amrita_event.adapter.EventListAdapter;
import com.craftofcode.amrita_event.apiModel.MySingleton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class Card_list_View_Admins extends AppCompatActivity {
Cache cache;
Network network;
RequestQueue requestQueue;
public EventListAdapter adapter;
// public String[] Title = {"Peppy paneer Pizza", "Paneer Makhni Pizza", "Cheese Burst Pizza", "Corn Pizza","papperoni pizza","farm house pizza", "vegie deilight pizza","chicken pizza", "tandoori pizza","custom pizza"};
// public String[] Club = {"Peppy paneer Pizza", "Paneer Makhni Pizza", "Cheese Burst Pizza", "Corn Pizza","papperoni pizza","farm house pizza", "vegie deilight pizza","chicken pizza", "tandoori pizza","custom pizza"};
// public String[] Date = {"250","260","240.5","350","312","250","260","240.5","350","312"};
int[] EventImages = {
R.drawable.p1,
R.drawable.p2,
};
private LinkedList<String> _id;
private LinkedList<Integer> EventImage;
//Image URL variable for now
private LinkedList<String> Url;
private LinkedList<String> EventTitle;
private LinkedList<String> Clubname;
private LinkedList<String> DateEvent;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_list_view_admins);
// Image Url String for now
// setting up the Request Queue
SettingUpRequestQueue();
SharedPreferences TOKEN = getSharedPreferences("TOKEN", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = TOKEN.edit();
//pushing token to shared preference
edit.putString("user-auth-token", "replaced-with-Token");
edit.commit();
// Api call is being made Here
String AdminUsersEventsEndpoint = "https://amrita-events.herokuapp.com/api/admin-users-portal";
JsonArrayRequest EventCardRequest = new JsonArrayRequest
(Request.Method.GET, AdminUsersEventsEndpoint, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
_id = new LinkedList<>();
EventImage = new LinkedList<>();
Url = new LinkedList<>();
EventTitle = new LinkedList<>();
Clubname = new LinkedList<>();
DateEvent = new LinkedList<>();
System.out.println(response);
for(int i = 0; i < response.length(); i++){
try {
EventImage.addLast(EventImages[i]);
System.out.println(response.getJSONObject(i));
JSONObject event = response.getJSONObject(i);
_id.addLast(event.get("_id").toString());
Url.addLast(event.get("ImageUrl").toString());
EventTitle.addLast(event.get("Title").toString());
Clubname.addLast(event.get("OrganizingClub").toString());
DateEvent.addLast(event.get("Date").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(EventTitle);
recyclerView = findViewById(R.id.recyclerView);
adapter = new EventListAdapter(getApplicationContext(), EventTitle, EventImage, Clubname, DateEvent);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences TOKEN = getSharedPreferences("TOKEN", Context.MODE_PRIVATE);
params.put("user-auth-token", TOKEN.getString("user-auth-token","Theif..!"));
return params;
}
};
//adding the request to Queue
MySingleton.getInstance(this).addToRequestQueue(EventCardRequest);
}
private void SettingUpRequestQueue() {
cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); //1Mb cap
network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
}
EventListAdapter.java
package com.craftofcode.amrita_event.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.craftofcode.amrita_event.R;
import java.util.LinkedList;
public class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ItemViewHolder> {
private final LinkedList<String> EventTitle;
private final LinkedList<Integer> EventImage;
private final LinkedList<String> OrgClub;
private final LinkedList<String> EventDate;
private LayoutInflater ItemLayoutInflater;
public Context context;
class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView ImageEvent;
public TextView EventTitle;
public TextView OrgClub;
public TextView Date;
//support for buttons
public Button DeleteButton;
public Button UpdateButton;
final EventListAdapter EventsAdapter;
public ItemViewHolder(View EventView, EventListAdapter EventsAdapter){
super(EventView);
ImageEvent = EventView.findViewById(R.id.image);
EventTitle = EventView.findViewById(R.id.title);
OrgClub = EventView.findViewById(R.id.club);
Date = EventView.findViewById(R.id.date);
DeleteButton = EventView.findViewById(R.id.delbutton);
UpdateButton = EventView.findViewById(R.id.updbutton);
this.EventsAdapter = EventsAdapter;
EventView.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("mess" , "Herllo click");
Log.d("mess", String.valueOf(getAdapterPosition()));
}
});
}
#Override
public void onClick(View v) {
// Intent intent = new Intent(context, Expanded_Card_Admins.class);
// //ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context, v, "ContainerTransform");
// context.startActivity(intent);
}
}
public EventListAdapter(Context context, LinkedList<String> EventTitle, LinkedList<Integer> EventImage, LinkedList<String> OrgClub,LinkedList<String> EventDate){
ItemLayoutInflater = LayoutInflater.from(context);
this.EventTitle = EventTitle;
this.EventImage = EventImage;
this.OrgClub = OrgClub;
this.EventDate = EventDate;
this.context = context;
}
public EventListAdapter.ItemViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View ItemView = ItemLayoutInflater.inflate(R.layout.admin_card_view,parent,false);
return new ItemViewHolder(ItemView, this);
}
#Override
public void onBindViewHolder(EventListAdapter.ItemViewHolder holder, int position) {
String CurrentEventName = EventTitle.get(position);
int CurrentEventImage = EventImage.get(position);
String CurrentOrgClub = OrgClub.get(position);
String CurrentEventDate = EventDate.get(position);
holder.EventTitle.setText(CurrentEventName);
holder.ImageEvent.setImageResource(CurrentEventImage);
holder.OrgClub.setText(CurrentOrgClub);
holder.Date.setText(CurrentEventDate);
//onclick listener here
}
#Override
public int getItemCount() {
return EventTitle.size();
}
}
This problem is not in your adapter/java code. I doubt this is in your layout file "admin_card_view"
Please double check this layout file, most probably there will have some dependency which is not satisfied yet
As per mentioned in error - It could be at line no. 19 and in MaterialCardView.
Make sure you have dependency added in your build.gradle file for the same
Please add this in app level build.gradle, clean and rebuild project once and then run your app
implementation "androidx.cardview:cardview:1.0.0"
Hope it will resolve your problem
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
i'm building an application that connects to my Drupal API. Somehow i'm not getting any data display within my application. I don't see any errors in the code and the debugging online gives the follow error: E/RecyclerView: No adapter attached; skipping layout
Here is my MainActivity code:
package com.example.eindopdrachtcmsapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
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.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity implements ExampleAdapter.onItemClickListener {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_BODY = "body";
public static final String EXTRA_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://vistudio.be/api/portfolio";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject portfolio = response.getJSONObject(i);
String title = portfolio.getString("title");
String body = portfolio.getString("body");
String link = portfolio.getString("field_website_url");
mExampleList.add(new ExampleItem(title, body, link));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
detailIntent.putExtra(EXTRA_BODY, clickedItem.getBody());
detailIntent.putExtra(EXTRA_LINK, clickedItem.getLink());
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
startActivity(detailIntent);
}
}
My Adapter code:
package com.example.eindopdrachtcmsapi;
import android.content.Context;
import android.graphics.PorterDuffColorFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.portfolioViewHolder>{
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private onItemClickListener mListener;
private onItemClickListener mListenerShare;
public interface onItemClickListener{
void onItemClick(int position);
}
public void setOnClickListener(onItemClickListener listener, onItemClickListener listenerShare){
mListener = listener;
mListenerShare = listenerShare;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> ExampleList) {
mContext = context;
mExampleList = ExampleList;
}
#Override
public portfolioViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.exampleitem, parent, false);
return new portfolioViewHolder(v);
}
#Override
public void onBindViewHolder(portfolioViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
String body = currentItem.getBody();
String link = currentItem.getLink();
holder.mTextViewTitle.setText(title);
holder.mTextViewBody.setText(body);
holder.mTextViewLink.setText(link);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class portfolioViewHolder extends RecyclerView.ViewHolder{
public TextView mTextViewTitle;
public TextView mTextViewBody;
public TextView mTextViewLink;
public Button mButton;
public portfolioViewHolder(View itemView) {
super(itemView);
mTextViewTitle = itemView.findViewById(R.id.text_view_title);
mTextViewBody = itemView.findViewById(R.id.text_view_body);
mTextViewLink = itemView.findViewById(R.id.text_view_link);
mButton = itemView.findViewById(R.id.share);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListenerShare != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListenerShare.onItemClick(position);
}
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
first remove inside oncreate()
mRecyclerView.setAdapter(mExampleAdapter);
after this code
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
add this:-
mExampleAdapter.notifyDataSetChanged();
I am not able to update the values when i click on the search button, The data is fetched but the old fetched data is not getting discards, the fetched data is overlapping over each other
SearchFragment.java
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
private String Api_id= "3f335994";
private String Api_key = "8e99e327d1f2130dc6ab3422e26a95e8";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "https://api.edamam.com/search?q=" + query + "&app_id=" + Api_id + "&app_key=" + Api_key;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hits = response.getJSONArray("hits");
for (int i =0;i<hits.length();i++) {
JSONObject jsonObject = hits.getJSONObject(i);
JSONObject recipe = jsonObject.getJSONObject("recipe");
String recipe_img = recipe.getString("image");
String recipe_title = recipe.getString("label");
String recipe_data = recipe.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(),recipeList);
recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonObjectRequest);
/*JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
Log.d("data",recipe_title);
}
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});*/
/*jsonArrayRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 3000;
}
#Override
public int getCurrentRetryCount() {
return 3000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});*/
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I want to get rid of the old data after the new data is fetched and don't want to display it after the new one is called
looks like you are only adding items to your ArrayList<Recipe> recipeList;, so they may duplicate
maybe try to recipeList.clear(); it in first line of onResponse method
also notifyDataSetChanged isn't needed, setAdapter does it itself (and a lot more in fact)
I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
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 android.widget.AdapterView;
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 org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
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.ArrayList;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});
I have been trying to call methods on the Main Activity from another class. But, the methods are not resolved. Check out the code.
package com.example.android.andhive_glideimagelib.activity;
import android.app.ProgressDialog;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.android.andhive_glideimagelib.R;
import com.example.android.andhive_glideimagelib.adapter.GalleryAdapter;
import com.example.android.andhive_glideimagelib.app.AppController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "http://api.androidhive.info/json/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
private void fetchImages() {
pDialog.setMessage("Downloading json...");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
image.setName(object.getString("name"));
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTimestamp(object.getString("timestamp"));
images.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
The Class,
package com.example.android.andhive_glideimagelib.model;
import java.io.Serializable;
public class Image implements Serializable {
private String name;
private String small, medium, large;
private String timestamp;
public Image() {
}
public Image(String name, String small, String medium, String large, String timestamp) {
this.name = name;
this.small = small;
this.medium = medium;
this.large = large;
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSmall() {
return small;
}
public void setSmall(String small) {
this.small = small;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getLarge() {
return large;
}
public void setLarge(String large) {
this.large = large;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
I can't call the methods of the Image class. Thanks for the help !
in the image class make it static method
example:
public static void setSmall(String small){
this.small=small;
}
in MainActivity
Image.setSmall("value");