I'm having trouble with some characters when searching within the app - java

I bought a movie app from Codecanyon. The support team screwed up, they can't fix the problem. I'm having trouble with letters like ç, ş, ğ, ü (Space) while searching for movies in the app. When I add a space between a two-word movie, all movies come off the screen.
https://youtube.com/shorts/Z9SOkbIa5kk
Home.java
Searchlistaddepter.java
Searchlist.java
Below
----------------------------------------------------------------------------
HOME.java
---------------------------------------------------------------------------
void searchContent(String text) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.GET, AppConfig.url +"searchContent/"+text+"/"+onlyPremium, response -> {
if(!response.equals("No Data Avaliable") ) {
JsonArray jsonArray = new Gson().fromJson(response, JsonArray.class);
List<SearchList> searchList = new ArrayList<>();
for (JsonElement r : jsonArray) {
JsonObject rootObject = r.getAsJsonObject();
int id = rootObject.get("id").getAsInt();
String name = rootObject.get("name").getAsString();
String year = "";
if(!rootObject.get("release_date").getAsString().equals("")) {
year = getYearFromDate(rootObject.get("release_date").getAsString());
}
String poster = rootObject.get("poster").getAsString();
int type = rootObject.get("type").getAsInt();
int status = rootObject.get("status").getAsInt();
int contentType = rootObject.get("content_type").getAsInt();
if (status == 1) {
searchList.add(new SearchList(id, type, name, year, poster, contentType));
}
}
RecyclerView searchLayoutRecyclerView = findViewById(R.id.Search_Layout_RecyclerView);
SearchListAdepter myadepter = new SearchListAdepter(context, searchList);
searchLayoutRecyclerView.setLayoutManager(new GridLayoutManager(context, 3));
searchLayoutRecyclerView.setAdapter(myadepter);
} else {
View bigSearchLottieAnimation = findViewById(R.id.big_search_Lottie_animation);
RecyclerView searchLayoutRecyclerView = findViewById(R.id.Search_Layout_RecyclerView);
bigSearchLottieAnimation.setVisibility(View.VISIBLE);
searchLayoutRecyclerView.setVisibility(View.GONE);
}
}, error -> {
// Do nothing because There is No Error if error It will return 0
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("x-api-key", AppConfig.apiKey);
return params;
}
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put("search",text);
params.put("onlypremium", String.valueOf(onlyPremium));
return params;
}
};
queue.add(sr);
}
---------------------------------------------------------
SEARCHLİSTADDEPTER.Java
----------------------------------------------------------
package com.xxxx.android.adepter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
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.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.xxxx.android.AppConfig;
import com.xxxx.android.R;
import com.xxxx.android.MovieDetails;
import com.xxxx.android.list.SearchList;
import com.xxxx.android.WebSeriesDetails;
import java.util.List;
public class SearchListAdepter extends RecyclerView.Adapter<SearchListAdepter.MyViewHolder> {
private Context mContext;
private List<SearchList> mData;
Context context;
public SearchListAdepter(Context mContext, List<SearchList> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public SearchListAdepter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(AppConfig.contentItem,parent,false);
return new SearchListAdepter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchListAdepter.MyViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.setTitle(mData.get(position));
holder.setYear(mData.get(position));
holder.setImage(mData.get(position));
holder.IsPremium(mData.get(position));
holder.Movie_Item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mData.get(position).getContent_Type() == 1) {
Intent intent = new Intent(mContext, MovieDetails.class);
intent.putExtra("ID", mData.get(position).getID());
mContext.startActivity(intent);
} else if(mData.get(position).getContent_Type() == 2) {
Intent intent = new Intent(mContext, WebSeriesDetails.class);
intent.putExtra("ID", mData.get(position).getID());
mContext.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Title;
TextView Year;
ImageView Thumbnail;
View Premium_Tag;
CardView Movie_Item;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Title = (TextView) itemView.findViewById(R.id.Movie_list_Title);
Year = (TextView) itemView.findViewById(R.id.Movie_list_Year);
Thumbnail = (ImageView) itemView.findViewById(R.id.Movie_Item_thumbnail);
Premium_Tag = (View) itemView.findViewById(R.id.Premium_Tag);
Movie_Item = itemView.findViewById(R.id.Movie_Item);
}
void IsPremium(SearchList type) {
if(type.getType() == 1) {
Premium_Tag.setVisibility(View.VISIBLE);
} else {
Premium_Tag.setVisibility(View.GONE);
}
}
void setTitle(SearchList title_text) {
Title.setText(title_text.getTitle());
}
void setYear(SearchList year_text) {
Year.setText(year_text.getYear());
}
void setImage(SearchList Thumbnail_Image) {
Glide.with(context)
.load(Thumbnail_Image.getThumbnail())
.placeholder(R.drawable.thumbnail_placeholder)
.into(Thumbnail);
}
}
}
------------------------------------------
SEARCHLİST.Java
---------------------------------------
package com.xxxx.android.list;
public class SearchList {
private int ID;
private int Type;
private String Title;
private String Year;
private String Thumbnail;
private int Content_Type;
public SearchList(int ID, int type, String title, String year, String thumbnail, int content_Type) {
this.ID = ID;
Type = type;
Title = title;
Year = year;
Thumbnail = thumbnail;
Content_Type = content_Type;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getType() {
return Type;
}
public void setType(int type) {
Type = type;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getYear() {
return Year;
}
public void setYear(String year) {
Year = year;
}
public String getThumbnail() {
return Thumbnail;
}
public void setThumbnail(String thumbnail) {
Thumbnail = thumbnail;
}
public int getContent_Type() {
return Content_Type;
}
public void setContent_Type(int content_Type) {
Content_Type = content_Type;
}
public void onResponse(String response) {
try{ byte[] u = response.toString().getBytes("ISO-8859-1");
response = new String(u, "UTF-8");
}
catch (Exception e){
e.printStackTrace();
}
}
}

Related

How to get the context of a item in Recycler View

I am retrieving Cloud Firesstore data in (Modelo) and I'm trying to pass these variables from the constructor "Modelo" to fragment (DescDenuncia) using a adapter (Adapter) but to do that I need to get the context to pass using the .getSupportFragmentManager() I've already tried use "AppCompatActivity activity = (AppCompatActivity) view.getContext();", but my app crashes every time, and is necessary to use a Context in the getSupportFragmentManager() to it works. I truly don't know what I should do, please someone answer me.
Modelo
package com.example.safe;
public class Modelo {
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
public Modelo() {
}
public Modelo(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSetor() {
return setor;
}
public void setSetor(String setor) {
this.setor = setor;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getRisco() {
return risco;
}
public void setRisco(String risco) {
this.risco = risco;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getPrazo() {
return prazo;
}
public void setPrazo(String prazo) {
this.prazo = prazo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getResolucao() {
return resolucao;
}
public void setResolucao(String resolucao) {
this.resolucao = resolucao;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
Adapter
package com.example.safe;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
//Vinculando o reclycler view ao firestore
public class Adapter extends FirestoreRecyclerAdapter<Modelo, Adapter.myviewholder> {
public Adapter(#NonNull FirestoreRecyclerOptions<Modelo> options) {
super(options);
}
//Sobrescrevendo o método
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull final Modelo model) {
//Associando os itens do atalho ocorrências
holder.IDText.setText(model.getID());
holder.tipoText.setText(model.getTipo());
Glide.with(holder.img1.getContext()).load(model.getImg()).into(holder.img1);
///////////////////////////////////////THE PROBLEM IS HERE///////////////////////////////////////////
holder.RLAYOUT.setOnClickListener(new View. OnClickListener() {
#Override
public void onClick(View view) {
.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
model.getEmpresa(),
model.getArea(),
model.getSetor(),
model.getTipo(),
model.getRisco(),
model.getImg(),
model.getData(),
model.getPrazo(),
model.getDesc(),
model.getResolucao(),
model.getID()
)).addToBackStack(null).commit();
}
});
//////////////////////////////////////////////////////////////////////////////////////////////////////
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view);
}
//Coneção do reclycler view com essa classe
public class myviewholder extends RecyclerView.ViewHolder {
//Variáveis do modelo atalho
TextView tipoText, IDText;
RelativeLayout RLAYOUT;
ImageView img1;
private Context context;
//Associando os objetos ao modelo atalho
public myviewholder(#NonNull View itemView) {
super(itemView);
tipoText = itemView.findViewById(R.id.txtTipo);
img1 = itemView.findViewById(R.id.imageView);
IDText = itemView.findViewById(R.id.txtModeloID);
RLAYOUT = itemView.findViewById(R.id.RLlayout);
}
}
}
Add a Context parameter in your myviewholder constructor that will accept an additional context argument
public class myviewholder extends RecyclerView.ViewHolder {
private Context context;
...
...
public myviewholder(#NonNull View itemView, Context context) {
super(itemView);
this.context = context
}
and in your onCreateViewHolder simply call parent.getContext() and pass it to the construction of the view holder.
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view, parent.getContext()); // add <- this
Also please practice naming classes with Uppercase Initials

I continuously got this error "com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type "

I'm trying to retrieve data from FireBase by using ReyclerView and CardView. When I try to run my system, it crashes every time. I think it's about the Datatype problem. But I can't find a solution.
FirebaseDatabaseHelper.java
package com.example.second_msma;
import androidx.annotation.NonNull;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class FirebaseDatabaseHelper {
private FirebaseDatabase mDatabase;
private DatabaseReference mRefferencevessel;
private List<VesselBook> vessel = new ArrayList<>();
public interface DataStatus{
void DataIsLoaded(List<VesselBook> vessel, List<String> keys);
void DataIsInserted();
void DataIsUpdated();
void DataIsDeleted();
}
public FirebaseDatabaseHelper(){
mDatabase = FirebaseDatabase.getInstance();
mRefferencevessel = mDatabase.getReference("Bookingvessel");
}
public void readVesselBook(final DataStatus dataStatus){
mRefferencevessel.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
vessel.clear();
List<String> keys = new ArrayList<>();
for (DataSnapshot keyNode : dataSnapshot.getChildren()){
keys.add(keyNode.getKey());
VesselBook vesselBook = keyNode.getValue(VesselBook.class);
vessel.add(vesselBook);
}
dataStatus.DataIsLoaded(vessel,keys);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Here where I always got the errorVesselBook vesselBook = keyNode.getValue(VesselBook.class);
This is my VesselBook.class
package com.example.second_msma;
public class VesselBook {
private String date;
private String destination;
private String origin;
private String type;
private String weight;
private String id;
public VesselBook() {
}
public VesselBook(String destination, String origin, String type, String weight) {
this.destination = destination;
this.origin = origin;
this.type = type;
this.weight = weight;
}
public VesselBook(String destination, String origin, String type) {
this.destination = destination;
this.origin = origin;
this.type = type;
}
public VesselBook(String date, String destination, String origin, String type, String weight, String id) {
this.date = date;
this.destination = destination;
this.origin = origin;
this.type = type;
this.weight = weight;
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
This is my RecyclerViewed_Config.java
package com.example.second_msma;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewed_Config {
private Context mContext;
private BooksAdapter mBookAdapter;
public void setConfig(RecyclerView recyclerView, Context context, List<VesselBook> vesselBook, List<String> keys){
mContext = context;
mBookAdapter = new BooksAdapter(vesselBook,keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(mBookAdapter);
}
class BookItemView extends RecyclerView.ViewHolder{
private TextView mTitle;
private TextView mAuthor;
private TextView mISBN;
private TextView mCategory;
private String key;
public BookItemView(ViewGroup parent){
super(LayoutInflater.from(mContext).inflate(R.layout.user_list, parent, false));
mTitle = (TextView) itemView.findViewById(R.id.tvName);
mAuthor = (TextView) itemView.findViewById(R.id.tvPhone);
mCategory = (TextView) itemView.findViewById(R.id.tvAddress);
mISBN = (TextView) itemView.findViewById(R.id.tvISBN);
}
public void bind (VesselBook vesselBook, String key){
mTitle.setText(vesselBook.getOrigin());
mAuthor.setText(vesselBook.getDestination());
mCategory.setText(vesselBook.getWeight());
mISBN.setText(vesselBook.getType());
this.key = key;
}
}
class BooksAdapter extends RecyclerView.Adapter<BookItemView>{
private List<VesselBook> mBookList;
private List<String> mKeys;
public BooksAdapter(List<VesselBook> mBookList, List<String> mKeys) {
this.mBookList = mBookList;
this.mKeys = mKeys;
}
#NonNull
#Override
public BookItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new BookItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull BookItemView holder, int position) {
holder.bind(mBookList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mBookList.size();
}
}
}
This is where my data will be inserted in firebase
public class BookingVessel extends AppCompatActivity {
EditText etDate,weight;
DatabaseReference reff;
BookngGetter bookingvessel;
Button book;
FirebaseDatabase db;
int maxid =0;
Spinner mySpinner;
ArrayAdapter<String> myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.booking_vessel);
book = findViewById(R.id.book);
mySpinner = findViewById(R.id.spinner);
final Spinner mySpinner1 = findViewById(R.id.spinner2);
final Spinner mySpinner2 = findViewById(R.id.spinner3);
weight = findViewById(R.id.weight);
bookingvessel= new BookngGetter();
reff = db.getInstance().getReference().child("Bookingvessel");
myAdapter = new ArrayAdapter<String>(BookingVessel.this,
android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.origin) );
myAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mySpinner.setAdapter(myAdapter);
ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(BookingVessel.this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.destination));
myAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mySpinner1.setAdapter(myAdapter1);
ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(BookingVessel.this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.shipment));
myAdapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mySpinner2.setAdapter(myAdapter2);
etDate = findViewById(R.id.et_date);
Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(
BookingVessel.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
String date = day + "/" + month + "/" + year;
etDate.setText(date);
}
}, year, month, day);
datePickerDialog.show();
}
});
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
maxid = (int) dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String origin = mySpinner.getSelectedItem().toString().trim();
String destination = mySpinner1.getSelectedItem().toString().trim();
String type = mySpinner2.getSelectedItem().toString().trim();
String date = etDate.getText().toString().trim();
bookingvessel.setOrigin(mySpinner.getSelectedItem().toString());
bookingvessel.setDestination(destination);
bookingvessel.setDate(date);
bookingvessel.setType(type);
bookingvessel.setWeight(weight.getText().toString().trim());
Toast.makeText(BookingVessel.this,"Booking Accepted", Toast.LENGTH_LONG).show();
reff.child(String.valueOf(maxid+1)).setValue(bookingvessel);
openFirst();
}
});
}
public void openFirst(){
Intent intent = new Intent(this, First.class);
startActivity(intent);
}
}
This is my database(Firebase)

