Getter returning null when testing get methods - java

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.

Related

I have problem in transferring data from activity to another activity

public class Memo extends AppCompatActivity {
DBHandler dbh;
Notes items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memo);
getSupportActionBar().hide();
try{
dbh = new DBHandler(this);
}
catch (Exception ex){
ex.printStackTrace();
}
display();
}
public void display( ){ //method to display all items in the database
List<Notes> books_list = dbh.getNotes(); ////here i get the list fromm the database
///// i used a custom adapter because i needed it
final myAdapter adapter = new myAdapter(this, books_list); ///creating adapter from
myadapter to link it with the list
ListView _note_ = findViewById(R.id.list_txt);
_note_.setAdapter(adapter);
_note_.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items = (Notes) adapter.getItem(position);
String Note_content = items.getNote();
String title = items.getTitle();
String Date = items.getDate();
Intent i = new Intent(getApplicationContext() ,Note_content.class);
i.putExtra("Note ", Note_content);
i.putExtra("title", title);
i.putExtra("Date", Date);
startActivity(i);
}
});
i have a problem when I try to to get data( only Note) from this activity to another activity, other values(Date and Title) are working, I tried to use toString method in Notes class but it gives null for note
public class Note_content extends AppCompatActivity {
Notes item;
TextView txt_note ,txt_date , txt_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_content);
txt_title = findViewById(R.id.txt_ntitle);
txt_note = findViewById(R.id.txt_Nnote);
txt_date = findViewById(R.id.txt_Ndate);
Intent i = getIntent();
String note = i.getStringExtra("Note");
String title = i.getStringExtra("title");
String date = i.getStringExtra("Date");
item = new Notes(title,note,date);
txt_note.setText(item.getNote());
//txt_note.setText(note)
txt_date.setText(date);
txt_title.setText(title);
}
this is the second activit, it is not giving any errors but null instead of the note
and this Notes class
public class Notes {
private int id;
private String title;
private String note ;
private String date;
public Notes() {
}
public Notes(String title, String note, String date) {
this.title = title;
this.note = note;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return this.note+"\n"+title+"\n"+date;
}
}
i.putExtra("Note ", Note_content);
In the above code line, "Note " has an extra space at the end.

Display data into RecyclerView

