Resource$NotFoundException while getting String by resource ID - java

I encountered this error
android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:244)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:3940)
at com.example.android.tourrior.TourAdapter.getView(TourAdapter.java:43)
The error said my problem lies here
TextView address = (TextView) listItemView.findViewById(R.id.address);
if (currentPosition.hasAddress()) {
address.setText(currentPosition.getAddress());
} else {
address.setVisibility(address.GONE);
}
The getAddress method is declared here
public class Tour {
private int mName;
private int mPhoneNumber;
private int mAddress;
private int mOpeningHours;
private int mDescription;
private int mImageResourceId;
private static final int UNAVAILABLE = -1;
public Tour(int name,int address, int description, int phoneNumber, int openingHours, int image) {
mName = name;
mAddress = address;
mDescription = description;
mPhoneNumber = phoneNumber;
mOpeningHours = openingHours;
mImageResourceId = image;
}
public Tour(int name,int description, int openingHours, int image) {
mName = name;
mDescription = description;
mOpeningHours = openingHours;
mImageResourceId = image;
}
public Tour(int name, int address, int openingHours){
mName = name;
mAddress = address;
mOpeningHours = openingHours;
}
public Tour(int name,int address, int description, int openingHours, int phoneNumber) {
mName = name;
mAddress = address;
mDescription = description;
mOpeningHours = openingHours;
mPhoneNumber = phoneNumber;
}
public int getName() {
return mName;
}
public int getAddress() {
return mAddress;
}
public int getDescription() {
return mDescription;
}
public int getOpeningHours() {
return mOpeningHours;
}
public int getPhoneNumber() {
return mPhoneNumber;
}
public int getImageResourceId() {
return mImageResourceId;
}
I tried to change the code in the error line to this
address.setText("" + currentPosition.getAddress());
and it returns 0. I'm making an adapter for 4 children activities, each contains 4 objects with 3 to 6 states (shown above) and one of them is address. This is one of my activity:
public class MallsActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.places);
ArrayList<Tour> tour = new ArrayList<Tour>();
tour.add(new Tour(R.string.mall1_name,R.string.mall1_address,R.string.mall1_opening_hours));
tour.add(new Tour(R.string.mall2_name,R.string.mall2_address,R.string.mall2_opening_hours));
tour.add(new Tour(R.string.mall3_name,R.string.mall3_address,R.string.mall3_opening_hours));
tour.add(new Tour(R.string.mall4_name,R.string.mall4_address,R.string.mall4_opening_hours));
TourAdapter adapter = new TourAdapter(this, tour);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
My adapter until the address view
public class TourAdapter extends ArrayAdapter<Tour> {
public TourAdapter(Context context, ArrayList<Tour> tour) {
super(context, 0, tour);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Tour currentPosition = getItem(position);
TextView name = (TextView) listItemView.findViewById(R.id.name);
name.setText(currentPosition.getName());
TextView description = (TextView) listItemView.findViewById(R.id.description);
if (currentPosition.hasDescription()) {
description.setText(currentPosition.getDescription());
} else {
description.setVisibility(View.GONE);
}
TextView address = (TextView) listItemView.findViewById(R.id.address);
if (currentPosition.hasAddress()) {
address.setText(currentPosition.getAddress());
} else {
address.setVisibility(View.GONE);
}

First, make sure that your getAddress is returning correct "String resource Id".
And for getting String from res id call following:
address.setText(getResources().getString("YOUR_INT_RES_ID"));

Try to simplify your class.
public class Tour {
private int mName;
private int mPhoneNumber;
private int mAddress;
private int mOpeningHours;
private int mDescription;
private int mImageResourceId;
private static final int UNAVAILABLE = -1;
public Tour(int name,int address, int description, int phoneNumber, int openingHours, int image) {
mName = name;
mAddress = address;
mDescription = description;
mPhoneNumber = phoneNumber;
mOpeningHours = openingHours;
mImageResourceId = image;
}
public Tour(int name,int description, int openingHours, int image) {
this(name, 0, description, 0, openingHours, image);
}
public Tour(int name, int address, int openingHours){
this(name, address, 0, 0, openingHours, 0);
}
public Tour(int name,int address, int description, int openingHours, int phoneNumber) {
this(name, address, description, phoneNumber, openingHours, 0);
}
// Getters, setters
}
Then, you should set a breakpoint in the debugger at
Tour currentPosition = getItem(position);
Check each one of your fields of that object. The error states that one of them is returning as 0, or a non-existent ID value.
Note: You can simplify that object adding...
final Resources res = getResources();
final String packageName = getPackageName();
for (int i = 1; i <= 4; i++) {
String resName = "mall"+i;
tour.add(
new Tour(
res.getIdentifier(resName+"_name", "string", packageName),
res.getIdentifier(resName+"_address", "string", packageName),
res.getIdentifier(resName+"_opening_hours", "string", packageName)));
}

The answer lies in where I think was not important and did not post it, here it is
public boolean hasImage(){
return mImageResourceId != UNAVAILABLE;
}
public boolean hasDescription(){
return mDescription != UNAVAILABLE;
}
public boolean hasPhoneNumber(){
return mPhoneNumber != UNAVAILABLE;
}
public boolean hasAddress(){
return mAddress != UNAVAILABLE;
}
}
here is the example for hasDescription method
TextView description = (TextView) listItemView.findViewById(R.id.description);
if (currentPosition.hasDescription()) {
description.setText(currentPosition.getDescription());
} else {
description.setVisibility(View.GONE);
}
What I was trying to do in this section is to check if my object has these fields or not, since they are different from each other. I set the UNAVAILABLE constant to -1 and expect if the ID points to nowhere it will return -1 and erase that field. However, in fact it return 0, making my method useless, since it will never return -1, the field will always exist no matter what. So what I fixed was simply change the UNAVAILABLE constant
private static final int UNAVAILABLE = 0;
And that's all

Related

problem with scrolling up or down of listview

When I try to take all the values of the NumberPicker, it correctly returns the ones in the middle, while the first and last returns only the last one that has been modified between them. I don't understand where I'm wrong.
public class piatto {
String nome;
String Descrizione;
String prezzo;
String immagine;
String tag;
public piatto(String nome, String Descrizione, String prezzo, String immagine, String tag) {
this.nome= nome;
this.Descrizione= Descrizione;
this.prezzo= prezzo;
this.immagine=immagine;
this.tag=tag;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescrizione() {
return Descrizione;
}
public void setDescrizione(String descrizione) {
Descrizione = descrizione;
}
public String getPrezzo() {
return prezzo;
}
public void setPrezzo(String prezzo) {
this.prezzo = prezzo;
}
public String getImmagine() {
return immagine;
}
public void setImmagine(String immagine) {
this.immagine = immagine;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
this is my adapeter
public class ProductListAdapterforListView extends BaseAdapter {
private Context mContext;
private List<piatto> mProductList;
public ProductListAdapterforListView(Context mContext, List<piatto> mProductList) {
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public piatto getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listitemview ;
if (convertView==null){
listitemview = View.inflate(mContext, R.layout.row_data_list, null);
ImageView i = (ImageView) listitemview.findViewById(R.id.imagepiatto);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) listitemview.findViewById(R.id.number_picker);
TextView n=(TextView) listitemview.findViewById(R.id.namepiatto);
TextView p=(TextView) listitemview.findViewById(R.id.prezzopiatto);
n.setText(mProductList.get(position).getNome());
p.setText(mProductList.get(position).getPrezzo()+" €");
Picasso.get().load(mProductList.get(position).getImmagine()).into(i);
} else {
listitemview=convertView;
}
return listitemview;
}
}
And this is my Java class where I get the values of the NumberPicker of each Item
#Override
public void onClick(View view) {
if (view.getId()==R.id.buttonnext){
Float totale = (float) 0.0;
String listapiatti="";
for (int i = 0; i < listView.getChildCount(); i++) {
view = listView.getChildAt(i);
TextView n = view.findViewById(R.id.namepiatto);
String nome = n.getText().toString();
TextView p = view.findViewById(R.id.prezzopiatto);
String pricestr = p.getText().toString();
String[] prezzo = pricestr.split(" ");
Float price = Float.valueOf(prezzo[0]);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) view.findViewById(R.id.number_picker);
int value = numberPicker.getValue();
if (value != 0) {
totale = totale + (price * value);
listapiatti = listapiatti + nome + ": " + value + ", ";
Toast.makeText(getApplicationContext(), String.valueOf(i)+" "+value,
Toast.LENGTH_LONG).show();
}
}
String finale=String.valueOf(totale);
startActivity(new Intent(carrello3.this, ordine.class));
}
if (view.getId()==R.id.buttonback){
onBackPressed();
}
}
it doesn't seem like a good idea to create an object on setOnScrollListener which gets called many many times during scrolling up/down. if you could provide more detail would be great.

How to get videos folder?

I am working on a video player app. I have two fragments: one is AllVideolist fragment and the other one is Videos folders fragment. The AllVideoListenter code here fragment is working fine, but I don't know how to show get all videos folder.
This is my MainActivity.java code.
MainActivity.java
public ArrayList<videoFiles> getAllVideos(Context context) {
ArrayList<videoFiles> tempArrayList = new ArrayList<>();
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String [] projection = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DATE_ADDED,
MediaStore.Video.Media.DURATION
};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor!= null){
while (cursor.moveToNext()){
String id =cursor.getString(0);
String path =cursor.getString(1);
String title =cursor.getString(2);
String fileName =cursor.getString(3);
String size =cursor.getString(4);
String dateAdded =cursor.getString(5);
String duration =cursor.getString(6);
int durationa = Integer.parseInt(duration);
String duration_formet;
int sec = (durationa/1000)%60;
int min = (durationa/(1000*60))%60;
int hours = durationa/(1000*60*60);
if (hours == 0){
duration_formet = String.valueOf(min).concat(":" .concat(String.format(Locale.UK, "%02d",sec)));
}else {
duration_formet = String.valueOf(hours).concat(":" .concat(String.format(Locale.UK, "%02d",min).concat(":" .concat(String.format(Locale.UK, "%02d",sec)))));
}
videoFiles videoFiles = new videoFiles(id, path, title,fileName,size, dateAdded,duration_formet);
Log.d("path", path);
tempArrayList.add(videoFiles);
}
cursor.close();
}
return tempArrayList;
}
I craete this model class.
VideoFiles.java
public class videoFiles {
///------------------MODEL CLASS ---------------
private String id;
private String path;
private String title;
private String fileName;
private String size;
private String dateAdded;
private String duration;
public videoFiles(String id, String path, String title, String fileName, String size, String dateAdded, String duration) {
this.id = id;
this.path = path;
this.title = title;
this.fileName = fileName;
this.size = size;
this.dateAdded = dateAdded;
this.duration = duration;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getDateAdded() {
return dateAdded;
}
public void setDateAdded(String dateAdded) {
this.dateAdded = dateAdded;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
This is folder Adapter.
FolderAdapter.java
public class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.folderViewHolder> {
View view;
Context context;
private ArrayList<videoFiles> folderList;
public FolderAdapter(Context context, ArrayList<videoFiles> folderList) {
this.context = context;
this.folderList = folderList;
}
#NonNull
#Override
public FolderAdapter.folderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(context).inflate(R.layout.foldeitems, parent, false);
return new folderViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FolderAdapter.folderViewHolder holder, int position) {
holder.folderName.setText(folderList.get(position).getPath());
}
#Override
public int getItemCount() {
return folderList.size();
}
public class folderViewHolder extends RecyclerView.ViewHolder {
TextView folderName;
public folderViewHolder(#NonNull View itemView) {
super(itemView);
folderName = itemView.findViewById(R.id.foldername);
}
}
}
This is main foledr fragment. I want to show videos in folder by folder
FoldeFragment.java
public class FolderFragment extends Fragment {
View view;
RecyclerView recyclerView;
public FolderFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_folder, container, false);
recyclerView = view.findViewById(R.id.folderRecylerView);
return view;
}
}
There is no "videos folder" in Android. There are number of default locations for videos, but they vary from device to device. Devices that have expandable memory often have video storage defaults that don't exist on non-expandable devices. User are not obliged to put video files in these default locations, anyway.
If you want to get a list of all directories that contain video files, you'll either need to implement some sort of search/index operation yourself, or use the built-in media database. You should be able to enumerate the list of videos from the database, and extract the unique folder names.
For what it's worth, I answered a similar question here:
How to show only videos folder?

