create button on xml file (not new activity) and open new activity - java

I'm new in android studio and currently creating an app which will retrieve data from existing db of sqlite. based on what I'd found is to create a layout file (not by creating new empty activity) to design on how the display the data. But in the layout, I want the button to open new activity, but somehow it didn't and I didn't found any solution so far. and the image also didn't appeared. This is the code:
DataPOI.java
public class DataPOI {
private int id;
private String category;
private String name;
private String hour;
private String phone_number;
private String address;
private String website;
private int fee_adult_standard;
private int fee_child_standard;
private int fee_senior_standard;
private int fee_adult_MyKad;
private int fee_child_MyKid;
private int fee_senior_MyKad;
private int fee_student_standard;
private int fee_student_MyKad;
private String description;
private byte[] photo;
private String coordinate;
private String door;
private String parking1;
private String parking2;
public DataPOI(int id, String category, String name, String hour, String phone_number,
String address, String website, int fee_adult_standard, int fee_child_standard,
int fee_senior_standard, int fee_adult_MyKad, int fee_child_MyKid,
int fee_senior_MyKad, int fee_student_standard, int fee_student_MyKad,
String description, byte[] photo, String coordinate, String door,
String parking1, String parking2) {
this.id = id;
this.category = category;
this.name = name;
this.hour = hour;
this.phone_number = phone_number;
this.address = address;
this.website = website;
this.fee_adult_standard = fee_adult_standard;
this.fee_child_standard = fee_child_standard;
this.fee_senior_standard = fee_senior_standard;
this.fee_adult_MyKad = fee_adult_MyKad;
this.fee_child_MyKid = fee_child_MyKid;
this.fee_senior_MyKad = fee_senior_MyKad;
this.fee_student_standard = fee_student_standard;
this.fee_student_MyKad = fee_student_MyKad;
this.description = description;
this.photo = photo;
this.coordinate = coordinate;
this.door = door;
this.parking1 = parking1;
this.parking2 = parking2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getFee_adult_standard() {
return fee_adult_standard;
}
public void setFee_adult_standard(int fee_adult_standard) {
this.fee_adult_standard = fee_adult_standard;
}
public int getFee_child_standard() {
return fee_child_standard;
}
public void setFee_child_standard(int fee_child_standard) {
this.fee_child_standard = fee_child_standard;
}
public int getFee_senior_standard() {
return fee_senior_standard;
}
public void setFee_senior_standard(int fee_senior_standard) {
this.fee_senior_standard = fee_senior_standard;
}
public int getFee_adult_MyKad() {
return fee_adult_MyKad;
}
public void setFee_adult_MyKad(int fee_adult_MyKad) {
this.fee_adult_MyKad = fee_adult_MyKad;
}
public int getFee_child_MyKid() {
return fee_child_MyKid;
}
public void setFee_child_MyKid(int fee_child_MyKid) {
this.fee_child_MyKid = fee_child_MyKid;
}
public int getFee_senior_MyKad() {
return fee_senior_MyKad;
}
public void setFee_senior_MyKad(int fee_senior_MyKad) {
this.fee_senior_MyKad = fee_senior_MyKad;
}
public int getFee_student_standard() {
return fee_student_standard;
}
public void setFee_student_standard(int fee_student_standard) {
this.fee_student_standard = fee_student_standard;
}
public int getFee_student_MyKad() {
return fee_student_MyKad;
}
public void setFee_student_MyKad(int fee_student_MyKad) {
this.fee_student_MyKad = fee_student_MyKad;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
public String getCoordinate() {
return coordinate;
}
public void setCoordinate(String coordinate) {
this.coordinate = coordinate;
}
public String getDoor() {
return door;
}
public void setDoor(String door) {
this.door = door;
}
public String getParking1() {
return parking1;
}
public void setParking1(String parking1) {
this.parking1 = parking1;
}
public String getParking2() {
return parking2;
}
public void setParking2(String parking2) {
this.parking2 = parking2;
}
}
ListPOIadapter.java
public class ListPOIadapter extends BaseAdapter {
private Context mContext;
private List<DataPOI> mPOIList;
public ListPOIadapter(Context mContext, List<DataPOI> mPOIList) {
this.mContext = mContext;
this.mPOIList = mPOIList;
}
#Override
public int getCount() {
return mPOIList.size();
}
#Override
public Object getItem(int i) {
return mPOIList.get(i);
}
#Override
public long getItemId(int i) {
return mPOIList.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.data_layout, null);
//edit below this
ImageView myPhoto = (ImageView)v.findViewById(R.id.imageView);
TextView myName = (TextView)v.findViewById(R.id.name);
TextView myHour = (TextView)v.findViewById(R.id.operational_hour);
TextView myContact = (TextView)v.findViewById(R.id.contact_number);
TextView myWebsite = (TextView)v.findViewById(R.id.website);
TextView myAddress = (TextView)v.findViewById(R.id.address);
//myPhoto.setI(mPOIList.get(i).getPhoto());
myName.setText(mPOIList.get(i).getName());
myHour.setText(mPOIList.get(i).getHour());
myContact.setText(mPOIList.get(i).getPhone_number());
myWebsite.setText(mPOIList.get(i).getWebsite());
myAddress.setText(mPOIList.get(i).getAddress());
return v;
}
}
AmusementPark.java
public class AmusementPark extends AppCompatActivity {
private ListView lvPOI;
private ListPOIadapter adapter;
private List<DataPOI> mPOIList;
private AmusementPark_Helper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amusement_park);
lvPOI = (ListView)findViewById(R.id.listview_product);
mDBHelper = new AmusementPark_Helper(this);
//Check existis database
File database = getApplicationContext().getDatabasePath(AmusementPark_Helper.DBNAME);
if(false == database.exists()) {
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database success", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Copy database error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mPOIList = mDBHelper.getListPOI();
//Init adapter
adapter = new ListPOIadapter(this, mPOIList);
//Set adapter for listview
lvPOI.setAdapter(adapter);
}
private boolean copyDatabase (Context context) {
try {
InputStream inputStream = context.getAssets().open(AmusementPark_Helper.DBNAME);
String outFileName = AmusementPark_Helper.DBLOCATION + AmusementPark_Helper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("Amusement Park", "DB copied");
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
AmusementPark_Helper.java
public class AmusementPark_Helper extends SQLiteOpenHelper {
public static final String DBNAME = "placeofinterest.sqlite";
public static final String DBLOCATION = "/data/data/com.example.lenovo.welcome.ListHelper";
private Context mContext;
private SQLiteDatabase mDatabase;
public AmusementPark_Helper (Context context) {
super(context, DBNAME, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase() {
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if(mDatabase != null && mDatabase.isOpen()) {
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if(mDatabase != null) {
mDatabase.close();
}
}
public List<DataPOI> getListPOI() {
DataPOI placeofinterest = null;
List<DataPOI> poiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM amusement_park", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//below is depends on data type of each column
placeofinterest = new DataPOI(
cursor.getInt(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5),
cursor.getString(6), cursor.getInt(7), cursor.getInt(8),
cursor.getInt(9), cursor.getInt(10), cursor.getInt(11),
cursor.getInt(12), cursor.getInt(13), cursor.getInt(14),
cursor.getString(15), cursor.getBlob(16), cursor.getString(17),
cursor.getString(18), cursor.getString(19), cursor.getString(20));
poiList.add(placeofinterest);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return poiList;
}
}
data_layout.xml (created not by using "create new empty activity")
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="210dp"
android:background="#89cff0">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
app:srcCompat="#mipmap/ic_launcher_round" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/imageView"
android:text="Name of POI"
android:textColor="#000"
android:textSize="19sp" />
<TextView
android:id="#+id/operational_hour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_toRightOf="#id/imageView"
android:text="Operational Hours"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/contact_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/operational_hour"
android:layout_toRightOf="#id/imageView"
android:text="Contact Number"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/website"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/contact_number"
android:layout_toRightOf="#id/imageView"
android:clickable="true"
android:text="Website"
android:autoLink="web"
android:textColor="#000"
android:textSize="15sp" />
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/website"
android:layout_toRightOf="#id/imageView"
android:clickable="true"
android:text="Address"
android:textColor="#000"
android:textSize="15sp" />
<Button
android:id="#+id/button_description"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/address"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/imageView"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Description"
android:textColor="#000" />
<Button
android:id="#+id/button_entrance_fee"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/address"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/button_description"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Entrance Fee"
android:textColor="#000" />
<Button
android:id="#+id/button_nearest_me"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/button_entrance_fee"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/imageView"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Nearest Me"
android:textColor="#000" />
<Button
android:id="#+id/button_take_me_there"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_below="#id/button_entrance_fee"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#id/button_nearest_me"
android:layout_weight="1"
android:background="#drawable/mybutton"
android:text="Take Me There"
android:textColor="#000" />
</RelativeLayout>
So, how to open new activity from a button which as no .java? I tried to create a new activity and copy paste from the data_layout.xml but it still not working. I hope my explanation is quite clear. and please help me. Thank you.

In your AmusementPark.java file, change
if(false == database.exists()) {
to
if(database.exists == false) {
Also verify the paths are correct. See this very similar article: How do I get a button to open another activity in Android Studio?
Code taken from article:
Manifest file
<activity
android:name="MyOtherActivity"
android:label="#string/app_name">
</activity>
Activity.java file
Button btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
}
});

Related

How to implement "favourite" button feature (like favourite recipe/food) and display on another list in another fragment

I want to have a feature that when the user clicked the button on a certain row, it will add the row to another list which is called favorite list. Currently i have created database that also include favourite status. I already tried to start with creating a button that when its clicked it will change the fav status.
Im still new on android studio, just learnt for half a month. So go easy on me. I am currently stuck on this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 13778
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.myapplication.data.DatabaseHandler.addRecipe(com.example.myapplication.model.Recipe)' on a null object reference
at com.example.myapplication.adapter.RecyclerViewAdapter$ViewHolder$1.onClick(RecyclerViewAdapter.java:123)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Recipe.java
public class Recipe {
private int id;
private String name;
private String description;
private String ingredient;
private int image;
private String favStatus;
public Recipe() {
}
public Recipe(int id, String name, String description, String ingredient, int image, String favStatus) {
this.id = id;
this.name = name;
this.description = description;
this.ingredient = ingredient;
this.image = image;
this.favStatus = favStatus;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIngredient() {
return ingredient;
}
public void setIngredient(String ingredient) {
this.ingredient = ingredient;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getFavStatus() {
return favStatus;
}
public void setFavStatus(String favStatus) {
this.favStatus = favStatus;
}
}
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, Util.DATABASE_NAME, null, Util.DATABASE_VERSION);
}
//We create our table..
#Override
public void onCreate(SQLiteDatabase db) {
//SQL- Structured Query Language
/*
create table _name(id, name, desc, ingredient, image);
*/
String CREATE_CONTACT_TABLE = "CREATE TABLE " + Util.TABLE_NAME + "("
+ Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT,"
+ Util.KEY_DESCRIPTION + " TEXT," + Util.KEY_INGREDIENT + " TEXT,"
+ Util.KEY_IMAGE + " BLOB," + Util.KEY_FAV_STATUS + " TEXT" + ")";
db.execSQL(CREATE_CONTACT_TABLE); //Creating our table..
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE = String.valueOf(R.string.db_drop);
db.execSQL(DROP_TABLE, new String[]{Util.DATABASE_NAME});
//Create table again
onCreate(db);
}
//Add Recipe
public void addRecipe(Recipe recipe) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME, recipe.getName());
values.put(Util.KEY_DESCRIPTION, recipe.getDescription());
values.put(Util.KEY_INGREDIENT, recipe.getIngredient());
values.put(Util.KEY_IMAGE, recipe.getImage());
values.put(Util.KEY_FAV_STATUS, recipe.getFavStatus());
//Insert into row..
db.insert(Util.TABLE_NAME, null, values);
Log.d("DBHandler", "addRecipe: " + "item added");
db.close();
}
//Get a recipe
public Recipe getRecipe(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Util.TABLE_NAME,
new String[] { Util.KEY_ID, Util.KEY_NAME, Util.KEY_DESCRIPTION, Util.KEY_FAV_STATUS,
Util.KEY_INGREDIENT, Util.KEY_IMAGE}, Util.KEY_ID +"=?",
new String[]{String.valueOf(id)},
null, null, null);
if (cursor != null)
cursor.moveToFirst();
Recipe recipe = new Recipe();
recipe.setId(Integer.parseInt(cursor.getString(0)));
recipe.setName(cursor.getString(1));
recipe.setDescription(cursor.getString(2));
recipe.setIngredient(cursor.getString(3));
recipe.setImage(Integer.parseInt(cursor.getString(4)));
recipe.setFavStatus(cursor.getString(5));
return recipe;
}
//Get all Recipes
public List<Recipe> getAllRecipes() {
List<Recipe> recipeList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//Select all recipes
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll, null);
//Loop through our data
if (cursor.moveToFirst()) {
do {
Recipe recipe = new Recipe();
recipe.setId(Integer.parseInt(cursor.getString(0)));
recipe.setName(cursor.getString(1));
recipe.setDescription(cursor.getString(2));
recipe.setIngredient(cursor.getString(3));
recipe.setImage(Integer.parseInt(cursor.getString(4)));
recipe.setFavStatus((cursor.getString(5)));
//add recipe objects to our list
recipeList.add(recipe);
}while (cursor.moveToNext());
}
return recipeList;
}
//Update recipe
public int updateRecipe (Recipe recipe) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME, recipe.getName());
values.put(Util.KEY_DESCRIPTION, recipe.getDescription());
values.put(Util.KEY_INGREDIENT, recipe.getIngredient());
values.put(Util.KEY_IMAGE, recipe.getImage());
values.put(Util.KEY_FAV_STATUS, recipe.getFavStatus());
//Update the row
return db.update(Util.TABLE_NAME, values, Util.KEY_ID + "=?",
new String[]{String.valueOf(recipe.getId())});
}
//Delete single recipe
public void deleteRecipe(Recipe recipe) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Util.TABLE_NAME, Util.KEY_ID + "=?",
new String[]{String.valueOf(recipe.getId())});
db.close();
}
//Select all favorite list method.
public List<Recipe> getAllFavRecipes() {
List<Recipe> recipeList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//Select all recipes
String selectAll = "SELECT * FROM " + Util.TABLE_NAME + " WHERE " + Util.KEY_FAV_STATUS + " ='1'";
Cursor cursor = db.rawQuery(selectAll, null);
//Loop through our data
if (cursor.moveToFirst()) {
do {
Recipe recipe = new Recipe();
recipe.setId(Integer.parseInt(cursor.getString(0)));
recipe.setName(cursor.getString(1));
recipe.setDescription(cursor.getString(2));
recipe.setIngredient(cursor.getString(3));
recipe.setImage(Integer.parseInt(cursor.getString(4)));
recipe.setFavStatus((cursor.getString(5)));
//add recipe objects to our list
recipeList.add(recipe);
}while (cursor.moveToNext());
}
return recipeList;
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable{
private Context context;
private List<Recipe> recipeList;
private List<Recipe> recipeListFull;
private DatabaseHandler db;
public RecyclerViewAdapter(Context context, List<Recipe> recipeList) {
this.context = context;
this.recipeList = recipeList;
recipeListFull = new ArrayList<>(recipeList);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recipe_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
Recipe recipe = recipeList.get(position); //each recipe object inside of our list
viewHolder.recipeName.setText(recipe.getName());
viewHolder.description.setText(recipe.getDescription());
viewHolder.image.setImageResource(recipe.getImage());
}
#Override
public int getItemCount() {
return recipeList.size();
}
#Override
public Filter getFilter() {
return filterRecipe;
}
private Filter filterRecipe = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String searchText = charSequence.toString().toLowerCase();
List<Recipe> tempList = new ArrayList<>();
if(searchText.length()==0 | searchText.isEmpty()) {
tempList.addAll(recipeListFull);
}else {
for (Recipe item:recipeListFull) {
if (item.getName().toLowerCase().contains(searchText)) {
tempList.add(item);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tempList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
recipeList.clear();
recipeList.addAll((Collection<? extends Recipe>) filterResults.values);
notifyDataSetChanged();
}
};
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView recipeName;
public TextView description;
public ImageView image;
public ImageView favBtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
recipeName = itemView.findViewById(R.id.name);
description = itemView.findViewById(R.id.description);
image = itemView.findViewById(R.id.recipe_imageView);
favBtn = itemView.findViewById(R.id.fav_image_btn);
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Recipe recipe = recipeList.get(position);
if (recipe.getFavStatus().equals("0")) {
recipe.setFavStatus("1");
db.addRecipe(recipe);
favBtn.setImageResource(R.drawable.favourite_star);
} else {
recipe.setFavStatus("0");
db.deleteRecipe(recipe);
favBtn.setImageResource(R.drawable.shadow_fav_star);
}
}
});
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipe = recipeList.get(position);
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("name", recipe.getName());
intent.putExtra("description", recipe.getDescription());
intent.putExtra("ingredient", recipe.getIngredient());
intent.putExtra("image", recipe.getImage());
context.startActivity(intent);
//Log.d("Clicked", "onClick: " + recipe.getName());
}
}
//Create method to read and check for fav status for every row..
}
recipeRow.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/row_cardView"
android:layout_width="0dp"
android:layout_height="150dp"
android:layout_marginStart="1dp"
android:layout_marginTop="2dp"
android:layout_marginEnd="1dp"
app:cardCornerRadius="15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<ImageView
android:id="#+id/recipe_imageView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginStart="3dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="12dp"
android:ellipsize="end"
android:fontFamily="#font/courgette"
android:maxLines="2"
android:text="Title Text"
android:textColor="#color/darker"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.007"
app:layout_constraintStart_toEndOf="#+id/recipe_imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ellipsize="end"
android:maxLines="3"
android:text="Desc Text"
android:textSize="13sp"
android:textColor="#color/darkGray"
app:layout_constraintBottom_toTopOf="#+id/fav_image_btn"
app:layout_constraintEnd_toEndOf="#+id/name"
app:layout_constraintStart_toStartOf="#+id/name"
app:layout_constraintTop_toBottomOf="#+id/name" />
<ImageView
android:id="#+id/fav_image_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="25dp"
android:layout_marginBottom="7dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/favourite_star" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
The following error can occur when you try to use object which is not initialised before using it. means it's in null state, as you can see your db object in RecyclerViewAdapter is not initialised.
to solve this just initialised the object before using it or check if it's not null.
in you case just do as
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable{
....
private DatabaseHandler db; // object declared here
public RecyclerViewAdapter(Context context, List<Recipe> recipeList) {
this.context = context;
this.recipeList = recipeList;
recipeListFull = new ArrayList<>(recipeList);
db = new DatabaseHandler(context); // db object initialised here
}
....
}

