Fragment, Volley and RecyclerView JSON - java

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

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.

java.lang.ClassCastException: CustomAdapter cannot be cast to android.widget.ArrayAdapter in java

I am trying to load json data into a scrollable spinner. But I am getting the error that the CustomAdapter is not able to cast into ArrayAdapter. Can you help me with this?
Provide_Food.xml: This is the file where the spinner is located
<?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"
android:background="#drawable/grdnt"
tools:context=".Provide_food">
<com.toptoche.searchablespinnerlibrary.SearchableSpinner
android:id="#+id/select_food"
android:layout_width="120dp"
android:layout_height="50dp"
android:layout_marginTop="250dp"
android:background="#color/bgcolor"
app:hintText="Select Item"
/>
<Button
android:id="#+id/select_food_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/select_food"
android:layout_marginTop="250dp"
android:layout_marginLeft="40dp"
android:text="Add Item"/>
</RelativeLayout>
Provide_Food.java: The java class for loading the json data into the spinner
package com.example.helping_hands_individual;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.textclassifier.TextLinks;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
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.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.database.annotations.Nullable;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Provide_food extends AppCompatActivity {
Spinner spinner;
String url = "api_link"; //can't mention the link here
List<Item_Model> list = new ArrayList<>();
List<String> list1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provide_food);
spinner = (Spinner)findViewById(R.id.select_food);
new Getdata().execute();
}
class Getdata extends AsyncTask<Void,Void,String>{
String result;
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
CustomAdapter adapter = new CustomAdapter(Provide_food.this, list);
spinner.setAdapter(adapter);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL mainurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)mainurl.openConnection();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null){
builder.append(line);
}
result = builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray array = new JSONArray(result);
for (int i=0; i<array.length(); i++){
Item_Model item_model = new Item_Model();
JSONObject object = array.getJSONObject(i);
String itemname = object.getString("Item Name");
item_model.setItemname(itemname);
list.add(item_model);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Item_Model.java: The model class for getting the item name from the json api
package com.example.helping_hands_individual;
public class Item_Model {
String itemname;
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
}
CustomAdapter.java: The custom adapter used for parsing the data into the spinner
package com.example.helping_hands_individual;
import android.content.Context;
import android.transition.Slide;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class CustomAdapter extends BaseAdapter {
LayoutInflater inflater;
Context context;
List<Item_Model> list;
public CustomAdapter(Context applicationContext, List<Item_Model> list){
this.context = applicationContext;
this.list = list;
inflater = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.item,null);
TextView itemname = (TextView)view.findViewById(R.id.item_names);
itemname.setText(list.get(i).itemname);
return view;
}
}
item.xml: The sample layout file where it contains only the textview which will be displayed in the spinner
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/item_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:textSize="18dp"
android:text="Demo"/>
</LinearLayout>
Your CustomAdapter should extends ArrayAdapter, so you can change your class in this way:
public class CustomAdapter extends ArrayAdapter {
LayoutInflater inflater;
Context context;
List<Item_Model> list;
public CustomAdapter(Context applicationContext, int resources, List<Item_Model> list) {
super(applicationContext, resources);
this.context = applicationContext;
this.list = list;
inflater = (LayoutInflater.from(applicationContext));
}
//...
}
Consider using the parameterized ArrayAdapter<T> feature

Having trouble converting an activity into a fragment. Activity contains a DialogueFragment

So I have to convert an activity into a fragment. I followed some basic principles however the app still crashes.
The converted activity code:
package com.example.computerscienceiawithtablayout;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import java.io.File;
import java.util.*;
public class FragmentHome extends Fragment implements AddBookDialogue.AddBookDialogueListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onStart() {
super.onStart();
}
public void onBigButtonClick(View w) {
AddBookDialogue addBookDialogue = new AddBookDialogue();
addBookDialogue.show(getChildFragmentManager(), "add book dialogue");
}
#Override
public void getTexts(String bookAuthor, String bookTitle, String bookBarcode, String bookCourse, String selectedBookshelf) {
if(bookAuthor.isEmpty() || bookTitle.isEmpty() || bookBarcode.isEmpty() || bookCourse.isEmpty()){
Toast.makeText(getActivity(), "You didn't enter all necessary data", Toast.LENGTH_LONG).show();
}else{
if(bookBarcode.length()!=8){
Toast.makeText(getActivity(), "Barcodes should be eight digits long", Toast.LENGTH_LONG).show();
}else{ if(selectedBookshelf.equals("Withdrawn")){
Book a = new Book(bookAuthor, bookTitle, bookBarcode, bookCourse, selectedBookshelf);
Toast.makeText(getActivity(), a.toString(), Toast.LENGTH_LONG).show();
}else{
Book a = new Book(bookAuthor, bookTitle, bookBarcode, bookCourse, selectedBookshelf);
Toast.makeText(getActivity(), a.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
The fragment call upon an addBookDialogue, which is a dialoguefragment, code here:
package com.example.computerscienceiawithtablayout;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
public class AddBookDialogue extends AppCompatDialogFragment{
private EditText editTextBookAuthor;
private EditText editTextBookTitle;
private EditText editTextBookCourse;
private EditText editTextBookBarcode;
private Spinner spinnerBookshelf;
private AddBookDialogueListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentFragment().getActivity());
LayoutInflater inflater = getParentFragment().getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialogue_addbook, null);
builder.setView(view)
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String bookAuthor = editTextBookAuthor.getText().toString();
String bookTitle = editTextBookTitle.getText().toString();
String bookBarcode = editTextBookBarcode.getText().toString();
String bookCourse = editTextBookCourse.getText().toString();
String seletecBookshelf = spinnerBookshelf.getSelectedItem().toString();
listener.getTexts( bookAuthor, bookTitle, bookBarcode, bookCourse, seletecBookshelf);
}
});
editTextBookAuthor = view.findViewById(R.id.author);
editTextBookTitle= view.findViewById(R.id.bookTitle);
editTextBookBarcode= view.findViewById(R.id.bookBarcode);
editTextBookCourse= view.findViewById(R.id.bookBarcode);
spinnerBookshelf= view.findViewById(R.id.spinnerBookshelf);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.addBookBookshelfsAvailable, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerBookshelf.setAdapter(spinnerAdapter);
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (AddBookDialogueListener) context;
} catch(ClassCastException e){
throw new ClassCastException(context.toString() + "no listener");
}
}
public interface AddBookDialogueListener{
void getTexts(String bookAuthor, String bookTitle, String bookBarcode, String bookCourse, String selectedBookshelf);
}
}
I am huge newbie and basing some of this code on intuition. The major flaws that I can think of are calling the addBookDialogue with .show(getChildFragmentManager) and in AddBookDialogue file setting the builder to getParentFragment.getActivity This probably isn't the correct approach, but I am having difficulties understanding the interactions between fragments. The book object is a simple java class with a constructor and a few setters/getters
So yeah, idk where to problem is, all help appreciated :)
For more reference here is the xml file for the main activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHome">
<fragment
android:id="#+id/fragmentHome"
android:name="com.example.computerscienceiawithtablayout.FragmentHome"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</android.support.constraint.ConstraintLayout>
and here is the xml for the fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHome">
<Button
android:text="#string/Add"
android:textStyle="bold"
android:textColor="#ffffff"
android:background="#drawable/button_states"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="onBigButtonClick"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="480dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="164dp" style="#style/Widget.AppCompat.Button"/>
</android.support.constraint.ConstraintLayout>

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.

