What is making my app crash without an error - crash

I am writing an app. that you can search info about celebs and save it to a SQlite database. I followed tutorials in showing the information but when I run the app it crashes without an error... please assist
When I request the data I only want the names display in a Listview, then when the user clicks on the name of the Celeb, it will open a page with all the saved data..I have no idea where to even start looking for the problem..I can open the app, save the data but when I open the activity to show the ListView it crashes without an error...
my xml for displaying the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:background="#drawable/mway"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#color/colorPrimaryDark"
android:text="#string/app_name"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_view"
android:background="#drawable/mway">
</ListView>
</LinearLayout>
Here is my java file for displaying the listview
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class viewceleb extends AppCompatActivity {
DatabaseHelper db;
ArrayList<String> listItems;
ArrayAdapter adapter;
ListView userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewceleb);
userList = findViewById(R.id.list_view);
listItems = new ArrayList<>();
viewData();
userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
String text = userList.getItemAtPosition(i).toString();
Toast.makeText(viewceleb.this, "Now something can happen", Toast.LENGTH_LONG).show();
}
});
}
private void viewData() {
Cursor cursor = db.viewData();
if (cursor.getCount()== 0){
Toast.makeText(this,"No Data To Show", Toast.LENGTH_LONG).show();
}else {
while(cursor.moveToNext()){
listItems.add(cursor.getString(1));//index 1 is name, 0 is ID
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
userList.setAdapter(adapter);
}
}
}

You are only declaring db, it needs to be instantiated.
That is you have DatabaseHelper db; and you additionall need db = new DatabaseHelper(?); where ? are the parameters required by the DatabaseHelper constructor. Typically just the Context so perhaps db = new DatabaseHelper(this);. This would be coded in the activity's onCreate method BEFORE calling the viewData method.
e.g.
public class viewceleb extends AppCompatActivity {
DatabaseHelper db;
ArrayList<String> listItems;
ArrayAdapter adapter;
ListView userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewceleb);
dn = new DatabaseHelper(this); //<<<<<<<<<< ADDED note just the context has been assumed, the parameters depend upon the constructor as per what is coded in the DatabaseHelper class.
userList = findViewById(R.id.list_view);
listItems = new ArrayList<>();
viewData();
userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
String text = userList.getItemAtPosition(i).toString();
Toast.makeText(viewceleb.this, "Now something can happen", Toast.LENGTH_LONG).show();
}
});
}
private void viewData() {
Cursor cursor = db.viewData();
if (cursor.getCount()== 0){
Toast.makeText(this,"No Data To Show", Toast.LENGTH_LONG).show();
}else {
while(cursor.moveToNext()){
listItems.add(cursor.getString(1));//index 1 is name, 0 is ID
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
userList.setAdapter(adapter);
}
}
}

Related

Modify all recycler view items show all view holder stacked values

I desire to update each item of a recycled view every second with a new value. But instead of viewing only all updated values, all viewHolders seems to be stacked.
My recyclerView is declared like this :
recyclerView = findViewById(R.id.recycle);
adapter = new ExampleAdapter();
LinearLayoutManager recyclerViewLayout = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewLayout);
recyclerView.setAdapter(adapter);
I update the list of the adapter like this :
ArrayList<Integer> newList = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
private void addNewInt() {
for (int i=0;i<newList.size();i++) {
newList.set(i, newList.get(i) + 10);
}
adapter.updateList(newList);
}
And this is my Adapter :
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ViewHolder> {
private ArrayList<Integer> list;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txt;
public ViewHolder(View view) {
super(view);
txt = view.findViewById(R.id.txt);
}
}
public ExampleAdapter() {
this.list = new ArrayList<>();
}
#Override
public ExampleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View cellView = inflater.inflate(R.layout.raw_example, parent, false);
return new ViewHolder(cellView);
}
#Override
public void onBindViewHolder(#NonNull ExampleAdapter.ViewHolder holder, int position) {
if (!list.isEmpty()) {
Integer val = list.get(position);
holder.txt.setText(Integer.toString(val));
}
}
#Override
public int getItemCount() {
return list.size();
}
public void updateList(ArrayList<Integer> newList) {
list.clear();
list.addAll(newList);
notifyDataSetChanged();
}
}
The problem does not seem to be linked with recycling. I tried to add holder.setIsRecyclable(false) to force recreate a new viewHolder without any effect.
I tried also to play with the recyclerView.getRecycledViewPool().setMaxRecycledViews and recyclerView.setItemViewCacheSize() methods without any success.
I try to use notifyItemRangeChange() instead of using the notifyDataSetChanged(). Nothing better.
I also try to force to clear the recyclerview before adding the new elements like this :
list.clear();
notifyDataSetChanged();
list.addAll(newList);
notifyDataSetChanged();
The xml of my Activity is the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp" >
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycle"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
What is wrong with my code?

