how to get data from mysql database into recycler view? - java

I am making an app that let users create meetings and I would like the details of the meeting (eg name, type, location) in a recycler view.I ran the php code by itself and was able to get the values from the database.
Currently, I am getting an error of
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at in recyclerviewAdapter
holder.Name.setText(users.getName());
holder.Type.setText(users.getType());
holder.Location.setText(users.getLocation());
which is linked to
public class Users {
private String name,type,location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
recyclerviewAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserHolder>{
Context context;
List<Users> usersList;
public UserAdapter(Context context, List<Users> usersList) {
this.context = context;
this.usersList = usersList;
}
#NonNull
#Override
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View userLayout= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main2,parent,false);
return new UserHolder(userLayout);
}
#Override
public void onBindViewHolder(#NonNull UserHolder holder, int position) {
Users users=usersList.get(position);
holder.Name.setText(users.getName());
holder.Type.setText(users.getType());
holder.Location.setText(users.getLocation());
}
#Override
public int getItemCount() {
return usersList.size();
}
public class UserHolder extends RecyclerView.ViewHolder{
TextView Name,Type,Location;
public UserHolder(#NonNull View itemView){
super(itemView);
Name=itemView.findViewById(R.id.textTitle);
Type=itemView.findViewById(R.id.textType);
Location=itemView.findViewById(R.id.textLocation);
}
}
}
main activity code
public class MainActivity2 extends AppCompatActivity {
private static final String URL = "http://10.0.2.2/mad/activitydisplay.php";
RecyclerView recyclerView;
UserAdapter userAdapter;
List<Users> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
recyclerView = findViewById(R.id.recylcerList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
usersList=new ArrayList<>();
LoadAllUser();
}
private void LoadAllUser() {
JsonArrayRequest request =new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray array) {
for (int i=0;i<array.length();i++){
try {
JSONObject object=array.getJSONObject(i);
String name=object.getString("eventname").trim();
String type=object.getString("type").trim();
String location=object.getString("location").trim();
Users user= new Users();
user.setName(name);
user.setType(type);
user.setLocation(location);
usersList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
userAdapter=new UserAdapter(MainActivity2.this,usersList);
recyclerView.setAdapter(userAdapter);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(MainActivity2.this, error.toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue=Volley.newRequestQueue(MainActivity2.this);
requestQueue.add((request));
}
}
php code to get data from table
$sql="SELECT * FROM `activitytable` ";
$result=mysqli_query($conn,$sql);
$user=array();
while($row = mysqli_fetch_assoc($result)){
$index['eventname']=$row['eventname'];
$index['type']=$row['type'];
$index['location']=$row['location'];
array_push($user, $index);
}
echo json_encode($user);
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recylcerList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
activity_list resource file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textTitle"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textType"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textLocation"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>

instead of
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View userLayout= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main2,parent,false);
return new UserHolder(userLayout);
}
use this
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View userLayout= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_list ,parent,false);
return new UserHolder(userLayout);
}
because activity_main2 doesn't contain R.id.textTitle,R.id.textType,R.id.textLocation

check your xml(R.layout.activity_main2) looks like id of your view are from another layout

Related

recyclerview no showing data of firebase