RecyclerView wont show anything when everything is already set

I'm currently using a method made by Prabeesh R K from YouTube. I'm currently following all the steps without a miss, and I'm only modifying it a little, but the problem is the RecyclerView in my phone is not showing anything. Moreover, there is an error in log : E/RecyclerView: No adapter attached; skipping layout. Can you please help me resolve this. By the way this is my code
GenreView.java (Activity)
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
/**
* Created by A46CB on 2/21/2016.
*/
public class GenreView extends AppCompatActivity{
RecyclerView rvgenre;
GenreAdapter adaptergenre;
RecyclerView.LayoutManager genrelayoutmanager;
String[] judulgenre;
int []imgres = {R.drawable.w06, R.drawable.w100, R.drawable.w102, R.drawable.w144, R.drawable.w173,
R.drawable.w179, R.drawable.w182, R.drawable.w36, R.drawable.w77, R.drawable.w79, R.drawable.w93,
R.drawable.w97};
ArrayList<GenreContent> arrayList = new ArrayList<GenreContent>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_genre);
rvgenre = (RecyclerView)findViewById(R.id.genre_recycler_view);
rvgenre.setHasFixedSize(true);
judulgenre = getResources().getStringArray(R.array.genre_title);
int i = 0;
for(String name : judulgenre)
{
GenreContent genrecontent = new GenreContent(imgres[i],judulgenre[i]);
arrayList.add(genrecontent);
i++;
}
genrelayoutmanager = new GridLayoutManager(this, 2);
rvgenre.setLayoutManager(genrelayoutmanager);
adaptergenre = new GenreAdapter(arrayList);
rvgenre.setAdapter(adaptergenre);
}
}
GenreAdapter.Java (Adapter)
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;
/**
* Created by A46CB on 2/21/2016.
*/
public class GenreAdapter extends RecyclerView.Adapter<GenreAdapter.GenreRecyclerViewHolder> {
private ArrayList<GenreContent> arrayList = new ArrayList<GenreContent>();
public GenreAdapter(ArrayList<GenreContent> arrayList)
{
this.arrayList = arrayList;
}
#Override
public GenreRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.genre_layout, parent, false);
GenreRecyclerViewHolder grvh = new GenreRecyclerViewHolder(view);
return grvh;
}
#Override
public void onBindViewHolder(GenreRecyclerViewHolder holder, int position) {
GenreContent genreContent = arrayList.get(position);
holder.imgView.setImageResource(genreContent.getImg());
holder.tvgenre.setText(genreContent.getTitle());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class GenreRecyclerViewHolder extends RecyclerView.ViewHolder {
ImageView imgView;
TextView tvgenre;
public GenreRecyclerViewHolder (View view){
super (view);
imgView = (ImageView)view.findViewById(R.id.genrepic);
tvgenre = (TextView)view.findViewById(R.id.titlegenre);
}
}
}
GenreContent.java
public class GenreContent {
private int img;
private String title;
public GenreContent(int img, String title){
this.setImg(img);
this.setTitle(title);
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
My Layout
TabGenre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/genre_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
GenreLayout.xml (Custom Layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dip"
android:orientation="vertical">
<ImageView
android:layout_width="160dp"
android:layout_height="120dp"
android:src="#drawable/bgheader"
android:id="#+id/genrepic"/>
<TextView
android:id="#+id/titlegenre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mystery"
android:layout_marginTop="-5dp"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
You should change this line
adaptergenre = new GenreAdapter(new ArrayList<>(arrayList));
to
adaptergenre = new GenreAdapter(arrayList);
There is new need to create new ArrayList

Categories

Resources