Getter returning null when testing get methods

I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.
Any insight would be appreciated as I am lost here. Thanks in advance.
Here is where I initialise the class:
public ArrayList<GameStats> getAllData() {
ArrayList<GameStats> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String lName = cursor.getString(1);
int lScore = cursor.getInt(2);
String rName = cursor.getString(3);
int rScore = cursor.getInt(4);
String notes = cursor.getString(5);
GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
arrayList.add(gameStats);
}
return arrayList;
}
Here is where I am trying to use the getters:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_saved_games, null);
TextView lName = convertView.findViewById(R.id.lName);
TextView lScore = convertView.findViewById(R.id.lScore);
TextView rName = convertView.findViewById(R.id.rName);
TextView rScore = convertView.findViewById(R.id.rScore);
TextView notes = convertView.findViewById(R.id.notes);
GameStats gameStats = arrayList.get(position);
testVar = gameStats.getlName();
Log.d("MyAdaptor","gameStats = " + var);
lName.setText(gameStats.getlName());
lScore.setText(String.valueOf(gameStats.getlScore()));
rName.setText(gameStats.getrName());
rScore.setText(String.valueOf(gameStats.getrScore()));
notes.setText(gameStats.getNotes());
return convertView;
}
Here is the model class:
public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getlScore() {
return lScore;
}
public void setlScore(int lScore) {
this.lScore = lScore;
}
public int getrScore() {
return rScore;
}
public void setrScore(int rScore) {
this.rScore = rScore;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
and here is where I am calling the methods:
public class SavedGameScreen extends AppCompatActivity {
ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_game_screen);
lv1 = findViewById(R.id.lv1);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
loadData();
}
private void loadData() {
arrayList = databaseHelper.getAllData();
myAdaptor = new MyAdaptor(this, arrayList);
lv1.setAdapter(myAdaptor);
myAdaptor.notifyDataSetChanged();
}
}
Please change the constructor as below and see if that works,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
In your model class initialize the variables using constrtuctor. I guess that is the problem. Since you are not initializing the model class properties, it the getters will return "null" or any garbage value
You are passing the values to the model constructor but you are not assigning it to the model variables. You need to change the code as below,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
Else initialise each variable through setter() method.