How can I resolve the issue of the data not displaying from firebase-firestore on my recyclerview?

Please I need help on an issue around displaying data from firebase firestore to my RecyclerView
I'm building an app that needs to display list of users showing their name, picture, status and last chat on a RecyclerView. I have written the adapter and all the necessary POJO class and it works fine when populate it manually from the code
However I keep hitting a snag when trying to do this automatically from firebase firestore
See my codes below and firebase structure below
THIS IS MY SIMPLE POJO CLASS
package com.rhemaapp.rhematech.rhemahive.RhemaHiveMessagingPackage;
public class RhemaHiveUserMessageModel {
public String senderId;
public String receiverId;
public String messageTimeStamp;
public boolean isMessageStarred;
public String messageStatus;
public String userStatus;
public String userIcon;
public String userMessage;
public String messageType;
public String senderName;
public String receiverName;
public String user_church;
public String receiverMessage;
public String receiverTime;
public RhemaHiveUserMessageModel(String senderId, String receiverId, String messageTimeStamp, boolean isMessageStarred, String messageStatus, String userStatus, String userIcon, String userMessage, String messageType, String churchName) {
this.senderId = senderId;
this.receiverId = receiverId;
this.messageTimeStamp = messageTimeStamp;
this.isMessageStarred = isMessageStarred;
this.messageStatus = messageStatus;
this.userStatus = userStatus;
this.userIcon = userIcon;
this.userMessage = userMessage;
this.messageType = messageType;
}
public RhemaHiveUserMessageModel(String messageTimeStamp, String userMessage) {
this.receiverTime = messageTimeStamp;
this.userMessage = userMessage;
}
public RhemaHiveUserMessageModel() {
}
public RhemaHiveUserMessageModel(String messageTimeStamp, String messageStatus, String userMessage, String senderId, String receiverId, String messageType, boolean isMessageStarred, String church_name) {
this.messageTimeStamp = messageTimeStamp;
this.messageStatus = messageStatus;
this.userMessage = userMessage;
this.senderId = senderId;
this.receiverId = receiverId;
this.messageType = messageType;
this.isMessageStarred = isMessageStarred;
this.user_church = church_name;
}
public String getChurch_name() {
return user_church;
}
public String getReceiverMessage() {
return receiverMessage;
}
public String getReceiverTime() {
return receiverTime;
}
public RhemaHiveUserMessageModel(String messageTimeStamp, String userIcon, String userMessage, String receiverName, String receiverId, String recStat) {
this.messageTimeStamp = messageTimeStamp;
this.userIcon = userIcon;
this.userMessage = userMessage;
this.receiverName = receiverName;
this.receiverId = receiverId;
this.userStatus = recStat;
}
public RhemaHiveUserMessageModel(String messageTimeStamp, String userStatus, String userMessage, String receiverMessage, String receiverTime) {
this.messageTimeStamp = messageTimeStamp;
this.userStatus = userStatus;
this.userMessage = userMessage;
this.receiverMessage = receiverMessage;
this.receiverTime = receiverTime;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getReceiverId() {
return receiverId;
}
public void setReceiverId(String receiverId) {
this.receiverId = receiverId;
}
public String getMessageTimeStamp() {
return messageTimeStamp;
}
public void setMessageTimeStamp(String messageTimeStamp) {
this.messageTimeStamp = messageTimeStamp;
}
public boolean isMessageStarred() {
return isMessageStarred;
}
public void setMessageStarred(boolean messageStarred) {
isMessageStarred = messageStarred;
}
public String getMessageStatus() {
return messageStatus;
}
public void setMessageStatus(String messageStatus) {
this.messageStatus = messageStatus;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public String getUserIcon() {
return userIcon;
}
public void setUserIcon(String userIcon) {
this.userIcon = userIcon;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getReceiverName() {
return receiverName;
}
public void setReceiverName(String receiverName) {
this.receiverName = receiverName;
}
}
THIS IS MY ADAPTER CLASS
package com.rhemaapp.rhematech.rhemahive.RhemaHiveControllerPackage;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.rhemaapp.rhematech.rhemahive.GlideApp;
import com.rhemaapp.rhematech.rhemahive.R;
import com.rhemaapp.rhematech.rhemahive.RhemaHiveMessagingPackage.RhemaHiveUserMessageModel;
import java.util.ArrayList;
public class RhemaHiveMessageAdapter extends RecyclerView.Adapter<RhemaHiveMessageAdapter.RhemaHiveMessageViewHolder> implements Filterable {
private ArrayList<RhemaHiveUserMessageModel> rhemaHiveUserMessListMain = new ArrayList<>();
private RhemaHiveUserMessageModel rhemaModelMain;
private ArrayList<RhemaHiveUserMessageModel> chatListFiltered;
private View v;
#NonNull
#Override
public RhemaHiveMessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_message_lay,parent, false);
return new RhemaHiveMessageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RhemaHiveMessageViewHolder holder, int position) {
rhemaModelMain = new RhemaHiveUserMessageModel();
rhemaModelMain = rhemaHiveUserMessListMain.get(position);
holder.tvName.setText(rhemaModelMain.getReceiverName());
holder.tvTime.setText(rhemaModelMain.getMessageTimeStamp());
holder.tvLastChat.setText(rhemaModelMain.getUserMessage());
holder.tvRecvid.setText(rhemaModelMain.getReceiverId());
if(!rhemaModelMain.getUserIcon().equals("")){
GlideApp.with(v.getContext()).load(rhemaModelMain.getUserIcon()).centerCrop().fitCenter().into(holder.iv);
}
else{
holder.iv.setImageResource(R.drawable.pic_upload);
}
}
#Override
public int getItemCount() {
return rhemaHiveUserMessListMain.size();
}
/**
* this method is implemented for performing filtering
* #return
*/
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
//the user entry is retrieved and converted to String
String searchString = charSequence.toString();
//a check is done for when entry is empty and then the list remains unchanged
if(searchString.isEmpty()){
chatListFiltered = rhemaHiveUserMessListMain;
}
//otherwise a new list is created
else{
ArrayList<RhemaHiveUserMessageModel> filteredChatListInternal = new ArrayList<>();
//a loop is carried out on the list
for(RhemaHiveUserMessageModel rModel : rhemaHiveUserMessListMain){
// a comparison is made to check if the list has entry from the search box
if(rModel.getReceiverName().toLowerCase().contains(searchString) || rModel.getUserMessage().toLowerCase().contains(searchString) || rModel.getUserStatus().toLowerCase().contains(searchString)){
//the new list is populated with this result
filteredChatListInternal.add(rModel);
}
}
//the new list is saved in the chatList
chatListFiltered = filteredChatListInternal;
}
//filter result is replaced and returned
FilterResults filterResults = new FilterResults();
filterResults.values = chatListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
//the results are published
chatListFiltered = (ArrayList<RhemaHiveUserMessageModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class RhemaHiveMessageViewHolder extends RecyclerView.ViewHolder{
TextView tvName, tvTime, tvLastChat,tvRecvid;
ImageView iv;
public RhemaHiveMessageViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.message_chat_name);
tvTime = itemView.findViewById(R.id.message_time_sent);
tvLastChat = itemView.findViewById(R.id.message_last_chat);
iv = itemView.findViewById(R.id.message_user_icon);
tvRecvid = itemView.findViewById(R.id.receivId);
}
}
public RhemaHiveMessageAdapter(ArrayList<RhemaHiveUserMessageModel> rhemaHiveUserMessListMain) {
this.rhemaHiveUserMessListMain = rhemaHiveUserMessListMain;
this.chatListFiltered = rhemaHiveUserMessListMain;
}
}
THIS IS MY LAYOUT FILE FOR INFLATING MY ADAPTER
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="56dp"
android:layout_height="56dp"
app:cardCornerRadius="40dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:cardElevation="8dp"
android:innerRadius="0dp"
android:shape="ring"
android:id="#+id/cv_message_img_card"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ImageView
android:layout_width="53dp"
android:layout_height="53dp"
android:id="#+id/message_user_icon"
android:contentDescription="#string/sign_out_lab"
app:srcCompat="#drawable/user_female"/>
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/message_chat_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/fauna_one"
android:textStyle="bold"
android:textAlignment="center"
android:gravity="center"
android:textSize="16sp"
app:layout_constraintStart_toEndOf="#id/cv_message_img_card"
app:layout_constraintTop_toTopOf="parent"
tools:text="Samuel Iwuchukwu" />
<TextView
android:id="#+id/message_time_sent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="88dp"
android:layout_marginTop="8dp"
android:textSize="12sp"
android:fontFamily="#font/fauna_one"
android:layout_marginEnd="8dp"
app:layout_constraintStart_toEndOf="#id/message_chat_name"
app:layout_constraintEnd_toEndOf="parent"
android:textAlignment="textEnd"
android:gravity="end"
tools:text="3:10"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/fauna_one"
android:id="#+id/message_last_chat"
tools:text="I am fine"
android:drawableStart="#drawable/ic_good"
app:layout_constraintTop_toBottomOf="#id/message_chat_name"
app:layout_constraintStart_toEndOf="#id/cv_message_img_card"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/receivId"
android:layout_marginTop="8dp"
android:layout_marginStart="100dp"
android:textSize="12sp"
app:layout_constraintStart_toEndOf="#id/message_last_chat"
app:layout_constraintTop_toBottomOf="#id/message_chat_name"
android:textColor="#color/design_default_color_surface"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
This is my Fragment class for displaying the recyclerview
THIS RETRIEVES THE CHAT LIST FROM FIREBASE FIRESTORE
public void retrieveChatList(String church_name, String user_type){
if (networkInfo != null && networkInfo.isConnectedOrConnecting() && networkInfo.isConnected()) {
progressDialog.show();
progressDialog.setMessage("Please wait while we retrieve the chats");
collRef = fStore.collection("rhema_churches");
collRef.whereEqualTo("user_church",church_name).whereEqualTo("user_type",user_type).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
//dismiss the dialog
for(DocumentSnapshot d : task.getResult()){
if(d.exists()) {
receiverPics = d.getString("user_pix");
retreiveRecId = d.getString("user_uid");
receiverName = d.getString("user_fName");
receiverStatus = d.getString("user_about");
messageTimeStamp = d.getString("user_address");
userMessage = d.getString("user_lName");
getAuto().getToast(getContext(), "ID : " + retreiveRecId, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
getAuto().getToast(getContext(), "name : " + receiverName, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
getAuto().getToast(getContext(), "Status : " + receiverStatus, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
rhemaHiveUserMessageModels.add(new RhemaHiveUserMessageModel(messageTimeStamp, receiverPics, userMessage, receiverName, retreiveRecId, receiverStatus));
messageAdapter.notifyDataSetChanged();
}
else{
getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + " no documents found here", RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
}//end of for loop
progressDialog.dismiss();
}
else{
getAuto().getToast(getContext(),RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + task.getException().getLocalizedMessage(),RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
}
});
}
else{
getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + networkInfo.getReason(),RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
getAuto().getToast(getContext(), "ID : " + retreiveRecId, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
getAuto().getToast(getContext(), "name : " + receiverName, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
getAuto().getToast(getContext(), "Status : " + receiverStatus, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
THIS IS THE ONCREATE VIEW WHERE THE ADAPTER IS INSTANTIATED
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
try {
setHasOptionsMenu(true);
progressDialog = new ProgressDialog(getContext());
recIdBund = new Bundle();
arrRecId = new ArrayList<>();
messageAreaIntent = new Intent(getContext(), RhemaHiveMessagingActivity.class);
rhemaHiveUserMessageModels = new ArrayList<>();
fAuth = FirebaseAuth.getInstance();
rhemaHiveUserMessageModel = new RhemaHiveUserMessageModel();
fStore = FirebaseFirestore.getInstance();
selRecID = retrAllId();
connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
//the NetworkInfo class gets the current state of the device network connection
networkInfo = connMgr.getActiveNetworkInfo();
v = inflater.inflate(R.layout.fragment_rhema_hive_message, container, false);
rv = v.findViewById(R.id.rv_messaging);
messageAdapter = new RhemaHiveMessageAdapter(rhemaHiveUserMessageModels);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(mLayoutManager);
rv.setHasFixedSize(true);
rv.setItemAnimator(new DefaultItemAnimator());
rv.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
rv.setAdapter(messageAdapter);
rv.addOnItemTouchListener(new RhemaHiveMessageTouchListenerClass(getContext(), rv, new RhemaHiveMessageTouchListenerClass.ClickListener() {
#Override
public void onClick(View view, int position) {
rhemaHiveUserMessageModel = rhemaHiveUserMessageModels.get(position);
retreiveRecId = rhemaHiveUserMessageModel.getReceiverId();
Toast.makeText(getContext(),"you are chatting with : " + rhemaHiveUserMessageModel.getReceiverName(),RhemaHiveClassReferenceConstants.TOAST_LONG_LEN).show();
try {
//sendMessage("How are you",getCurrentDateTime(),RhemaHiveInstanceManagerClass.getRhemaHiveUserSubClass().getMessageType(0),false, getUid(),"hLqcai3Hn0YEGz2oINECMK0GGOF2",RhemaHiveInstanceManagerClass.getRhemaHiveUserSubClass().getMessageStatus(0),retrChurchName(getUid()));
//RhemaHiveMessageAreaFragment mFrag = new RhemaHiveMessageAreaFragment();
recIdBund.putString("rId", retRecId());
messageAreaIntent.putExtras(recIdBund);
startActivity(messageAreaIntent);
} catch (NullPointerException e) {
getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + e.getLocalizedMessage() , RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
retrieveChatList(retrChurchName(getUid()),"RhemaHiveUser");
} catch (Exception e) {
Toast.makeText(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + e.getLocalizedMessage(),RhemaHiveClassReferenceConstants.TOAST_LONG_LEN).show();
}
return v;
}
THIS IS THE RETRIEVE CHURCH NAME METHOD
public String retrChurchName(String uid) throws NullPointerException{
if (networkInfo != null && networkInfo.isConnectedOrConnecting() && networkInfo.isConnected()) {
collRef = fStore.collection("rhema_churches");
collRef.whereEqualTo("user_uid", uid).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if(!queryDocumentSnapshots.getDocuments().isEmpty()){
for(DocumentSnapshot doc : queryDocumentSnapshots.getDocuments()){
churchName = doc.getString("user_church");
// getAuto().getToast(getContext(),"Church Retreived : " + churchName,RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
}
else{
getAuto().getToast(getContext(), "Oops ! ! Sorry no chat to retreive", RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + e.getLocalizedMessage(), RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
});
}
else{
getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + networkInfo.getExtraInfo(), RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}
return churchName;
}
Firebase Firestore structure

Android : UI and data not survive when screen rotation in MVVM pattern

I try to implement MVVM by Mindorks to show data from here :(https://api.themoviedb.org/3/movie/384018?api_key=67bc513a7a353631119fdffe5f7377a8&language=en-US) in my Activity. I try using databinding for update UI, everything is going well untill I try to rotate my screen, I see from my logcat the data is always reload and my ImageView is always refresh, this is my Activity:
public class DetailActivity extends BaseActivity<ActivityDetailBinding, DetailViewModel> implements DetailNavigator {
#Inject
ViewModelProviderFactory factory;
private DetailViewModel detailViewModel;
public static final String INTENT_ID = "id_intent";
public static final String INTENT_FLAG = "id_flag";
private ActivityDetailBinding mActivityDetailBinding;
public static Intent newIntent(Context context) {
return new Intent(context, DetailActivity.class);
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.activity_detail;
}
#Override
public DetailViewModel getViewModel() {
detailViewModel = ViewModelProviders.of(this, factory).get(DetailViewModel.class);
return detailViewModel;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
detailViewModel.setNavigator(this);
mActivityDetailBinding = getViewDataBinding();
initView();
initData(savedInstanceState);
}
private void initData(Bundle savedInstanceState) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int id = extras.getInt(INTENT_ID, 0);
int flag = extras.getInt(INTENT_FLAG, 0);
detailViewModel.fetchDetail(id, flag);
}
}
private void initView() {
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
#Override
public void ShowProgressDialog(Boolean loading) {
if (loading) {
showLoading();
} else {
hideLoading();
}
}
}
and my BaseActivity like this :
public abstract class BaseActivity<T extends ViewDataBinding, V extends BaseViewModel> extends AppCompatActivity
implements BaseFragment.Callback {
// TODO
// this can probably depend on isLoading variable of BaseViewModel,
// since its going to be common for all the activities
private ProgressDialog mProgressDialog;
private T mViewDataBinding;
private V mViewModel;
/**
* Override for set binding variable
*
* #return variable id
*/
public abstract int getBindingVariable();
/**
* #return layout resource id
*/
public abstract
#LayoutRes
int getLayoutId();
/**
* Override for set view model
*
* #return view model instance
*/
public abstract V getViewModel();
#Override
public void onFragmentAttached() {
}
#Override
public void onFragmentDetached(String tag) {
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
performDependencyInjection();
super.onCreate(savedInstanceState);
performDataBinding();
}
public T getViewDataBinding() {
return mViewDataBinding;
}
#TargetApi(Build.VERSION_CODES.M)
public boolean hasPermission(String permission) {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
public void hideKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
public void hideLoading() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.cancel();
}
}
public void showLoading() {
hideLoading();
mProgressDialog = CommonUtils.showLoadingDialog(this);
}
public boolean isNetworkConnected() {
return NetworkUtils.isNetworkConnected(getApplicationContext());
}
public void performDependencyInjection() {
AndroidInjection.inject(this);
}
#TargetApi(Build.VERSION_CODES.M)
public void requestPermissionsSafely(String[] permissions, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
}
// public void showLoading() {
// hideLoading();
// mProgressDialog = CommonUtils.showLoadingDialog(this);
// }
private void performDataBinding() {
mViewDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
this.mViewModel = mViewModel == null ? getViewModel() : mViewModel;
mViewDataBinding.setVariable(getBindingVariable(), mViewModel);
mViewDataBinding.setLifecycleOwner(this);
mViewDataBinding.executePendingBindings();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
this is my ViewModelFactory class :
#Singleton
public class ViewModelProviderFactory extends ViewModelProvider.NewInstanceFactory {
private final DataManager dataManager;
private final SchedulerProvider schedulerProvider;
#Inject
public ViewModelProviderFactory(DataManager dataManager,
SchedulerProvider schedulerProvider) {
this.dataManager = dataManager;
this.schedulerProvider = schedulerProvider;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
if (modelClass.isAssignableFrom(DetailViewModel.class)) {
return (T) new DetailViewModel(dataManager,schedulerProvider);
}
throw new IllegalArgumentException("Unknown class name");
}
}
this is my ViewModel class :
public class DetailViewModel extends BaseViewModel<DetailNavigator> {
private final ObservableField<String> originalName = new ObservableField<>();
private final ObservableField<String> releaseDate = new ObservableField<>();
private final ObservableField<String> overview = new ObservableField<>();
private final ObservableField<String> genreMovie = new ObservableField<>();
private final ObservableField<String> posterPath = new ObservableField<>();
private final ObservableField<String> voteAverage = new ObservableField<>();
public DetailViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
super(dataManager, schedulerProvider);
}
public void fetchDetail(int id, int flag) {
if (flag == 1) {
getNavigator().ShowProgressDialog(true);
getCompositeDisposable().add(getDataManager()
.getApiHelper().doDetailMovie(id, URLConfig.API_KEY, getDataManager().getLanguage())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(detailResponse -> {
setUpData(detailResponse);
getNavigator().ShowProgressDialog(false);
// getNavigator().updateView();
}, throwable -> {
getNavigator().ShowProgressDialog(false);
}));
} else if (flag == 2) {
getNavigator().ShowProgressDialog(true);
getCompositeDisposable().add(getDataManager()
.getApiHelper().doDetailTV(id, URLConfig.API_KEY, getDataManager().getLanguage())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(detailResponse -> {
setUpData(detailResponse);
getNavigator().ShowProgressDialog(false);
}, throwable -> {
getNavigator().ShowProgressDialog(false);
}));
}
}
private void setUpData(DetailResponse detailResponse) {
if (detailResponse.getOriginal_name() != null) {
originalName.set(detailResponse.getOriginal_name());
} else if (detailResponse.getOriginal_title() != null) {
originalName.set(detailResponse.getOriginal_title());
} else {
}
if (detailResponse.getFirst_air_date() != null) {
releaseDate.set(detailResponse.getFirst_air_date());
} else {
releaseDate.set(detailResponse.getRelease_date());
}
if (!detailResponse.getOverview().equals("")) {
overview.set(detailResponse.getOverview());
} else {
overview.set(getNavigator().noDesc());
}
posterPath.set(String.valueOf(detailResponse.getPoster_path()));
voteAverage.set(String.valueOf(detailResponse.getVote_average()));
String genres = "";
for (int i = 0; i < detailResponse.getGenreList().size(); i++) {
genres = genres + detailResponse.getGenreList().get(i).getName();
if (i != detailResponse.getGenreList().size() - 1) {
genres = genres + ", ";
}
}
genreMovie.set(genres);
}
public ObservableField<String> getOriginalName() {
return originalName;
}
public ObservableField<String> getReleaseDate() {
return releaseDate;
}
public ObservableField<String> getOverview() {
return overview;
}
public ObservableField<String> getGenreMovie() {
return genreMovie;
}
public ObservableField<String> getPosterPath() {
return posterPath;
}
public ObservableField<String> getVoteAverage() {
return voteAverage;
}
}
and this is my DetailResponse Class :
public class DetailResponse {
#SerializedName("original_name")
private String original_name ;
#SerializedName("original_title")
private String original_title ;
#SerializedName("release_date")
private String release_date ;
#SerializedName("first_air_date")
private String first_air_date ;
#SerializedName("vote_average")
private Double vote_average ;
#SerializedName("overview")
private String overview ;
#SerializedName("poster_path")
private String poster_path;
#SerializedName("genres")
private List<Genre> genreList;
public String getOriginal_name() {
return original_name;
}
public String getOriginal_title() {
return original_title;
}
public String getRelease_date() {
return release_date;
}
public String getFirst_air_date() {
return first_air_date;
}
public Double getVote_average() {
return vote_average;
}
public String getOverview() {
return overview;
}
public String getPoster_path() {
return poster_path;
}
public List<Genre> getGenreList() {
return genreList;
}
public static class Genre{
#SerializedName("name")
private String name ;
public String getName() {
return name;
}
}
}
and last one, here how I try to get data in my UI using databinding, this is my layout :
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.detail.DetailActivity">
<data>
<import type="android.view.View" />
<variable
name="viewModel"
type="id.dicoding.eriza.moviecatalogue.ui.detail.DetailViewModel" />
</data>
<androidx.core.widget.NestedScrollView
android:id="#+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:animateLayoutChanges="true">
<com.github.florent37.shapeofview.shapes.ArcView
android:id="#+id/shape_header"
android:layout_width="match_parent"
android:layout_height="#dimen/size300dp"
android:alpha="0.7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:shape_arc_cropDirection="outside"
app:shape_arc_height="#dimen/size30dp"
app:shape_arc_position="bottom">
<com.flaviofaria.kenburnsview.KenBurnsView
android:id="#+id/image_header"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/poster_avengerinfinity"
app:imageDetailUrl="#{viewModel.posterPath}"
android:tint="#6F000000" />
</com.github.florent37.shapeofview.shapes.ArcView>
<com.github.florent37.shapeofview.shapes.RoundRectView
android:id="#+id/shape_poster"
android:layout_width="#dimen/size150dp"
android:layout_height="#dimen/size200dp"
android:layout_marginTop="#dimen/margin250dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/shape_header"
app:shape_roundRect_bottomLeftRadius="#dimen/corner10dp"
app:shape_roundRect_bottomRightRadius="#dimen/corner10dp"
app:shape_roundRect_topLeftRadius="#dimen/corner10dp"
app:shape_roundRect_topRightRadius="#dimen/corner10dp">
<ImageView
android:id="#+id/image_poster"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/hint_poster"
android:scaleType="fitXY"
app:imageDetailUrl="#{viewModel.posterPath}"
android:src="#drawable/poster_avengerinfinity" />
</com.github.florent37.shapeofview.shapes.RoundRectView>
<TextView
android:id="#+id/text_title"
style="#style/FontText.Title.Detail"
android:layout_marginTop="#dimen/margin15dp"
android:textSize="#dimen/font_large_size"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/shape_poster"
android:text="#{viewModel.originalName}"
tools:text="#string/hint_title" />
<TextView
android:id="#+id/text_title_release"
style="#style/FontText"
android:layout_marginTop="#dimen/margin10dp"
android:text="#string/text_release"
app:layout_constraintEnd_toStartOf="#+id/guideline"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
app:layout_constraintTop_toBottomOf="#+id/text_title" />
<TextView
android:id="#+id/text_release"
style="#style/FontText"
android:layout_marginStart="#dimen/margin2dp"
android:layout_marginTop="#dimen/margin10dp"
android:text="#{viewModel.releaseDate}"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
app:layout_constraintStart_toEndOf="#+id/text_title_release"
app:layout_constraintTop_toBottomOf="#+id/text_title"
tools:text="#string/hint_release" />
<TextView
android:id="#+id/text_genres"
style="#style/FontText.Normal"
android:layout_marginStart="#dimen/margin15dp"
android:layout_marginTop="#dimen/margin10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_release"
android:text="#{viewModel.genreMovie}"
tools:text="#string/hint_genres" />
<RatingBar
android:id="#+id/rating_bar"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_marginStart="#dimen/margin15dp"
android:layout_marginTop="#dimen/margin5dp"
android:isIndicator="true"
android:numStars="5"
android:rating="3.8"
android:stepSize="0.1"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
app:layout_constraintStart_toStartOf="parent"
app:ratingBar="#{viewModel.voteAverage}"
app:layout_constraintTop_toBottomOf="#+id/text_genres" />
<TextView
android:id="#+id/text_rating"
style="#style/FontText.Rating.Orange"
android:layout_marginStart="#dimen/margin5dp"
app:layout_constraintRight_toLeftOf="parent"
app:layout_constraintStart_toEndOf="#+id/rating_bar"
app:layout_constraintTop_toBottomOf="#+id/text_genres"
android:text="#{viewModel.voteAverage}"
tools:text="#string/hit_rating" />
<TextView
android:id="#+id/text_default_rating"
style="#style/FontText.Rating"
android:textStyle="normal"
android:visibility="#{viewModel.isConnected ? View.VISIBLE : View.GONE}"
app:layout_constraintRight_toLeftOf="parent"
app:layout_constraintStart_toEndOf="#+id/text_rating"
app:layout_constraintTop_toBottomOf="#+id/text_genres"
android:text="#string/hint_default_rating" />
<TextView
android:id="#+id/text_desc"
style="#style/FontText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin15dp"
android:layout_marginTop="#dimen/margin25dp"
android:layout_marginEnd="#dimen/margin15dp"
android:paddingBottom="#dimen/padding100dp"
app:layout_constraintTop_toBottomOf="#+id/rating_bar"
android:text="#{viewModel.overview}"
tools:text="#string/hint_desc" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</layout>
I think ViewModelshould manages UI that related data in Activity lifecycle, and tt allows to survive configuration changes in the Application, but in my case, the data is survive, but when I check on my logcat the fetchDetail() in DetailViewModel class is always call when screen rotation, and my ImageView is also refresh when I rotate my screen, so I think the viewModel not manage my UI when screen rotation. is there any problem with my code?
hope anybody can help me to show me where is my fault and what I must do. Thank you very much.

How to display firebase realtime multiple child into recyclerview with cardview? [duplicate]

I am trying to display my data from firebase real time database on a listview in the main menu screen once the users log in. The app is running but its not displaying the data.
This is the data in my database
Now for the codes.
MainMenu.java This function is called on the OnCreate().
public void makeItem ()
{
lv = findViewById(R.id.listView);
db = FirebaseDatabase.getInstance().getReference();
helper = new FirebaseHelper(db);
adapter= new AdapterItem(this,helper.retrive());
lv.setAdapter(adapter);
}
CustomListAdapter.java
public class CustomListAdapter{
private String ItemName;
private String Quantity;
private String SerialNo;
private String SupplierName;
private String SupplierEmail;
private String SupplierPhone;
public CustomListAdapter(){
}
public CustomListAdapter (String ItemName,String Quantity,String SerialNo,String SupplierName,String SupplierEmail,String SupplierPhone)
{
this.ItemName = ItemName;
this.Quantity = Quantity;
this.SerialNo = SerialNo;
this.SupplierName = SupplierName;
this.SupplierEmail = SupplierEmail;
this.SupplierPhone = SupplierPhone;
}
public void setItemName (String ItemName)
{
this.ItemName = ItemName;
}
public String getItemName ()
{
return ItemName;
}
public void setQuantity (String Quantity)
{
this.Quantity = Quantity;
}
public String getQuantity ()
{
return Quantity;
}
public void setSerialNo (String SerialNo)
{
this.SerialNo = SerialNo;
}
public String getSerialNo ()
{
return SerialNo;
}
public void setSupplierName (String SupplierName)
{
this.SupplierName = SupplierName;
}
public String getSupplierName()
{
return SupplierName;
}
public void setSupplierEmail (String SupplierEmail)
{
this.SupplierEmail = SupplierEmail;
}
public String getSupplierEmail() {
return SupplierEmail;
}
public void setSupplierPhone (String SupplierPhone)
{
this.SupplierPhone = SupplierPhone;
}
public String getSupplierPhone() {
return SupplierPhone;
}
}
AdapterItem.java
public class AdapterItem extends BaseAdapter {
Context c;
ArrayList<CustomListAdapter> customListAdapters;
public AdapterItem(Context c, ArrayList<CustomListAdapter> customListAdapters) {
this.c = c;
this.customListAdapters = customListAdapters;
}
#Override
public int getCount() {
return customListAdapters.size();
}
#Override
public Object getItem(int position) {
return customListAdapters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
convertView=LayoutInflater.from(c).inflate(R.layout.content_main_menu_list,parent,false);
}
TextView ItemName = convertView.findViewById(R.id.name);
TextView SerialNo = convertView.findViewById(R.id.serialNo);
TextView SupplierName = convertView.findViewById(R.id.supplierName);
TextView amount = convertView.findViewById(R.id.amount);
final CustomListAdapter CLA = (CustomListAdapter) this.getItem(position);
ItemName.setText(CLA.getItemName());
SerialNo.setText(CLA.getSerialNo());
SupplierName.setText(CLA.getSupplierName());
amount.setText(CLA.getQuantity());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c,CLA.getItemName(),Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
content_main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main_menu">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
content_main_menu_list.xml is a custom layout that i created for every data set to be displayed.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="#+id/serialNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/supplierName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintTop_toBottomOf="#+id/serialNo" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="23dp"
android:layout_marginBottom="8dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0171B0"
app:layout_constraintBottom_toTopOf="#+id/serialNo" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
The problem in your code lies in the fact that you have in your CustomListAdapter class a field named ItemName but you are using a getter named getItemName(), which is not correct since Firebase is looking in the database for a field named itemName and not ItemName. See the lowercase i letter vs. capital letter I?
There are two ways in which you can solve this problem. The first one would be to change your model class by renaming the fields according to the Java Naming Conventions. So you model class should look like this:
public class CustomListAdapter {
private String itemName, quantity, serialNo, supplierName, supplierEmail, supplierPhone;
public CustomListAdapter() {}
public CustomListAdapter(String itemName, String quantity, String serialNo, String supplierName, String supplierEmail, String supplierPhone) {
this.itemName = itemName;
this.quantity = quantity;
this.serialNo = serialNo;
this.supplierName = supplierName;
this.supplierEmail = supplierEmail;
this.supplierPhone = supplierPhone;
}
public String getItemName() { return itemName; }
public String getQuantity() { return quantity; }
public String getSerialNo() { return serialNo; }
public String getSupplierName() { return supplierName; }
public String getSupplierEmail() { return supplierEmail; }
public String getSupplierPhone() { return supplierPhone; }
}
See in this example, there are private fields and public getters. There is also a simpler solution, to set the value directly on public fields like this:
public class CustomListAdapter {
public String itemName, quantity, serialNo, supplierName, supplierEmail, supplierPhone;
}
Now just remove the current data and add it again using the correct names. This solution will work only if you are in testing phase.
There is also the second approach, which is to use annotations. So if you prefer to use private fields and public getters, you should use the PropertyName annotation only in front of the getter. So your CustomListAdapter class should look like this:
public class CustomListAdapter {
private String ItemName;
private String Quantity;
private String SerialNo;
private String SupplierName;
private String SupplierEmail;
private String SupplierPhone;
public CustomListAdapter() {}
public CustomListAdapter(String itemName, String quantity, String serialNo, String supplierName, String supplierEmail, String supplierPhone) {
ItemName = itemName;
Quantity = quantity;
SerialNo = serialNo;
SupplierName = supplierName;
SupplierEmail = supplierEmail;
SupplierPhone = supplierPhone;
}
#PropertyName("ItemName")
public String getItemName() { return ItemName; }
#PropertyName("Quantity")
public String getQuantity() { return Quantity; }
#PropertyName("SerialNo")
public String getSerialNo() { return SerialNo; }
#PropertyName("SupplierName")
public String getSupplierName() { return SupplierName; }
#PropertyName("SupplierEmail")
public String getSupplierEmail() { return SupplierEmail; }
#PropertyName("SupplierPhone")
public String getSupplierPhone() { return SupplierPhone; }
}

Retrieve result through REST API and show it in a LIST VIEW in a new activity (Minor issue arises with LIST VIEW)

I am retrieving data from a JOB site through REST api. I am able to retrieve the data and even can show that in the same page after Search button. But, I want to show the list view in the new activity . I am using Intent to do this. But, Unfortunately, I am unable to show that. My app crashes and outputs nothing, once I click on it.
MAIN ACTIVITY.java
public class MainActivity extends Activity {
//private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
//private String url2 = "&mode=xml";
EditText queryText;
EditText locationText;
EditText sortText;
EditText fromAgeText;
ListView responseView;
// EditText radiusText;
ProgressBar progressBar;
EditText jtText;
EditText chnlText;
EditText countryText;
EditText txText;
static final String API_KEY = "298**70********4";
static final String API_URL = "http://api.xyz.com/abc/apisearch?";
ProgressDialog waitProgress;
EditText startText;
EditText limitRes;
EditText filterText;
EditText userIpText; //="122.171.57.131";
EditText radiusText;
EditText browserText;
EditText version;
EditText stText;
EditText latlongText;
//private HandleXML obj;
String finalUrl;
ArrayList<Result> rList = null;
ArrayList<Result> resultlist;
String tempResponse;
private PostBaseAdapter adapter;
ListView list;
Result result;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializeUI("java","bangalore","karnataka","date","25","jobsite","fulltime","0","15","14","1","1","india","null","122.172.176.113","chrome","2");
initializeUI();
}
//responseView = (ListView) findViewById(R.id.responseView);
private void initializeUI() {
queryText = (EditText) findViewById(R.id.queryText);
locationText = (EditText) findViewById(R.id.locationText);
txText = (EditText) findViewById(R.id.txText);
sortText = (EditText) findViewById(R.id.sortText);
radiusText = (EditText) findViewById(R.id.radiusText);
stText = (EditText) findViewById(R.id.stText);
jtText = (EditText) findViewById(R.id.jtText);
//startText = (EditText) findViewById(R.id.startText);
limitRes = (EditText) findViewById(R.id.limitRes);
fromAgeText = (EditText) findViewById(R.id.fromAgeText);
//filterText = (EditText) findViewById(R.id.filterText);
//latlongText = (EditText) findViewById(R.id.latlongText);
countryText = (EditText) findViewById(R.id.countryText);
//chnlText = (EditText) findViewById(R.id.chnlText);
userIpText = (EditText) findViewById(R.id.userIpText);
//browserText = (EditText) findViewById(R.id.browserText);
//version = (EditText) findViewById(R.id.version);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
Button queryButton = (Button) findViewById(R.id.queryButton);
//list = (ListView) findViewById(R.id.resultList);
queryButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String query = queryText.getText().toString();
String location = locationText.getText().toString();
String tx = txText.getText().toString();
String sort = sortText.getText().toString();
String radius = radiusText.getText().toString();
String st = stText.getText().toString();
String jobtype = jtText.getText().toString();
//String start = startText.getText().toString();
String limit = limitRes.getText().toString();
String fromAge = fromAgeText.getText().toString();
//String filter = filterText.getText().toString();
//String latlong = latlongText.getText().toString();
String country = countryText.getText().toString();
//String chnlTxt = chnlText.getText().toString();
String userIp = userIpText.getText().toString();
//String browser = browserText.getText().toString();
//String versionTx = version.getText().toString();
//ArrayList<String> arl= new ArrayList<String>();
//arl.add(query);
new RetrieveFeedTask().execute(query, location, tx, sort, radius, st, jobtype,"1",limit,fromAge,"1","1",country,"null",userIp, "chrome","2");
//responseView.setText(url);
Log.e("ERROR","In button call");
Log.i("INFO","Inside Button call");
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.tvTitle)).getText().toString();
// create intent to start another activity
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
// add the selected text item to our intent.
intent.putExtra("title", name);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<String, String, String> {
private Exception exception;
String tempResponse = "";
protected void onPreExecute() {
waitProgress = ProgressDialog.show(MainActivity.this, "", "Loading... please wait...");
// progressBar.setVisibility(View.VISIBLE);
// responseView.setAdapter(null);//.setText(" ");
Log.e("ERROR","In onPreExecute call");
Log.i("INFO","Inside onPreExecutecall");
}
protected String doInBackground(String... args) {
// Do some validation here
String query = args[0];
String location = args[1];
String tx = args[2];
String sort = args[3];
String radius = args[4];
String st = args[5];
String jobtype = args[6];
String start = args[7];
String limit = args[8];
String fromAge = args[9];
String filter = args[10];
String latlong = args[11];
String country = args[12];
String chnlTxt = args[13];
String userIp = args[14];
String browser = args[15];
String versionTx = args[16];
finalUrl = API_URL + "publisher=" + API_KEY + "&q=" + query + "&l=" + location + "," + tx + "&sort=" + sort + "&radius=" + radius + "&st=" + st + "&jt=" + jobtype + "&start=" + start + "&limit=" + limit + "&fromage=" + fromAge + "&filter=" + filter + "&latlong=" + latlong + "&co=" + country + "&chnl=" + chnlTxt + "&userip=" + userIp + "&useragent=" + browser + "&v=" + versionTx;
//finalUrl= "http://api.xyz.com/ads/apisearch?publisher=2986470692413324&q=java&l=BANGALORE%2C+karnataka&sort=date&radius=25&st=jobsite&jt=fulltime&start=1&limit=10&fromage=14&filter=1&latlong=1&co=india&chnl=null&userip=122.166.158.225&useragent=Chrome&v=2";
SAXParser();
return "";
}
protected void onPostExecute(String response) {
/* if (response == null || response.trim().equals("")) {
response = "THERE WAS AN ERROR";
}*/
/* if (rList == null) {
responseView.setAdapter(null); //setText("Error");
//return;
}*/
// progressBar.setVisibility(View.GONE);
//Log.i("INFO", response);
// getting values from selected ListItem
// Bundle bundle= new Bundle();
String name = ((TextView) findViewById(R.id.tvTitle)).getText().toString();
Bundle bundle= new Bundle();
// create intent to start another activity
//bundle.putString("name",result.getJobtitle());
Intent intent2 = new Intent(MainActivity.this, ResultListView.class);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
// add the selected text item to our intent.
//intent2.putExtra("title", name);
bundle.putString("title",name);
intent2.putExtra("pBundle",bundle);
startActivity(intent2);
//displayData();
if (waitProgress != null) {
waitProgress.dismiss();
}
}
/* protected void onPostExecute()
{ progressBar.setVisibility(View.GONE);
displayData();
}*/
private void SAXParser(){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
//XMLReader xmlreader = factory.getXMLReader();
SAXParser parser = factory.newSAXParser();
resultlist = new ArrayList<Result>();
URL ul = new URL(finalUrl);
URLConnection uc = ul.openConnection();
ResultHandler resultHandler = new ResultHandler(resultlist);
// assign our handler
// xmlreader.setContentHandler(resultHandler);
// perform the synchronous parse
parser.parse(new InputSource(uc.getInputStream()), resultHandler);
resultlist = resultHandler.getResultList();
Log.e("ERROR","In SAXParser call");
Log.i("INFO","Inside SAXParser");
} catch (Exception e) {
e.printStackTrace();
}
Log.e("ERROR","In doInBackground call");
Log.i("INFO","Inside doInBackgr call");
// SAXParser();
}
}
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:fillViewport="true"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="portfolio.first_app.practice.com.simplewebapi3.xyzJobActivity">
<EditText
android:id="#+id/queryText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Skill"/>
<!--android:inputType="textEmailAddress"-->
<EditText
android:id="#+id/locationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Location"/>
<EditText
android:id="#+id/txText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the State"/>
<EditText
android:id="#+id/sortText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Date"/>
<EditText
android:id="#+id/radiusText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Radius"/>
<EditText
android:id="#+id/stText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Site Type"/>
<EditText
android:id="#+id/jtText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Job Type"/>
<!-- <EditText
android:id="#+id/startText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Start Index of the Result"/>-->
<EditText
android:id="#+id/limitRes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Result Limit"/>
<EditText
android:id="#+id/fromAgeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Age"/>
<!-- <EditText
android:id="#+id/filterText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Duplicate filter value"/>
<EditText
android:id="#+id/latlongText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the value 1 or 0"/>-->
<EditText
android:id="#+id/countryText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Country"/>
<!-- <EditText
android:id="#+id/chnlText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Group channel"/>-->
<EditText
android:id="#+id/userIpText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the User IP address"/>
<!-- <EditText
android:id="#+id/browserText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Browser"/>
<EditText
android:id="#+id/version"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the Version:"/>-->
<Button
android:id="#+id/queryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Search"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:layout_centerHorizontal="true"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
ResultListView.java
/**
* Created by SouRAV on 6/15/2016.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by SouRAV on 6/15/2016.
*/
public class ResultListView extends Activity {
TextView textView;
ListView list;
ArrayList<Result> resultlist;
private PostBaseAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_list_view);
list = (ListView) findViewById(R.id.resultList);
textView = (TextView) findViewById(R.id.textView);
// get the intent from which this activity is called.
Intent intent2 = getIntent();
Bundle bundle= intent2.getBundleExtra("pBundle");
String text = bundle.getString("title");
textView.setText(text);
displayData1();
// fetch value from key-value pair and make it visible on TextView.
//Bundle intent2 = getIntent().getExtras();
//String list_data = intent2.getString("list");
// textView.setText(list_data);
}
private void displayData1() {
adapter = new PostBaseAdapter(ResultListView.this, resultlist);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Log.e("ERROR","In displayData call");
Log.i("Info","Inside displaydata");
//Log.i("INFO", response);
// responseView.setText(response);
// ProgressBar.dismiss();
}
}
result_list_view.xml
<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ListView android:id="#+id/resultList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</ListView>
</LinearLayout>
Result.java
package portfolio.first_app.practice.com.xyzjobactivity3;
/**
* Created by SouRAV on 4/29/2016.
*/
import java.util.ArrayList;
import java.util.ArrayList;
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I am not showing PARSING XML data as it is working fine. Issue is simple , I am using intent, but unable to display it in LIST VIEW. I am asking about the code inside postExecute();
Implement Result by Parcelable interface. Now after fetchind data from server, just put the ArrayList in intent, and retrieve them in ResultActivity.
In list.setItemClickListener -
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
intent.putParcelableArrayListExtra("RESULT", resultlist);
intent.putExtra("title", name);
startActivity(intent);
And again in onCreate of Result activity don't forget to initialize resultlist -
resultlist = getIntent().getParcelableArrayExtra("RESULT");
Hope it will help you :)

Categories

Resources