How to set an OnClickListener on a recyclerview not depending on the position

I want the onclicklistener method to open the activity which is related to the object:entidad1, entidad2 or entidad3.
The OnRecipe method on the MainActivity.java which i want it to make that if the entidad1 appears it takes me to x activity, and if entidad2 appears to y activity and so, any idea of how to do it, because now it takes me all the time to the activity of the entidad1. I guess it must be related with using priority to decide which to open instead of the position.
That's my Adapter:
package com.test.platos_4;
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.RatingBar;
import android.widget.TextView;
import java.util.List;
public class Adaptador2 extends RecyclerView.Adapter<Adaptador2.ViewHolder>
{
private List<Entidad2> listItems;
private OnRecipeListener mOnRecipeListener;
public Adaptador2(List<Entidad2> listItems, OnRecipeListener onRecipeListener) {
this.listItems = listItems;
this.mOnRecipeListener = onRecipeListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.elemento_lista2, parent, false);
return new ViewHolder(view, mOnRecipeListener);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int position) {
int resource = listItems.get(position).getImgFoto();
String title = listItems.get(position).getTitulo();
String time = listItems.get(position).getTiempo();
int barra = listItems.get(position).getRating();
//int fondo = listItems.get(position).getColorfondo();
viewholder.setData(resource, title, time, barra);
// por si necesito color de fondo viewholder.setData(resource, title, time, barra, fondo);
}
#Override
public int getItemCount() {
return listItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgFoto;
private TextView titulo;
private TextView tiempo;
private RatingBar ratingBar;
//private ImageView colorfondo;
OnRecipeListener onRecipeListener;
public ViewHolder(View itemView, OnRecipeListener onRecipeListener) {
super(itemView);
imgFoto = itemView.findViewById(R.id.imgFoto);
titulo = itemView.findViewById(R.id.tvTitulo);
tiempo = itemView.findViewById(R.id.tvTiempo);
ratingBar = itemView.findViewById(R.id.ratingBarVerd);
//colorfondo = itemView.findViewById(R.id.colorfondo);
this.onRecipeListener = onRecipeListener;
itemView.setOnClickListener(this);
}
//por si necesito color de fondo private void setData(int resource, String title, String time, int barra, int fondo){
private void setData(int resource, String title, String time, int barra){
imgFoto.setImageResource(resource);
titulo.setText(title);
tiempo.setText(time);
ratingBar.setRating(barra);
//colorfondo.setImageResource(fondo);
}
#Override
public void onClick(View v) {
onRecipeListener.OnRecipe(getAdapterPosition());
}
}
public interface OnRecipeListener{
void OnRecipe(int priority);
}
}
And that is the MainActivity.java:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
And the Entidad.java:
public class Entidad2 {
private int imgFoto;
private String titulo;
private String tiempo;
private int ratingBar;
private int priority;
private int d;
public Entidad2(int imgFoto, String titulo, String tiempo, int ratingBar, int priority) {
this.imgFoto = imgFoto;
this.titulo = titulo;
this.tiempo = tiempo;
this.ratingBar = ratingBar;
this.priority = priority;
}
public int getImgFoto() {
return imgFoto;
}
public String getTitulo() {
return titulo;
}
public String getTiempo() {
return tiempo;
}
public int getRating() { return ratingBar; }
public int getPriority() {
return priority;
}
}
Please help me to solve the problem and if you need more information just tell me i will post it.
You are trying to differentiate your items by Priority but you are passing item position from your adapter to your activity. You need to pass clicked item's Priority instead of its position. I have changed your Adaptor2 class
package com.test.platos_4;
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.RatingBar;
import android.widget.TextView;
import java.util.List;
public class Adaptador2 extends RecyclerView.Adapter<Adaptador2.ViewHolder>
{
private List<Entidad2> listItems;
private OnRecipeListener mOnRecipeListener;
public Adaptador2(List<Entidad2> listItems, OnRecipeListener onRecipeListener) {
this.listItems = listItems;
this.mOnRecipeListener = onRecipeListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.elemento_lista2, parent, false);
return new ViewHolder(view, mOnRecipeListener);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int position) {
Entidad2 entidad = listItems.get(position);
int resource = entidad.getImgFoto();
String title = entidad.getTitulo();
String time = entidad.getTiempo();
int barra = entidad.getRating();
final int priority = entidad.getPriority();
//int fondo = listItems.get(position).getColorfondo();
viewholder.setData(resource, title, time, barra);
//You can pass the clicked item's priority back to your activity like this
viewholder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnRecipeListener.OnRecipe(priority);
}
});
// por si necesito color de fondo viewholder.setData(resource, title, time, barra, fondo);
}
#Override
public int getItemCount() {
return listItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgFoto;
private TextView titulo;
private TextView tiempo;
private RatingBar ratingBar;
//private ImageView colorfondo;
OnRecipeListener onRecipeListener;
public ViewHolder(View itemView, OnRecipeListener onRecipeListener) {
super(itemView);
imgFoto = itemView.findViewById(R.id.imgFoto);
titulo = itemView.findViewById(R.id.tvTitulo);
tiempo = itemView.findViewById(R.id.tvTiempo);
ratingBar = itemView.findViewById(R.id.ratingBarVerd);
//colorfondo = itemView.findViewById(R.id.colorfondo);
//This is useless
//this.onRecipeListener = onRecipeListener;
}
//por si necesito color de fondo private void setData(int resource, String title, String time, int barra, int fondo){
private void setData(int resource, String title, String time, int barra){
imgFoto.setImageResource(resource);
titulo.setText(title);
tiempo.setText(time);
ratingBar.setRating(barra);
//colorfondo.setImageResource(fondo);
}
#Override
public void onClick(View v) {
}
}
public interface OnRecipeListener{
void OnRecipe(int priority);
}
}