Retrofit with recyclerview issue

I am not getting data in recycler view but not getting any error .
This is Main Activity class
package in.co.getonlinerecharge.cab.bw_cab.activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import in.co.getonlinerecharge.cab.bw_cab.AppController;
import in.co.getonlinerecharge.cab.bw_cab.R;
import in.co.getonlinerecharge.cab.bw_cab.adepter.CarTypeAdepter;
import in.co.getonlinerecharge.cab.bw_cab.helper.ToastHelper;
import in.co.getonlinerecharge.cab.bw_cab.model.Cartype;
import in.co.getonlinerecharge.cab.bw_cab.model.CartypeArray;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Slect_Car_Activity extends AppCompatActivity {
RecyclerView rvGetCartype;
private ArrayList<Cartype> data;
private CarTypeAdepter carTypeAdepter;
private TextView txt_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slect__car_);
rvGetCartype = (RecyclerView)findViewById(R.id.RV_list);
txt_data = (TextView)findViewById(R.id.txt_data);
getAndSetCarType();
}
private void getAndSetCarType() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog.show();
Call<CartypeArray> call = AppController.getInstance().getApiInterface().getCartype();
call.enqueue(new Callback<CartypeArray>() {
#Override
public void onResponse(Call<CartypeArray> call, Response<CartypeArray> response) {
progressDialog.dismiss();
CartypeArray cartypeArray = response.body();
Collections.reverse(cartypeArray.getCtypes());
carTypeAdepter = new CarTypeAdepter(cartypeArray,getApplicationContext());
rvGetCartype.setAdapter(carTypeAdepter);
}
#Override
public void onFailure(Call<CartypeArray> call, Throwable t) {
progressDialog.dismiss();
}
});
}
}
This is my model class for retrofit which gives Json array with status
package in.co.getonlinerecharge.cab.bw_cab.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Cartype {
#SerializedName("id")
#Expose
private String id;
#SerializedName("vehicle_type")
#Expose
private String Vehicale_type;
#SerializedName("vehicle_name")
#Expose
private String Vehicale_name;
#SerializedName("vehicle_no")
#Expose
private String Vehicale_no;
#SerializedName("vimage")
#Expose
private String Vimage;
#SerializedName("status")
#Expose
private String status;
#SerializedName("created_at")
#Expose
private String created_at;
#SerializedName("updated_at")
#Expose
private String updated_at;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVehicale_type() {
return Vehicale_type;
}
public void setVehicale_type(String vehicale_type) {
Vehicale_type = vehicale_type;
}
public String getVehicale_name() {
return Vehicale_name;
}
public void setVehicale_name(String vehicale_name) {
Vehicale_name = vehicale_name;
}
public String getVehicale_no() {
return Vehicale_no;
}
public void setVehicale_no(String vehicale_no) {
Vehicale_no = vehicale_no;
}
public String getVimage() {
return Vimage;
}
public void setVimage(String vimage) {
Vimage = vimage;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
This is my Adapter class with view holder for recycler view
package in.co.getonlinerecharge.cab.bw_cab.adepter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import in.co.getonlinerecharge.cab.bw_cab.R;
import in.co.getonlinerecharge.cab.bw_cab.model.Cartype;
import in.co.getonlinerecharge.cab.bw_cab.model.CartypeArray;
import in.co.getonlinerecharge.cab.bw_cab.utils.Constans;
public class CarTypeAdepter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private CartypeArray cartypeArray;
private Context mcontext;
public CarTypeAdepter(CartypeArray cartypeArray, Context mcontext) {
this.cartypeArray = cartypeArray;
this.mcontext = mcontext;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = (LayoutInflater.from(parent.getContext()).inflate(R.layout.list_car,parent, false));
CartypeHolder cartypeHolder = new CartypeHolder(view);
return cartypeHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder Holder, int position) {
CartypeHolder cartypeHolder = (CartypeHolder) Holder;
cartypeHolder.txt_cartype.setText(cartypeArray.getCtypes().get(position).getVehicale_name());
}
#Override
public int getItemCount() {
return cartypeArray.getCtypes().size();
}
private class CartypeHolder extends RecyclerView.ViewHolder {
ImageView img_car;
TextView txt_cartype;
public CartypeHolder(View itemview) {
super(itemview);
img_car = (ImageView)itemview.findViewById(R.id.CarImageView);
txt_cartype = (TextView)itemview.findViewById(R.id.titleTextView);
}
}
}
My second model class for retrofit for getting JSON data
package in.co.getonlinerecharge.cab.bw_cab.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class CartypeArray {
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("Cartype")
#Expose
private List<Cartype> ctypes;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public List<Cartype> getCtypes() {
return ctypes;
}
public void setCtypes(List<Cartype> ctypes) {
this.ctypes = ctypes;
}
}
This is Activity main XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical" tools:context="in.co.getonlinerecharge.cab.bw_cab.activity.Slect_Car_Activity">
<android.support.design.widget.AppBarLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="Select Your Car" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/RV_list"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt_data"/>
</LinearLayout>
List of display data for list view
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/card_height"
android:orientation="vertical"
>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/CarImageView"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:src="#drawable/suv"
/>
<TextView
android:layout_gravity="center"
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="SUV"
android:textSize="#dimen/card_text_size"
android:textColor="#color/colorPrimary"/>
</LinearLayout>
</android.support.v7.widget.CardView>
set Layout Manager to your recycler in onCreate:
rvGetCartype = (RecyclerView)findViewById(R.id.RV_list);
rvGetCartype.setLayoutManager(new LinearLayoutManager(this));
If it didnt help try next:
1.Make sure, that in your response ArrayList isnt empty.
2.If it isnt, try to next:
public class CarTypeAdepter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<Cartype> cartypeArray;
private Context mcontext;
public CarTypeAdapter(Context context){
this.mcontext = context;
cartypeArray = new ArrayList<>();
}
public void setList(ArrayList<Cartype> list){
this. cartypeArray = list;
notifyDataSetChanges();
}
//other methods
}
then create variable of this adapter in activity and init it in onCreate, and set it to your recycler view. Then in onResponse use method setList(cartypeArray) to set array to adapter.
Hope you understand me and its help.

