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");
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 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);
}
}
SmsAdapter.java
package com.s4starb4boy.smstopdf.adapter;
import android.content.Context;
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.TextView;
import com.s4starb4boy.smstopdf.R;
import com.s4starb4boy.smstopdf.model.SMS;
import java.util.List;
public class SmsAdapter extends RecyclerView.Adapter<SmsAdapter.SmsViewHolder> {
private static final String TAG = SmsAdapter.class.getSimpleName() ;
private List<SMS> smsList;
private LayoutInflater mInflater;
public SmsAdapter(Context context, List<SMS> smsList) {
this.smsList = smsList;
this.mInflater = LayoutInflater.from(context);
}
#Override
public SmsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder");
View view = mInflater.inflate(R.layout.sms_list, parent, false);
SmsViewHolder holder = new SmsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(SmsViewHolder holder, int position) {
Log.i(TAG, "onBindViewHolder" + position);
SMS currentObj = smsList.get(position);
holder.setData(currentObj, position);
}
#Override
public int getItemCount() {
return smsList.size();
}
class SmsViewHolder extends RecyclerView.ViewHolder{
TextView tvPhoneNo;
TextView tvsmsBody;
int position;
SMS current;
public SmsViewHolder(View itemView) {
super(itemView);
tvPhoneNo = (TextView) itemView.findViewById(R.id.tvPhoneNo);
tvsmsBody = (TextView) itemView.findViewById(R.id.tvMessageBody);
}
public void setData(SMS current, int position) {
this.tvPhoneNo.setText(current.getPhoneNo());
this.tvsmsBody.setText(current.getSmsBody());
this.current =current;
this.position = position;
}
}
}
SMS.java
public class SMS extends AppCompatActivity{
private String phoneNo;
private String smsBody;
public SMS(String phoneNo, String smsBody) {
this.phoneNo = phoneNo;
this.smsBody = smsBody;
}
public SMS() {
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getSmsBody() {
return smsBody;
}
public void setSmsBody(String smsBody) {
this.smsBody = smsBody;
}
public static ArrayList<String> getSMS(){
ArrayList<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, null);
while (cur != null && cur.moveToNext()) {
String address = cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
if (cur != null) {
cur.close();
}
return sms;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int READ_SMS_PERMISSIONS_REQUEST = 1;
private static final int READ_CONTACTS_PERMISSIONS_REQUEST = 1;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpToolbar();
setUpRecyclerView();
}
private void setUpRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
SmsAdapter adapter = new SmsAdapter(this, SMS.getSMS());
recyclerView.setAdapter(adapter);
LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(this);
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
private void setUpToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Navigation Drawer Demo");
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String msg = "";
switch (item.getItemId()) {
case R.id.settings:
msg = "Settings";
break;
case R.id.edit:
msg = "Edit";
break;
case R.id.search:
msg = "Search";
break;
case R.id.exit:
msg = "Exit";
break;
case R.id.delete:
msg = "Delete";
break;
}
Toast.makeText(MainActivity.this, msg + " Clicked", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
Above are all code I want to fetch sms and display them in card view using recycler view. I am repeating here that I am absolutely beginner so please keep this point in your mind while giving me solution I may unable to get your professional hint rather ask me in detail plz.
Try to pass current context object to the SMS class
SmsAdapter adapter = new SmsAdapter(this, SMS.getSMS(this.getApplicationContext()));
and change getSMS to:
public static ArrayList<String> getSMS(Context context){
.....
Cursor cur = context.getContentResolver().query(uriSMSURI, null, null, null, null);
.....
Unfortunately I don't have any Android IDE to test this but it should work.
getContentResolver>>>nonstatic member can not be referenced
This means, you are trying to access non-static member from static context, in case getContentResolver() is non-static method, which you are trying to invoke from static method i.e. getSMS ()
You can do either :
Remove static from getSMS OR add static to getContentResolver
Create an instance of this class to call getContentResolver
I'm trying to visualize a toast inside a fragment by pressing an item of a recycling but I can not see it
Note: There is no error in the log attached to my class
This is my fragment
public class FotoFragment extends Fragment
{
private Cursor cursor;
private int columnIndex;
private static final String TAG = "RecyclerViewExample";
private List<DataPictures> mediaList = new ArrayList<>();
private RecyclerView mRecyclerView;
private MediaRVAdapter adapter;
String type = "";
public FotoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
type = "images";
new MediaAsyncTask().execute(type);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
return view;
}
public class MediaAsyncTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
String type = params[0];
try {
mediaList = new ArrayList<>();
if (type.equalsIgnoreCase("images")) {
result = 1;
}
} catch (Exception e) {
e.printStackTrace();
result = 0;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
adapter = new MediaRVAdapter(getActivity(), mediaList);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Click pressed",Toast.LENGTH_SHORT).show();
}
});
} else {
Log.e(TAG, "Failed to show list");
}
}
}
}
This is my adapter
public class MediaRVAdapter extends RecyclerView.Adapter<MediaListRowHolder> {
private List<DataPictures> itemList;
private Context mContext;
public MediaRVAdapter(Context context, List<DataPictures> itemList) {
this.itemList = itemList;
this.mContext = context;
}
#Override
public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
MediaListRowHolder mh = new MediaListRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
try{
DataPictures item = itemList.get(i);
Uri uri = Uri.fromFile(new File(item.getFilePath()));
if(item.getFileType().equalsIgnoreCase("video")) {
Bitmap bmThumbnail = ThumbnailUtils.
extractThumbnail(ThumbnailUtils.createVideoThumbnail(item.getFilePath(),
MediaStore.Video.Thumbnails.FULL_SCREEN_KIND), 90, 60);
if(bmThumbnail != null) {
mediaListRowHolder.thumbnail.setImageBitmap(bmThumbnail);
}
} else if (item.getFileType().equalsIgnoreCase("audio")) {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(item.getFilePath());
try{
if (mmr != null) {
byte[] art = mmr.getEmbeddedPicture();
Bitmap bmp = BitmapFactory.decodeByteArray(art,0,art.length);
if(bmp != null) {
bmp= ThumbnailUtils.extractThumbnail(bmp,90,60);
mediaListRowHolder.thumbnail.setImageBitmap(bmp);
}
}
}catch (Exception e){
e.printStackTrace();
}
}else {
Picasso.with(mContext).load(uri)
.error(R.drawable.logo_slogan)
.placeholder(R.drawable.logo_slogan)
.centerCrop()
.resize(90, 60)
.into(mediaListRowHolder.thumbnail);
}
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return (null != itemList ? itemList.size() : 0);
}
}
Adapter class adapter
public class MediaListRowHolder extends RecyclerView.ViewHolder {
protected ImageView thumbnail;
protected TextView title;
public MediaListRowHolder(View view) {
super(view);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
this.title = (TextView) view.findViewById(R.id.title);
}
}
solution:
public class MediaListRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView thumbnail;
protected TextView title;
public MediaListRowHolder(View view) {
super(view);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
this.title = (TextView) view.findViewById(R.id.title);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
I think you can do this, such as the following code:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Author:Administrator on 2016/9/2 0002 20:37
* Contact:289168296#qq.com
*/
public abstract class OnItemSelectedListener implements RecyclerView.OnItemTouchListener{
private final GestureDetector mGestureDetector;
public OnItemSelectedListener(Context context){
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener(){
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
public abstract void onItemSelected(RecyclerView.ViewHolder holder, int position);
#Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
if (mGestureDetector.onTouchEvent(e)) {
View touchedView = rv.findChildViewUnder(e.getX(), e.getY());
onItemSelected(rv.findContainingViewHolder(touchedView),
rv.getChildAdapterPosition(touchedView));
}
return false;
}
#Override public void onTouchEvent(RecyclerView rv, MotionEvent e) {
throw new UnsupportedOperationException("Not implemented");
}
#Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
throw new UnsupportedOperationException("Not implemented");
}
}
And then to the RecycleView registration event, the event can be handled:
private RecyclerView grid;
grid.setAdapter(new PhotoAdapter(this, relevantPhotos));
grid.addOnItemTouchListener(new OnItemSelectedListener(MainActivity.this) {
#Override public void onItemSelected(RecyclerView.ViewHolder holder, int position) {
if (!(holder instanceof PhotoViewHolder)) {
return;
}
PhotoItemBinding binding = ((PhotoViewHolder) holder).getBinding();
final Intent intent = getDetailActivityStartIntent(MainActivity.this, relevantPhotos, position, binding);
final ActivityOptions activityOptions = getActivityOptions(binding);
MainActivity.this.startActivityForResult(intent, IntentUtil.REQUEST_CODE,
activityOptions.toBundle());
}
});
PhotoAdapter.java:
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.googlesamples.unsplash.R;
import com.googlesamples.unsplash.data.model.Photo;
import com.googlesamples.unsplash.databinding.PhotoItemBinding;
import com.googlesamples.unsplash.ui.ImageSize;
import java.util.ArrayList;
public class PhotoAdapter extends RecyclerView.Adapter<PhotoViewHolder> {
private final ArrayList<Photo> photos;
private final int requestedPhotoWidth;
private final LayoutInflater layoutInflater;
public PhotoAdapter(#NonNull Context context, #NonNull ArrayList<Photo> photos) {
this.photos = photos;
requestedPhotoWidth = context.getResources().getDisplayMetrics().widthPixels;
layoutInflater = LayoutInflater.from(context);
}
#Override
public PhotoViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
return new PhotoViewHolder((PhotoItemBinding) DataBindingUtil.inflate(layoutInflater,
R.layout.photo_item, parent, false));
}
#Override
public void onBindViewHolder(final PhotoViewHolder holder, final int position) {
PhotoItemBinding binding = holder.getBinding();
Photo data = photos.get(position);
binding.setData(data);
binding.executePendingBindings();
Glide.with(layoutInflater.getContext())
.load(holder.getBinding().getData().getPhotoUrl(requestedPhotoWidth))
.placeholder(R.color.placeholder)
.override(ImageSize.NORMAL[0], ImageSize.NORMAL[1])
.into(holder.getBinding().photo);
}
#Override
public int getItemCount() {
return photos.size();
}
#Override
public long getItemId(int position) {
return photos.get(position).id;
}
}
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";
}
}