I try to show data of firebase on a
recycler View but no work please help me what can to be the problem?
my code is down, I can to see space result on my view but not see data
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public ClienteAdapter(#NonNull FirestoreRecyclerOptions<cliente> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder viewHolder, int position, #NonNull cliente cli) {
viewHolder.name.setText(cli.getName());
viewHolder.address.setText(cli.getAddress());
viewHolder.phone.setText(cli.getPhone());
viewHolder.product.setText(cli.getProduct());
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_cliente_single, parent, false);
return new ViewHolder (v);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, address, phone, product;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nombre);
address = itemView.findViewById(R.id.direccion);
phone = itemView.findViewById(R.id.telefono);
product = itemView.findViewById(R.id.producto);
}
}
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/nombre"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Nombre" />
<TextView
android:id="#+id/direccion"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Direccion" />
<TextView
android:id="#+id/telefono"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Telefono" />
<TextView
android:id="#+id/producto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Producto" />
</LinearLayout>
here more code class
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/btn_inv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Inventario" />
<Button
android:id="#+id/btn_compras"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Compras" />
<Button
android:id="#+id/btn_sorteos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sorteos" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewSingle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
here more code class
Button btn_inv;
RecyclerView mRecycler;
ClienteAdapter mAdapter;
FirebaseFirestore mFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestore = FirebaseFirestore.getInstance();
mRecycler = findViewById(R.id.recyclerViewSingle);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
Query query = mFirestore.collection("cliente");
FirestoreRecyclerOptions<cliente> firestoreRecyclerOptions =
new FirestoreRecyclerOptions.Builder<cliente>().setQuery(query, cliente.class).build();
mAdapter = new ClienteAdapter(firestoreRecyclerOptions);
mAdapter.notifyDataSetChanged();
mRecycler.setAdapter(mAdapter);
btn_inv = findViewById(R.id.btn_inv);
btn_inv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, inventario.class)); }
});
}
#Override
protected void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mAdapter.stopListening();
}
layout inventario code here
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/nombre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="nombre"
android:inputType="textPersonName" />
<EditText
android:id="#+id/direccion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="direccion"
android:inputType="textPersonName" />
<EditText
android:id="#+id/telefono"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="telefono"
android:inputType="textPersonName" />
<EditText
android:id="#+id/producto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="producto"
android:inputType="textPersonName" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp" />
<Button
android:id="#+id/btn_act"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Actualizar" />
<Button
android:id="#+id/btn_guar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Guardar" />
<Button
android:id="#+id/btn_eli"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Eliminar" />
<Button
android:id="#+id/btn_bus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Buscar" />
<Button
android:id="#+id/btn_todo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ver Todos" />
</LinearLayout>
the class inventario code here
Button btn_act, btn_guar, btn_eli, btn_bus, btn_todo;
EditText nombre, direccion, telefono, producto;
private
more code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventario);
this.setTitle("Zona Inventario");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mfirestore = FirebaseFirestore.getInstance();
nombre = findViewById(R.id.nombre);
direccion = findViewById(R.id.direccion);
telefono = findViewById(R.id.telefono);
producto = findViewById(R.id.producto);
btn_act = findViewById(R.id.btn_act);
btn_guar = findViewById(R.id.btn_guar);
btn_eli = findViewById(R.id.btn_eli);
btn_bus = findViewById(R.id.btn_bus);
btn_todo = findViewById(R.id.btn_todo);
btn_guar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String namecli = nombre.getText().toString().trim();
String dircli = direccion.getText().toString().trim();
String telcli = telefono.getText().toString().trim();
String procli = producto.getText().toString().trim();
if (namecli.isEmpty() && dircli.isEmpty() && telcli.isEmpty() && procli.isEmpty()) {
Toast.makeText(getApplicationContext(), "Ingresar Los Datos", Toast.LENGTH_SHORT).show();
} else {
postDatos(namecli, dircli, telcli, procli);
}
}
});
}
private void postDatos(String namecli, String dircli, String telcli, String procli) {
Map<String, Object> map = new HashMap<>();
map.put("nombre", namecli);
map.put("direccion", dircli);
map.put("telefono", telcli);
map.put("producto", procli);
mfirestore.collection("cliente").add(map).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(inventario.this, "Creado Exitosamente!", Toast.LENGTH_SHORT).show();
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(inventario.this, "Error al Ingresar", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
please help me, what the problem on my program?

method of receiving data from firebase is not working

I am using the SwipeCard library and the shapeableimageview is stored in a separate xml file that is connected to the main layout activity xml. there is also an adapter for this SwipeCard. data is not received although there are no errors in the code
activity with receive method
private void getUsermenwomInfo()
{
DatabaseReference reference= FirebaseDatabase.getInstance().getReference()
.child("Userwoman_men");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()&&snapshot.getChildrenCount()>0)
{
String name=snapshot.child("name").getValue().toString();
nameusercard.setText(name);
if (snapshot.hasChild("image")) {
String image = snapshot.child("image").getValue().toString();
Picasso.get().load(image).into(imageosnovnoe);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
xml with shapeableimageview
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_gravity="center"
android:gravity="center"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_margin="15dp"
app:cardCornerRadius="15dp"
app:cardElevation="5dp">
<LinearLayout
android:id="#+id/linearmain"
android:layout_width="match_parent"
android:layout_height="400dp"
android:orientation="vertical">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/imageosnovnoe"
android:layout_width="match_parent"
android:layout_height="400dp"
android:backgroundTint="#color/white"
android:scaleType="fitXY"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearhori"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:layout_gravity="bottom"
android:weightSum="3">
<ImageView
android:id="#+id/like"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_weight="1"
android:src="#drawable/sas"
/>
<ImageView
android:id="#+id/disslike"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_weight="1"
android:src="#drawable/aan"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
her adapter java class
public class SwipeAdapter extends BaseAdapter {
private Context context;
private List<Integer> list;
public SwipeAdapter(Context context,List<Integer>list) {
this.context=context;
this.list=list;
}
#Override
public int getCount() {
return 20;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View view;
if(convertView==null)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_koloda,parent,false);
}else {
view=convertView;
}
return view;
}
}
how to change my code or write a new one so that image and textview data is taken from firebase and inserted into shapeableimageview and textview from this separate xml? and is it correct that I wrote the method inside the main activity and not in the adapter? Thanks in advance for your help

Android View InflateExeption showing up when trying to start an app

I'm new to android development, and I'm having issues with my app crashing when I'm trying to start it
This is the error message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cybermath/com.example.cybermath.modules.MainActivity}: android.view.InflateException: Binary XML file line #25: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
And this is the XML file for the data within recycler viewer:
'''
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="100"
android:gravity="center_vertical"
android:background="#color/colorPrimaryDark"
>
<TextView
android:id="#+id/account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="70"
android:background="#color/colorPrimary"
android:lines="1"
android:padding="10dp"
android:text="#string/app_name"
android:textColor="#color/colorText" >
</TextView>
<TextView
android:id="#+id/account_progress"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="20"
android:background="#color/colorPrimary"
android:text="Enter"
android:textSize="12sp"
android:textColor="#color/colorText"
>
</TextView>
'''
This is the XML for the MainActivity:
<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="match_parent"
tools:context="MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="416dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/informationView"
android:id="#+id/recyclerView">
</androidx.recyclerview.widget.RecyclerView>
<!--<TextView
android:id="#+id/informationView"
android:layout_width="408dp"
android:layout_height="50dp"
android:foregroundTint="#00050000"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:text="Choose an account"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.333"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>-->
</androidx.constraintlayout.widget.ConstraintLayout>
And here is the code for the MainActivity:
'''
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
// UI
private RecyclerView mRecyclerView;
// Variables
#NonNull
private ArrayList<Account> mAccounts = new ArrayList<>();
private AccountsRecyclerAdapter mAccountsRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_account_list);
mRecyclerView = findViewById(R.id.recyclerView);
initRecyclerView();
insertFakeAccounts();
}
private void insertFakeAccounts(){
for(int i = 0; i < 1000; i++){
Account account = new Account();
account.setName("title #" + i);
mAccounts.add(account);
}
mAccountsRecyclerAdapter.notifyDataSetChanged();
}
private void initRecyclerView(){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mAccountsRecyclerAdapter = new AccountsRecyclerAdapter(mAccounts);
mRecyclerView.setAdapter(mAccountsRecyclerAdapter);
}
'''
And my adapter public class AccountsRecyclerAdapter extends
RecyclerView.Adapter<AccountsRecyclerAdapter.ViewHolder> {
private ArrayList<Account> mAccounts = new ArrayList<>();
public AccountsRecyclerAdapter(ArrayList<Account> accounts) {
this.mAccounts = accounts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_account_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AccountsRecyclerAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(mAccounts.get(i).getName());
}
#Override
public int getItemCount() {
return mAccounts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.account_name);
}
}
Some if the thing are not as per requirement may cause an exception. Check for condition as
if(yourValue !=null && yourValue.equals("desired value"){
//do your stuff
}

Recycler View and Card View not displaying cards

This is my Activity:
public String id;
public String passPhrase;
public ArrayList<SongCell> songs;
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private RecyclerView.LayoutManager layoutManager;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs_view_layout);
Context context = this.getApplicationContext();
Bundle stateData = getIntent().getExtras();
try
{
id = stateData.getString("id");
passPhrase = stateData.getString("passPhrase");
ArrayList data;
recyclerView = (RecyclerView) findViewById(R.id.song_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<SongCell>();
for (int i=0; i<5;i++)
{
data.add(new SongCell("Song "+i,"Artist "+i, null));
}
myAdapter = new MyAdapter(data);
recyclerView.setAdapter(myAdapter);
}
catch(Exception e)
{
Log.d("Error: ", e.toString());
}
}
card.xml
<android.support.v7.widget.CardView android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dp"
>
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/song_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/song_name"
android:textSize="30sp"
android:text="Song Name"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#000000" />
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/vote_button"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:background="#drawable/arrow" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Activity.xml
<?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:background="#2d2d2d">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:layout_marginBottom="10dp"
android:background="#222222"></TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="10dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/featSongImage1"
android:contentDescription="#string/newsongimage"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/songname"
android:id="#+id/featSongName1" />
<ImageButton
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/featSongButt1"
android:background="#drawable/arrow"
android:contentDescription="#string/votearrow" />
</LinearLayout>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundGravity="fill_horizontal"
android:gravity="fill_horizontal|center">
<android.support.v7.widget.RecyclerView
android:id="#+id/song_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal" />
</TableRow>
</TableLayout>
</LinearLayout>
And this is my custom adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private ArrayList<SongCell> data;
public MyAdapter(ArrayList<SongCell> dataI)
{
data = dataI;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.song_card,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int pos) {
viewholder.songName.setText(data.get(pos).getName());
viewholder.artist.setText(data.get(pos).getArtist());
viewholder.image.setImageBitmap(data.get(pos).getArtwork());
}
#Override
public int getItemCount() {
return 0;
}
#Override
public int getItemViewType(int position) {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView songName;
TextView artist;
ImageView image;
ImageButton voteButton;
public ViewHolder(View v)
{
super(v);
this.songName = (TextView) v.findViewById(R.id.song_name);
this.image = (ImageView) v.findViewById(R.id.song_photo);
this.voteButton = (ImageButton) v.findViewById(R.id.vote_button);
}
}
}
I have looked at a ton of guides on how to get this working but it still doesn't work. Anyone have any clue what's going on? I'm on version 25.0.1, and have all the modules imported. But it's not adding a single card into the layout.
I thought it would be difficult to debug such a big code you uploaded. But luckily my eye went on this line
#Override
public int getItemCount() {
return 0;
}
return 0; in adapter.
Your list size is always 0.
instead write this
#Override
public int getItemCount() {
return data.size();
}
EDIT-1:
You will also get null pointer exception here
viewholder.artist.setText(data.get(pos).getArtist());
Because you are not initializing the artist variable in ViewHolder class.
Edit-2
#Override
public int getItemCount() {
return 0;
}
you can remove this particular code from your adapter. Because overriding the methods of class that we don't use might sometimes result in errors that you can't even imagine.