Can not transfer an object by using Intent and Parcelable

I am making a news app using Firebase. I have a problem when I try to transfer an object to another activity.
An exception:
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fx.fibi/com.example.fx.fibi.DetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.fx.fibi.News.getTitle()' on a null object reference.
Here is my code:
MainActivity:
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
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.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
Query query = FirebaseDatabase.getInstance().getReference().child("Global");
FirebaseRecyclerOptions<News> options = new FirebaseRecyclerOptions.Builder<News>()
.setQuery(query, News.class).build();
final FirebaseRecyclerAdapter<News,NewsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<News,
NewsViewHolder>(options) {
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_row, parent, false);
return new NewsViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull NewsViewHolder holder, int position, #NonNull News model) {
holder.setTitle(model.getTitle());
holder.setDesc(model.getDesc());
holder.setImage(getApplicationContext(), model.getImage());
holder.setOnClickListener(new NewsViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Item clicked at " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("news", position);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onItemLongClick(View view, int position) {
}
});
}
};
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
}
DetailActivity (this class gets NullPointerException at "title.setText(news.getTitle());"
public class DetailActivity extends AppCompatActivity {
TextView title, desc;
ImageView imageView;
News news;
String titleString, descString, image;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initCollapsingToolbar();
imageView = findViewById(R.id.thumbnail_image_header);
title = findViewById(R.id.detail_title);
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("news")) {
news = getIntent().getParcelableExtra("news");
title.setText(news.getTitle());
desc.setText(news.getDesc());
Picasso.with(mContext).load(image).into(imageView);
}
}
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbarLayout =
(CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbarLayout.setTitle(" ");
isShow = false;
}
}
});
}
}
Model:
public class News implements Parcelable {
private String title;
private String desc;
private String image;
public News(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public News (Parcel in) {
String[] data = new String[3];
in.readStringArray(data);
title = data[0];
desc = data[1];
image = data[2];
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public News() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {title, desc, image});
}
public static final Parcelable.Creator<News> CREATOR = new Parcelable.Creator<News>() {
#Override
public News createFromParcel(Parcel source) {
return new News(source);
}
#Override
public News[] newArray(int size) {
return new News[size];
}
};
}
Sorry if my question seems to be foolish, this is my first full app.
Thanks!
I added an object list List <News> newsList and changed method onItem click to:
if (position != RecyclerView.NO_POSITION) {
News clickedDataItem = newsList.get(position);
Toast.makeText(MainActivity.this, "Item clicked at " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("news", clickedDataItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
But now i get "java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference"
You can implement java Serializable interface instead of implementing Parcelable in your model class as shown below
public class News implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String title;
private String desc;
private String image;
public News(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public News() {
//empty contructor neeeded
}
#Overide
public String toString(){
return super.toString();
}
}
Then you can pass the object the intent like this
News news = new News("title", "desc", "image");
Intent intent = new Intent(StartActivity.this, TargetActivity.class);
intent.putExtra("news", news);
startActivity(intent);
In order to get the object from the intent, you need to cast New class into the Intent results as shown below.
News news = (News)getIntent().getSerializableExtra("news");
In your onBindViewHolder, you put wrong data.
intent.putExtra("news", position); // position is int
which position is an int, put the News object at the position instead.
You can set the value to the intent ....
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = "value";
i.putExtra("STRING_I_NEED", strName);
startActivity(i);
You can retrive the value in second activity..........
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
news = getIntent().getIntExtra("news");

Passing List Info to New Activity

I'm building on a tutorial I did in which I created a RecyclerView screen with cards with selectable options. I want one of the selectable options to bring the user to a new activity that has more information & options about the card they selected. My problem is when I try to transfer traits of that specific card to the next SlideViewActivity.java activity I am unable to successfully do so. I tried transforming my list into an array then sending that, but I keep obtaining a null value (which could be due to my syntax for all I know).
Any clarification & guidance would be appreciated, let me know if you would want any of the other code as well.
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private Context mContext;
private List<Properties> dogList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
public Adapter(Context mContext, List<Properties> dogList) {
this.mContext = mContext;
this.dogList = dogList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Properties dog = dogList.get(position);
holder.title.setText(dog.getName());
// loading dog cover using Glide library
Glide.with(mContext).load(dog.getThumbnail()).into(holder.thumbnail);
holder.overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupMenu(holder.overflow);
}
});
}
/**
* Showing popup menu when tapping on icon
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_add_favourite:
Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_more_info:
Intent slideStart = new Intent(mContext, SlideViewActivity.class);
String[] dogArray = new String[dogList.size()];
slideStart.putExtra("List", dogArray);
Log.e("putting extra", String.valueOf(dogArray[0]));
//TODO:MAKE NAME TRANSFERS WORK
mContext.startActivity(slideStart);
return true;
default:
}
return false;
}
}
Adding Properties.java:
public class Properties {
private String name;
private String info;
private int thumbnail;
public Properties() {
}
public Properties(String name, String info, int thumbnail) {
this.name = name;
this.info = info;
this.thumbnail = thumbnail;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void getInfo(String info) {
this.info = info;
}
public int getThumbnail() {
return thumbnail;
}
public void setThumbnail(int thumbnail) {
this.thumbnail = thumbnail;
}
}
You can pass ArrayList<T>, if T is Serializable.
for example:
ArrayList<String> list = new ArrayList<String>();
intent.putExtra("list", list);
use getSerializableExtra to extract data
Your array is dogList.size()-d null values.
String[] dogArray = new String[dogList.size()];
slideStart.putExtra("List", dogArray);
You should see null logged here.
Log.e("putting extra", String.valueOf(dogArray[0]));
It's not clear what type of class you have for Properties, but if it is your class, and not java.util.Properties, you should implement Parcelable on that class, then you'd have
intent.putParcelableArrayList("List", dogList)
(Tip: You should rename that class to Dog to avoid confusion for yourself and others)
But if you are just worried about getting null, case matters. You put a key="List", so make sure you aren't getting key="list" or anything else but "List"
Two ways possible for that::
First
While Sending the list using intent::
Intent slideStart = new Intent(mContext, SlideViewActivity.class);
slideStart.putExtra("List", dogList);
mContext.startActivity(slideStart);
In This just pass the list as is it is ::
But your class Properties should be implements "Serializable"
Now while receiving that intent ::
ArrayList<Properties> dogList =(ArrayList<Properties>) getIntent().getExtras().getSerializable("List");
Second way :: using Library
One library is there for converting string to arraylist & vice versa ,
compile 'com.google.code.gson:gson:2.4'
So, for this while sending list convert that list to string like ::
Type listType = new TypeToken<List<Properties>>() {
}.getType();
String listString=new Gson().toJson(dogList,listType );
pass this simple as string with intent:::
Intent slideStart = new Intent(mContext, SlideViewActivity.class);
slideStart.putExtra("List", listString);
mContext.startActivity(slideStart);
And while getting it back in other activity::
String listString =getIntent().getExtras().getString("List");
Type listType = new TypeToken<List<Properties>>() {}.getType();
List<Properties> list=new Gson().fromJson(listString, listType);
Tell me if need more help..
I have done a similar project I will share my code. Please take a look and if have doubts ping me
DataAdapter.java
package com.example.vishnum.indiavideo;
import android.content.Context;
import android.content.Intent;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
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 com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}
Video_Details.java
package com.example.vishnum.indiavideo;
public class Video_Details {
private String id;
private String v_id;
private String title;
private String thumb;
public String getId() {
return id;
}
public String getV_id() {
return v_id;
}
public String getTitle() {
return title;
}
public String getThumb() {
return (Constants.urlvideo+v_id+"/0.jpg");
}
public void setId(String id) {
this.id = id;
}
public void setV_id(String v_id) {
this.v_id = v_id;
}
public void setTitle(String title) {
this.title = title;
}
public void setThumb(String v_id) {
this.thumb =Constants.urlvideo+v_id+"/0.jpg";
}
}

Categories