Using Picasso Images not showing in Recycler view

I am trying to show images from a Firebase database in recycler view in android studio but the images are not displaying. I am not sure where I have gone wrong or what the problem is.
Main Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.test.test.AddBrandPage"
android:weightSum="1">
<TextView
android:id="#+id/editText"
android:layout_width="383dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Select your favourite stores..."
android:textAlignment="center"
android:textSize="22sp" />
<LinearLayout
android:id="#+id/alphaindex"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"></LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recylView"
android:layout_width="337dp"
android:layout_height="370dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editText2"
android:layout_marginLeft="14dp"
android:layout_marginRight="14dp"
android:layout_marginStart="14dp"
android:layout_marginTop="24dp"
android:layout_weight="0.23"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.11"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<Button
android:id="#+id/btn_skip"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"
android:layout_marginRight="15dp"
android:background="#color/colorPrimary"
android:text="Skip"
android:textAllCaps="true"
android:textColor="#android:color/background_light"
android:textSize="20sp"
android:textStyle="normal|bold" />
<Button
android:id="#+id/btn_submit"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginRight="20dp"
android:background="#color/colorPrimary"
android:text="Submit"
android:textAllCaps="true"
android:textColor="#android:color/background_light"
android:textSize="20sp"
android:textStyle="normal|bold" />
</LinearLayout>
</LinearLayout>
Logo_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardView="http://schemas.android.com/apk/res-auto"
android:id="#+id/logo_container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#android:color/darker_gray"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:visibility="visible"
cardView:layout_collapseParallaxMultiplier="1.0">
<android.support.v7.widget.CardView
android:layout_width="155dp"
android:layout_height="100dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
cardView:cardBackgroundColor="#android:color/white">
<GridLayout
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/img_logo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="1"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_row="0"
android:paddingBottom="5dp"
android:paddingLeft="2.5dp"
android:paddingRight="2.5dp"
android:paddingTop="5dp">
</ImageView>
</GridLayout>
<CheckBox
android:id="#+id/checkbox"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="130dp"
android:layout_marginTop="66dp"
/>
</android.support.v7.widget.CardView>
</LinearLayout>
LogoItems.java
public class LogoItems {
//declare variables(the items displayed in the layout)
private String logo;//, name;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
}
Main Activity.java
package com.test.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AddBrandPage extends AppCompatActivity implements OnClickListener {
//declare variables
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private DatabaseReference myRef;
private Button btn_skip;
private Button btn_submit;
//private String name;
//private String url;
List<LogoItems> brandLogo = new ArrayList<>();
//HashMap<String, String> dataSet = new HashMap<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_brand_page);
//initialize variables
btn_skip = (Button) findViewById(R.id.btn_skip);
btn_submit = (Button) findViewById(R.id.btn_submit);
myRef = FirebaseDatabase.getInstance().getReference().child("/brands");
// set the main recyclerview view in the layout
recyclerView = (RecyclerView) findViewById(R.id.recylView);
recyclerView.setHasFixedSize(true);
// set the main layoutManager of the recyclerview
layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
loadLogoImgData();
// set the recycler view adapter
adapter = new LogoAdapter(brandLogo, getBaseContext());
recyclerView.setAdapter(adapter);
//set the listener for the buttons click event
btn_skip.setOnClickListener(this);
btn_submit.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == btn_skip) {
//if skip button clicked close current window and go to user main page
finish();
startActivity(new Intent(getApplicationContext(), UserMainPage.class));
}
}
public void loadLogoImgData(){
brandLogo.clear();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value = brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails = new LogoItems();
// String name = value.getName();
String logos = value.getLogo();
//brandDetails.setName(name);
brandDetails.setLogo(logos);
brandLogo.add(brandDetails);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
LogoItemsAdapter.java
package com.test.test;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class LogoAdapter extends RecyclerView.Adapter<LogoAdapter.LogoViewHolder> {
List<LogoItems> brandLogo = new ArrayList<>();
// private AddBrandPage addBrandPage;
private Context context;
public LogoAdapter(List <LogoItems> brandLogo, Context context){
this.brandLogo = brandLogo;
this.context = context;
//addBrandPage = (AddBrandPage)context;
}
#Override
public LogoAdapter.LogoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.logo_items,parent,false);
LogoViewHolder logoViewHolder = new LogoViewHolder(view);
return logoViewHolder;
}
#Override
public void onBindViewHolder(LogoAdapter.LogoViewHolder holder, int position) {
//holder.logo.setImageURI(Uri.parse(brandLogo.get(position).getLogo()));
Picasso.with(context).load(brandLogo.get(position).getLogo()).into(holder.logo);
}
#Override
public int getItemCount() {
return brandLogo.size();
}
public static class LogoViewHolder extends RecyclerView.ViewHolder{
//declare variables
public ImageView logo;
CheckBox checkbox;
//private View itemView;
public LogoViewHolder(View itemView){
super(itemView);
//initialize variables inside the constructor
logo = (ImageView)itemView.findViewById(R.id.img_logo);
checkbox = (CheckBox)itemView.findViewById(R.id.checkbox);
// this.itemView = itemView;
}
}
}
your code seems a bit vague like here :
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails =
new LogoItems();
// String name = value.getName();
String logos = value.getLogo();
//brandDetails.setName(name);
brandDetails.setLogo(logos);
brandLogo.add(brandDetails); } }
Change this code to :
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
brandLogo.add(value); }
startRecyclerView();
}
Firebase methods are asynchronous, your present code inflates the recylcerview synchronously which means it is loaded before the data has been set and received.
The changed code starts recyclerview asynchronously after the data has been loaded from the database. You can add a progress bar to know the status. You can set it like this (Initialize it before this method and it will be visible by default) :
mProgressBar.setVisibility(View.INVISIBLE);
startRecyclerView();
This way the code looks organised.