Recycler's custom adapter methods are not called

i am using other layout elements and recyclerview in a layout and inflating cardview layout in oncreateViewHolder (custom adapter). Methods are only called when i just user recyclerview in a layout not with other layout elements.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_layout_for_item_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/detail_card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/detail_category_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:textStyle="bold"
android:layout_below="#+id/detail_category_price" />
<TextView
android:id="#+id/detail_category_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Rs: 1000" />
<Button
android:id="#+id/btn_bid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bid"
android:textColor="#color/colorPrimary"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/detail_category_price"
android:layout_margin="10dp"/>
<GridView
android:id="#+id/grid_view"
android:layout_below="#+id/btn_bid"
android:columnWidth="100dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</GridView>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:id="#+id/view"
android:layout_marginTop="5dp"
android:layout_below="#+id/grid_view"
android:background="#000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="About the seller"
android:layout_margin="5dp"
android:textSize="20sp"
android:textColor="#color/orange"
android:id="#+id/about_seller"
android:layout_below="#+id/view"
/>
<TextView
android:id="#+id/seller_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="username: bilal"
android:layout_margin="5dp"
android:layout_below="#+id/about_seller"/>
<Button
android:id="#+id/contact_seller_button"
android:text="contact button"
android:layout_margin="5dp"
android:layout_below="#+id/seller_user_name"
android:textColor="#color/colorPrimary"
android:shadowColor="#color/orange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.RecyclerView
android:id="#+id/bids_recycler_view"
android:layout_width="match_parent"
android:layout_below="#+id/detail_card_view"
android:layout_height="200dp"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
here is the layout that i am inflating
<android.support.v7.widget.CardView
android:layout_margin="5dp"
android:id="#+id/card_view"
android:layout_gravity="center"
android:background="#android:color/white"
app:cardElevation="2sp"
app:cardUseCompatPadding="true"
android:layout_width="match_parent"
android:layout_height="200dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/bid_text_View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="$10000"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#android:color/black"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/bidder_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bidder Name"
android:textStyle="italic"
android:textSize="16sp"
android:textColor="#android:color/black"
android:layout_below="#+id/bid_text_View"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</ScrollView>
here is the activity code ->
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private BidsAdapter mBidsAdapter;
private ArrayList<String> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_detials);
String detail = getIntent().getStringExtra(AppGlobals.detial);
setTitle(detail);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = (RecyclerView)findViewById(R.id.bids_recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout_for_item_detail);
mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green,
R.color.colorPrimary, R.color.gray);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.canScrollVertically(LinearLayoutManager.VERTICAL);
bitmapArrayList = new ArrayList<>();
arrayList = new ArrayList<>();
arrayList.add("test one");
arrayList.add("test two");
arrayList.add("test three");
arrayList.add("test four");
arrayList.add("test five");
}
#Override
protected void onResume() {
super.onResume();
mBidsAdapter = new BidsAdapter(arrayList);
mRecyclerView.setAdapter(mBidsAdapter);
System.out.println(mRecyclerView == null);
System.out.println(mBidsAdapter == null);
mRecyclerView.addOnItemTouchListener(new BidsAdapter(arrayList, getApplicationContext()
, new BidsAdapter.OnItemClickListener() {
#Override
public void onItem(String item) {
System.out.println(item);
}
}));
System.out.println("DONE");
}
static class BidsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements
RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
private BidView bidView;
private ArrayList<String> items;
public interface OnItemClickListener {
void onItem(String item);
}
public BidsAdapter(ArrayList<String> data) {
super();
this.items = data;
}
public BidsAdapter(ArrayList<String> categories, Context context, OnItemClickListener listener) {
this.items = categories;
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
System.out.println("beforeView");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bids_layout, parent, false);
System.out.println(view == null);
bidView = new BidView(view);
System.out.println("WORKING");
return bidView;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
bidView.textView.setText(String.valueOf(position));
bidView.bidderTextView.setText(items.get(position));
System.out.println(position);
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItem(items.get(rv.getChildPosition(childView)));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
#Override
public int getItemCount() {
return items.size();
}
}
static class BidView extends RecyclerView.ViewHolder {
public TextView textView;
public TextView bidderTextView;
public BidView(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.bid_text_View);
bidderTextView = (TextView) itemView.findViewById(R.id.bidder_user_name);
}
}
you replace this
static class BidsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements
RecyclerView.OnItemTouchListener {
instead
static class BidsAdapter extends RecyclerView.Adapter<BidsAdapter.BidView> implements
RecyclerView.OnItemTouchListener {

Categories

Resources