I get an error while creating a listview adapter

I would create some listview from my api json response, but I stuck with this LinkedTreeMap error in my code. Could anyone help me to solve this?
public class KategoriListAdapter extends BaseAdapter {
Context context;
ArrayList<Barang> barang;
public KategoriListAdapter(Context context, ArrayList<Barang> barang) {
this.context = context;
this.barang = barang;
}
#Override
public int getCount() {
return barang.size();
}
#Override
public Barang getItem(int i) {
return this.barang.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.custom_list_view_kategori, viewGroup, false);
}
TextView tvNama = (TextView) view.findViewById(R.id.tv_nama);
TextView tvHarga = (TextView) view.findViewById(R.id.tv_harga);
TextView tvUsername = (TextView) view.findViewById(R.id.tv_username);
Object getrow = this.barang.get(i);
LinkedTreeMap<Object, Object> rowmap = (LinkedTreeMap) getrow;
String nama = rowmap.get("nama").toString();
String harga = rowmap.get("harga").toString();
String username = rowmap.get("username").toString();
tvNama.setText(nama);
tvHarga.setText(harga);
tvUsername.setText(username);
return view;
}
}
public class Barang {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("nama")
#Expose
private String nama;
#SerializedName("harga")
#Expose
private String harga;
#SerializedName("gambar")
#Expose
private String gambar;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getGambar() {
return gambar;
}
public void setGambar(String gambar) {
this.gambar = gambar;
}
}
The log result while I run the activity is
java.lang.ClassCastException: com.example.barangkoz.model.Barang cannot be
cast to com.google.gson.internal.LinkedTreeMap
at com.example.barangkoz.activities.KategoriListAdapter.getView(KategoriListAdapter.java:57)`
You are passing ArrayList of "Barang" Object in you adapter constructor it means you already have a list of object Barang in your adapter and you can directly use it without casting to TreeMap.
In your getView method of adapter change this
Object getrow = this.barang.get(i);
to
Barang barang = barang.get(i);
it will give the Barang object at the position of i from the list of Barang.
and you can get the data from this object using the getters methods defined inside your object Barang like this.
String harga = barang.getHarga();
String nama = barang.getNama();
String userName = barang.getUsername();
and set it to your TextView or
You can directly set the data to TextView from Barang object (without doing extra step to setting it in variable before setting to TextView), like this
tvHarga.setText(barang.getHarga());
tvNama.setText(barang.getNama());
tvUsername.setText(barang.getUsername());
Replace
Object getrow = this.barang.get(i);
LinkedTreeMap<Object, Object> rowmap = (LinkedTreeMap) getrow;
String nama = rowmap.get("nama").toString();
String harga = rowmap.get("harga").toString();
String username = rowmap.get("username").toString();
With
Barang getrow = this.barang.get(i);
String nama = getrow.getName();
String harga = getrow.getHarga();
String username = getrow.getUsername();

Attempt to invoke virtual method 'int.java.lang.Integer.intValue()' on a null object reference at Cast.writetoParcel [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Getting Error
FATAL EXCEPTION: main
Process: com.example.wuntu.tv_bucket, PID: 3895
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at com.example.wuntu.tv_bucket.Models.Cast.writeToParcel(Cast.java:136)
at android.os.Parcel.writeParcelable(Parcel.java:1437)
at android.os.Parcel.writeValue(Parcel.java:1343)
at android.os.Parcel.writeList(Parcel.java:759)
at android.os.Parcel.writeValue(Parcel.java:1365)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:686)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1330)
at android.os.Bundle.writeToParcel(Bundle.java:1079)
at android.os.Parcel.writeBundle(Parcel.java:711)
at android.content.Intent.writeToParcel(Intent.java:8790)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3112)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1541)
at android.app.Activity.startActivityForResult(Activity.java:4284)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4231)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4568)
at android.app.Activity.startActivity(Activity.java:4536)
at com.example.wuntu.tv_bucket.Adapters.CastDetailAdapter$1.onClick(CastDetailAdapter.java:124)
at android.view.View.performClick(View.java:5698)
at android.widget.TextView.performClick(TextView.java:10908)
at android.view.View$PerformClick.run(View.java:22557)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7231)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Getting error in sending arraylist of object from adapter to other activity. I wanna send my arraylist from onBindViewHolder method of Adapter to another activity but its is showing null exception error on the Cast Class in writetoParcel Method. How to send arraylist properly?
Cast Class
public class Cast implements Parcelable {
#SerializedName("cast_id")
#Expose
private Integer castId;
#SerializedName("character")
#Expose
private String character;
#SerializedName("credit_id")
#Expose
private String creditId;
#SerializedName("gender")
#Expose
private Integer gender;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("order")
#Expose
private Integer order;
#SerializedName("profile_path")
#Expose
private String profilePath;
public Cast(){
}
protected Cast(Parcel in) {
character = in.readString();
id = in.readInt();
name = in.readString();
profilePath = in.readString();
}
public static final Creator<Cast> CREATOR = new Creator<Cast>() {
#Override
public Cast createFromParcel(Parcel in) {
return new Cast(in);
}
#Override
public Cast[] newArray(int size) {
return new Cast[size];
}
};
public Integer getCastId() {
return castId;
}
public void setCastId(Integer castId) {
this.castId = castId;
}
public String getCharacter() {
return character;
}
public void setCharacter(String character) {
this.character = character;
}
public String getCreditId() {
return creditId;
}
public void setCreditId(String creditId) {
this.creditId = creditId;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public String getProfilePath() {
return profilePath;
}
public void setProfilePath(String profilePath) {
this.profilePath = profilePath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i)
{
parcel.writeString(name);
parcel.writeString(profilePath);
parcel.writeString(character);
parcel.writeInt(id);
}
}
CastDetailAdapter Class
public class CastDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Cast> detailArrayList = new ArrayList<>() ;
private UrlConstants urlConstants = UrlConstants.getSingletonRef();
private Cast cast;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private Context context;
MovieView a;
ArrayList<Cast> FullArrayList = new ArrayList<>();
public CastDetailAdapter(MovieView movieView, ArrayList<Cast> detailArrayList,ArrayList<Cast> subCastArrayList)
{
a = movieView;
this.detailArrayList = subCastArrayList;
this.FullArrayList = detailArrayList;
}
public class MyViewHolder1 extends RecyclerView.ViewHolder
{
ImageView cast_profile_picture;
TextView cast_name,cast_character_name;
public MyViewHolder1(View view)
{
super(view);
cast_profile_picture = (ImageView) view.findViewById(R.id.thumbnail);
cast_name = (TextView) view.findViewById(R.id.title);
cast_character_name = (TextView) view.findViewById(R.id.count);
}
}
public class FooterViewHolder1 extends RecyclerView.ViewHolder
{
TextView view_more;
public FooterViewHolder1(View itemView) {
super(itemView);
view_more = (TextView) itemView.findViewById(R.id.view_more);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount() -1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
context = parent.getContext();
if (viewType == VIEW_ITEM)
{
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cast_details, parent, false);
return new MyViewHolder1(v);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.footer_layout_movie_details, parent, false);
return new FooterViewHolder1(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if(holder instanceof MyViewHolder1)
{
cast = detailArrayList.get(position);
((MyViewHolder1)holder).cast_character_name.setText(cast.getCharacter());
((MyViewHolder1)holder).cast_name.setText(cast.getName());
String url3 = urlConstants.URL_Image + cast.getProfilePath();
Picasso.with(context)
.load(url3)
.into(((MyViewHolder1)holder).cast_profile_picture);
}
else if (holder instanceof FooterViewHolder1)
{
((FooterViewHolder1)holder).view_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent intent = new Intent(context,CastViewActivity.class);
intent.putParcelableArrayListExtra("LIST",FullArrayList);
context.startActivity(intent);
}
});
}
}
#Override
public int getItemCount() {
return this.detailArrayList.size();
}
}
In your writeToParcel() method, you have
parcel.writeInt(id);
Since id is Integer, this is going to auto-unbox id. If id is null, this auto-unboxing will throw a NullPointerException.
Since there is no Parcel.writeInteger() method, you're going to have to record whether or not id is null in a separate write. Something like:
if (id == null) {
dest.writeInt(0);
}
else {
dest.writeInt(1);
dest.writeInt(id);
}
And to read it back out:
int hasId = in.readInt();
if (hasId == 1) {
id = in.readInt();
}
else {
id = null;
}
The order in which you read the values from the parcel has to be the same as the order it was written to it.
Try:
protected Cast(Parcel in) {
name = in.readString();
profilePath = in.readString();
character = in.readString();
id = in.readInt();
}

Categories