StaggeredGridLayoutManager with recyclerview showing only two images per page

I have taken sample code from https://github.com/chrisbanes/cheesesquare as base to show images in StaggeredGridLayoutManager. StaggeredGridLayoutManager with recyclerview showing only two images per page.
I tried almost all ways to show multiple images in full page, but its not working.
Any help would be great.
fragment_cheese_list.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.support.android.designlibdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/color_primary_teal">
<!--<android.support.v7.widget.CardView-->
<!--xmlns:card_view="http://schemas.android.com/apk/res-auto"-->
<!--xmlns:android="http://schemas.android.com/apk/res/android"-->
<!--android:id="#+id/card_view"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--card_view:cardUseCompatPadding="true"-->
<!--card_view:cardCornerRadius="8dp"-->
<!--android:layout_marginBottom="16dp">-->
<!--<RelativeLayout-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent">-->
<!--<de.hdodenhof.circleimageview.CircleImageView-->
<!--android:id="#+id/avatar"-->
<!--android:layout_width="#dimen/list_item_avatar_size"-->
<!--android:layout_height="#dimen/list_item_avatar_size"-->
<!--android:layout_marginRight="16dp"/>-->
<ImageView
android:id="#+id/avatar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:onClick="getImageDetails" />
<TextView
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?attr/textAppearanceListItem"/>
<!--</RelativeLayout>-->
<!--</android.support.v7.widget.CardView>-->
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
CheeseListFragment.java
package com.support.android.designlibdemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class CheeseListFragment extends Fragment {
//private RecyclerView.StaggeredGridLayoutManager mLayoutManager;
int cheeseImages[]= {R.drawable.cheese_1,R.drawable.cheese_2,R.drawable.cheese_3,
R.drawable.cheese_4,R.drawable.cheese_5};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_cheese_list, container, false);
RecyclerView rv = (RecyclerView) relativeLayout.findViewById(R.id.recyclerview);
//RecyclerView rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
private void setupRecyclerView(RecyclerView recyclerView) {
//recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
ArrayList<ImageDetails> placeList = getPlaces();
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, 30), placeList));
}
private List<String> getRandomSublist(String[] array, int amount) {
ArrayList<String> list = new ArrayList<>(amount);
Random random = new Random();
while (list.size() < amount) {
list.add(array[random.nextInt(array.length)]);
}
return list;
}
private ArrayList<ImageDetails> getPlaces() {
ArrayList<ImageDetails> details = new ArrayList<>();
for (int index=0; index<30;index++){
details.add(new ImageDetails(Cheeses.getRandomCheeseDrawable()));
}
return details;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
private ArrayList<ImageDetails> mImagesList;
public static class ViewHolder extends RecyclerView.ViewHolder {
public String mBoundString;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString() {
return super.toString() + " '" + mTextView.getText();
}
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items, ArrayList<ImageDetails> imageList) {
// context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
// mBackground = mTypedValue.resourceId;
mValues = items;
mImagesList = imageList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
//view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mBoundString = mValues.get(position);
holder.mTextView.setText(mValues.get(position));
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, CheeseDetailActivity.class);
intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString);
context.startActivity(intent);
}
});
holder.mImageView.setImageResource(mImagesList.get(position).getImageUrl());
// Glide.with(holder.mImageView.getContext())
// .load(Cheeses.getRandomCheeseDrawable())
// .fitCenter()
// .into(holder.mImageView);
}
#Override
public int getItemCount() {
return mValues.size();
}
}
}
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
chnage layout height to wrap_content:-
android:layout_height="wrap_content"

