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
Related
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();
}
}
}
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");
i am working in PopularMovies Project that i used the movies DB
and i was successful fetch the data from the API but when i click the item in RecyclerView it doesn't work.
I have followed the tutorial for udacity
PopularMovies-issue
there is the link of the source code
and this is the adapter
What should I do?
package com.popmov.popmov.popmov
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.popmov.popmov.popmov.data.Movie;
import com.squareup.picasso.Picasso;
class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder> {
private final Context context;
private Movie[] moviesData;
public static final String BASE_URL_IMAGE = "http://image.tmdb.org/t/p/w342";
private final MoviesAdapterOnClickHandler moviesAdapterOnClickHandler;
public interface MoviesAdapterOnClickHandler {
void onItemClickListener(int id, String title, String imageUrl, String synopsis, double rating, String releaseDate);
}
public MoviesAdapter(MoviesAdapterOnClickHandler clickHandler,Context context) {
moviesAdapterOnClickHandler = clickHandler;
this.context=context;
}
public class MoviesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final ImageView imageView;
public MoviesViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view_movie);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
int id = moviesData[adapterPosition].getId();
String title = moviesData[adapterPosition].getTitle();
String imageUrl = moviesData[adapterPosition].getImageUrl();
String synopsis = moviesData[adapterPosition].getSynopsis();
double rating = moviesData[adapterPosition].getRating();
String releaseDate = moviesData[adapterPosition].getReleaseDate();
moviesAdapterOnClickHandler.onItemClickListener(id, title, imageUrl, synopsis, rating, releaseDate);
}
}
#Override
public MoviesViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutForItem = R.layout.movies_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutForItem, viewGroup, false);
return new MoviesViewHolder(view);
}
#Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
String path = BASE_URL_IMAGE + moviesData[position].getImageUrl();
Picasso.get()
.load(path)
.placeholder(R.mipmap.poster)
.into(holder.imageView);
}
#Override
public int getItemCount() {
if (null == moviesData) {
return 0;
} else {
return moviesData.length;
}
}
}
In your movies_list_item.xml make ImageView clickable to false
android:clickable="false"
As your ImageView clickable property was set to true so your ImageView are absorbing the ClickListener
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";
}
}
I have a realm database model which i want to display in arecyclerview,
every row in the database model have a String name,int age and a boolean favourite,when i try to save the boolean value in the RecyclerviewAdapter
by using an interface but i gjava.lang.NullPointerException: Attempt to invoke virtual method 'void io.realm.Realm.beginTransaction()' on a null object reference
this the model
public class person extends RealmObject implements{
#PrimaryKey
private String name;
private String job;
private boolean favourite;
private String image;
public AuthorInfo(String image, String job, String name, boolean favoutite) {
this.image = image;
this.job = job;
this.name = name;
this.favourite = favourite;
}
public AuthorInfo() {
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFavourite() {
return favourite;
}
public void setFavourite(boolean favourite) {
this.favourite = favourite;
}
}
this is the interface
public interface ItemClickListener {
void onItemClick(View view,int position);}
and this the recyclerview adapter
public class PersonAdapter extends RecyclerView.Adapter<AuthorAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Realm mRealm;
private RealmResults<AuthorInfo> results;
public PersonAdapter(Context context, RealmResults<AuthorInfo> realmResults) {
inflater = LayoutInflater.from(context);
results = realmResults;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
AuthorInfo current = results.get(position);
holder.name.setText(current.getName());
holder.job.setText(current.getJob());
holder.setClickListener(new ItemClickListener() {
mRealm.beginTransaction();
#Override
public void onItemClick(View view, int position) {
CheckBox chk= (CheckBox) view;
if (chk.isChecked()){
results.get(position).setFavourite(true);
}
else if (!chk.isChecked()){
results.get(position).setFavourite(false);
}
}
mRealm.commitTransaction();
notifyItemChanged(position)
});
}
#Override
public int getItemCount() {
return results.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
CheckBox checkbox;
ItemClickListener itemclicklistener;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_job);
checkbox = (CheckBox) itemView.findViewById(R.id.checkbox);
checkbox.setOnClickListener(this);
}
public void setClickListener(ItemClickListener ic) {
this.itemclicklistener = ic;
}
#Override
public void onClick(View view) {
this.itemclicklistener.onItemClick(view,getAdapterPosition());
}
}
}
so and ideas?!