I never understood how SQL Database works. So I searched a little and found this library. I'm still trying it.
I want to display the data into a RecyclerView using a RecyclerAdapter. I have always worked with it and I know how to do it but only using Cloud Firestore. So my question is: how to display the data in that database library that I have found into the RecyclerView?
I have written the adapter code and created the model class. I still need the part where the data are displayed.
This is how to read all data:
Cursor res = easyDB.getAllData();
while (res.moveToNext()) {
int anIntegerVariable = res.getInt(columnIndex);
String aStringVariable = res.getString(columnIndex);
}
User.java
public class User {
String id, name, password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User() {
}
}
UsersRecyclerAdapater.java
public class UsersRecyclerAdapater extends RecyclerView.Adapter<UsersRecyclerAdapater.ViewHolder> {
public List<User> userList;
public Context context;
public UsersRecyclerAdapater(Context context, List<User> userList) {
this.userList = userList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_list_item, parent, false);
context = parent.getContext();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
String id = userList.get(position).getId();
String name = userList.get(position).getName();
String password = userList.get(position).getPassword();
holder.setIdView(id);
holder.setName(name);
holder.setPasswordView(password);
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView idView;
private TextView nameView;
private TextView passwordView;
public View view;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
}
public void setIdView(String id) {
idView = view.findViewById(R.id.user_id);
idView.setText(id);
}
public void setName(String name) {
nameView = view.findViewById(R.id.user_name);
nameView.setText(name);
}
public void setPasswordView(String password) {
passwordView = view.findViewById(R.id.user_password);
passwordView.setText(password);
}
}
}
MainActivity.java
easyDB = EasyDB.init(this, DATABASE_NAME)
.setTableName(TABLE_NAME)
.addColumn(new Column(NAME_COLUMN, "TEXT"))
.addColumn(new Column(PASSWORD_COLUMN, "TEXT"))
.doneTableColumn();
mainAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mainName.getText().toString();
String password = mainPassword.getText().toString();
boolean done = easyDB.addData(1, name)
.addData(2, password)
.doneDataAdding();
if (done) {
Toast.makeText(MainActivity.this, "User added successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "User not added", Toast.LENGTH_SHORT).show();
}
}
});
mainRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Cursor cursor = easyDB.getAllData();
while (cursor.moveToNext()) {
String name = cursor.getString(1);
String password = cursor.getString(2);
Toast.makeText(MainActivity.this, name + "\n" + password, Toast.LENGTH_SHORT).show();
}
*/
startActivity(new Intent(MainActivity.this, UsersActivity.class));
}
});
Any help please?
You have to prepare the user list from the DB cursor and use it to RecyclerView. Check below:
List<User> userList = new ArrayList<>();
EasyDB easyDB = EasyDB.init(this, DATABASE_NAME).setTableName(TABLE_NAME);
Cursor res = easyDB.getAllData();
if(res != null && res.getCount() > 0) {
res.moveToFirst();
do {
int id = res.getInt(0);
String name = res.getString(1);
String pass = res.getString(2);
userList.add(new User(id, name, pass));
} while (res.moveToNext());
}
res.close();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
UsersRecyclerAdapater adapter = new UsersRecyclerAdapater(this, userList);
recyclerView.setAdapter(adapter);
You will have to iterate through the cursor and create a List out of it and your RecyclerView will take that list as input.
List<User> userList = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
int anIntegerVariable = cursor.getInt(columnIndex);
String aStringVariable = cursor.getString(columnIndex);
User user = new User();
user.setId(anIntegerVariable();
user.setName(aStringVariable);
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
You should have a look at Room which is the recommended database library for android applications. https://developer.android.com/training/data-storage/room

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();

TodoList application android

Please I need your help .I'am trying to take the date from an activity and then put it in an array list then print it in an ListView .
The problem is the data that I should take it from "Adding Todo" is not showing in the ListView . it do take me to the List Activity but without showing the data .
This is How the app going to be "Adding todo"
And this is the ListView where the data should be in it
My code :-
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
arrayList = new ArrayList<>();
todoAdapter = new TodoAdapter(this , arrayList);
listView.setAdapter(todoAdapter);
}
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, AddTodo.class);
startActivityForResult(intent, Intent_Constants.INTENT_REQUEST_CODE);
}
protected void onActivityResult(int reqCode ,int resultCode , Intent data ){
// here Iam trying to get the data from ADDING TO DO class
if(resultCode == Intent_Constants.INTENT_REQUEST_CODE){
titleText = data.getStringExtra(Intent_Constants.INTENT_TITLE);
priorityText = data.getStringExtra(Intent_Constants.INTENT_PRIORITY);
statusText = data.getStringExtra(Intent_Constants.INTENT_STATUES);
dateText = data.getStringExtra(Intent_Constants.INTENT_DATE);
timeText = data.getStringExtra(Intent_Constants.INTENT_TIME);
todoAdapter.todo.add(new Todo (titleText , statusText ,priorityText ,dateText ,timeText));
}
}
Intent_Constants
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE = 1;
public final static int INTENT_RESULT_CODE = 1 ;
public final static String INTENT_TITLE = "Title";
public final static String INTENT_PRIORITY = "Priority";
public final static String INTENT_TIME = "Time";
public final static String INTENT_DATE = "Date";
public final static String INTENT_STATUES = "Statues";
}
AddTodo class
In this class I find the id then I converted to String
public void saveButton (View view){
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_TITLE , title);
intent.putExtra(Intent_Constants.INTENT_DATE , date);
intent.putExtra(Intent_Constants.INTENT_TIME , time);
intent.putExtra(Intent_Constants.INTENT_PRIORITY , priority);
intent.putExtra(Intent_Constants.INTENT_STATUES , completed);
setResult(INTENT_RESULT_CODE, intent);
finish();
}
TodoAdapter class
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
super(context, R.layout.todo_list,todo);
this.todo = todo;
}
public static class ViewHolder {
TextView titleText;
TextView priorityText;
TextView dateText;
TextView timeText;
CheckBox statusBox;
ImageButton edit_image;
ImageButton open_image;
ImageButton delet_image;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = LayoutInflater.from(getContext()) ;
View customeView =inflater.inflate(R.layout.todo_list,parent ,false);
holder.titleText.setText(getItem(position).getTitle());
holder.priorityText.setText(getItem(position).getPriority());
holder.dateText.setText(getItem(position).getDate());
holder.timeText.setText(getItem(position).getTime());
holder.statusBox.setChecked(false);
holder.edit_image = customeView.findViewById(R.id.edit_imageView);
holder.open_image = customeView.findViewById(R.id.open_imageButton);
holder.delet_image = customeView.findViewById(R.id.delete_imageView);
holder.edit_image.setImageResource(R.drawable.ic_edit_black_24dp);
holder.open_image.setImageResource(R.drawable.ic_refresh_black_24dp);
holder.delet_image.setImageResource(R.drawable.ic_delete_black_24dp);
return customeView;
}
Todo class
public class Todo {
private String title ;
private String status ;
private String priority ;
private String date ;
private String time ;
public Todo() {
}
public Todo(String title, String status, String priority, String date, String time) {
this.title = title;
this.status = status;
this.priority = priority;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public String getStatus() {
return status;
}
public String getPriority() {
return priority;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public void setTitle(String title) {
this.title = title;
}
public void setStatus(String status) {
this.status = status;
}
public void setPriority(String priority) {
this.priority = priority;
}
public void setDate(String date) {
this.date = date;
}
public void setTime(String time) {
this.time = time;
}
}
You can just set a new adapter, I know it isn't best way, but should do the work. Don't create new one, but nulify yours, and initialize it with new data.
#Noura change this
arrayList.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
to
todoAdapter.todo.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
todoAdapter.notifyDataSetChanged();
and at the constructor u need to update your code like below
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
this.todo = todo
super(context, R.layout.todo_list,todo);
}

Resource$NotFoundException while getting String by resource ID

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

Categories