Nullpointerexception on RecyclerView

All im trying to do is create a recyclerview inside of a tablayout i have tried setting up the adapter in the main activity as well as the fragment im using in the tablayout however either way im still getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{knightsrealms.managment_app/knightsrealms.managment_app.Dashboard}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
package knightsrealms.managment_app;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import java.util.ArrayList;
import java.util.Calendar;
public class Dashboard extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPageAdapter viewPagerAdapter;
ArrayList<knightsrealms.managment_app.Calendar> contacts = new ArrayList<knightsrealms.managment_app.Calendar>(5);
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
viewPagerAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
setSupportActionBar(toolbar);
final TabLayout.Tab messages = tabLayout.newTab();
final TabLayout.Tab dashboard = tabLayout.newTab();
messages.setText("Messages");
dashboard.setText("Dashboard");
tabLayout.addTab(dashboard, 0);
tabLayout.addTab(messages, 1);
tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
RecyclerView rvContacts = (RecyclerView)findViewById(R.id.rvcal);
contacts.add(0, new knightsrealms.managment_app.Calendar("Number 1",true));
contacts.add(1, new knightsrealms.managment_app.Calendar("Number 2",true));
CalendarAdapter adapter = new CalendarAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard_menu, menu);
return true;
}
void selectPage(int pageIndex){
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
}
this is my adapter
package knightsrealms.managment_app;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class CalendarAdapter extends RecyclerView.Adapter<CalendarAdapter.ViewHolder> {
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
public static class ViewHolder extends RecyclerView.ViewHolder {
// Your holder should contain a member variable
// for any view that will be set as you render a row
public TextView nameTextView;
public Button messageButton;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public ViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.contact_name);
messageButton = (Button) itemView.findViewById(R.id.message_button);
}
}
private List<Calendar> mContacts;
// Pass in the contact array into the constructor
public CalendarAdapter(List<Calendar> contacts) {
mContacts = contacts;
}
// Usually involves inflating a layout from XML and returning the holder
#Override
public CalendarAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.recyclercell, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
// Involves populating data into the item through holder
#Override
public void onBindViewHolder(CalendarAdapter.ViewHolder viewHolder, int position) {
// Get the data model based on position
Calendar contact = mContacts.get(position);
// Set item views based on the data model
TextView textView = viewHolder.nameTextView;
textView.setText(contact.getName());
Button button = viewHolder.messageButton;
if (contact.isOnline()) {
button.setText("Message");
button.setEnabled(true);
}
else {
button.setText("Offline");
button.setEnabled(false);
}
}
// Return the total count of items
#Override
public int getItemCount() {
return mContacts.size();
}
}
This code is for the fragment which is inside the tablayout
<android.support.v7.widget.RecyclerView
android:id="#+id/rvcal"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
And this is the main activity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:layout_below="#+id/tool_bar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
app:tabIndicatorHeight="3dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tabs"
/>
</RelativeLayout>
any insight/help into this is greatly appreciated thank you!!
have you already try in :
tabLayout.setupWithViewPager(viewPager);
Well because recyclerView is in your fragment xml not in your activity xml, thus the recyclerView is return null.
Ok, So your code is almost done, but you need 2 more things:
first, is a class that extends FragmentPagerAdapter for your ViewPager, I don't know if your ViewPageAdapter class is already do that, but let's assume you're not yet done that.
second, is a fragment for your FragmentPagerAdapter.
Oke Lets start :
Create FragmentContacts for the FragmentPagerAdapter, in this fragment you should manage your RecyclerView and it's adapter not in the Activity.
public class FragmentContacts extends Fragment {
ArrayList<knightsrealms.managment_app.Calendar> contacts = new ArrayList<knightsrealms.managment_app.Calendar>(5);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = (View) inflater.inflate(R.layout.your_fragment_xml, container, false);
contacts.add(0, new knightsrealms.managment_app.Calendar("Number 1",true));
contacts.add(1, new knightsrealms.managment_app.Calendar("Number 2",true));
CalendarAdapter adapter = new CalendarAdapter(contacts);
RecyclerView rvContacts = (RecyclerView) rootView.findViewById(R.id.rvcal);
rvContacts.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
rvContacts.setAdapter(adapter);
return rootView;
}
}
Lastly, back in your Dashboard Activity, in onCreate, setUp your Viewpager :
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPagerAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(0);
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new FragmentContacts();
if(position == 1) return new FragmentContacts();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "Messages";
if(position == 1) return "Dashboard";
throw new IllegalStateException("Unexpected position " + position);
}
}