Hii I am trying to read data from firebase database and storage to Firebase recycler everything is working fine till I am scrolling the Recycler view down then app is crashing here is my code
MODEL CLASS
package com.example.ace.park;
public class model {
public String name,num,type,sno;
public model(String name, String num, String type, String sno) {
this.name = name;
this.num = num;
this.type = type;
this.sno = sno;
}
public model() {
}
}
Here is JAVA CLASS
package com.example.ace.park;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class dis extends AppCompatActivity {
NavigationView navigationView;
TextView textView;
Intent intent;
FirebaseRecyclerAdapter<model, displayAdapter> adapter;
FirebaseRecyclerOptions<model> options;
RecyclerView recyclerView;
DatabaseReference mDatabase,query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dis);
recyclerView = findViewById(R.id.myRecView);
mDatabase = FirebaseDatabase.getInstance().getReference().child("parkings");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
query = FirebaseDatabase.getInstance().getReference().child("parkings");
options = new FirebaseRecyclerOptions.Builder<model>()
.setQuery(query, model.class)
.build();
adapter = new FirebaseRecyclerAdapter<model, displayAdapter>(
options) {
#Override
public displayAdapter onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler, parent, false);
return new displayAdapter(v);
}
#Override
protected void onBindViewHolder(displayAdapter holder, final int position, final model current) {
holder.setName(current.name);
holder.setTotal(current.num);
holder.setType(current.type);
holder.setImage(getApplicationContext(),current.sno,current.sno);
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(dis.this, ""+position, Toast.LENGTH_SHORT).show();
}
});
}
};
//Populate Item into Adapter
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Here is Adapter
package com.example.ace.park;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.io.File;
import java.io.IOException;
public class displayAdapter extends RecyclerView.ViewHolder {
public View mview;
public displayAdapter(View itemView) {
super(itemView);
mview = itemView;
}
public void setName(String name){
TextView recName = mview.findViewById(R.id.recyclerName);
recName.setText(name);
}
public void setTotal(String title){
TextView t = mview.findViewById(R.id.recyclerTotal);
t.setText(title);
}
public void setType(String type){
TextView t = mview.findViewById(R.id.recyclerType);
t.setText(type);
}
public void setImage(Context ctx, String image,String user){
final ImageView iv = mview.findViewById(R.id.recyclerImg);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReference().child("Parkings"+"/"+image);
try {
final File localFile = File.createTempFile("images", "jpg");
storageReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
iv.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {
Toast.makeText(ctx, "Error in Adapter", Toast.LENGTH_SHORT).show();
}
}
}
This is recycler layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
app:cardCornerRadius="10dp"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerName"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textColor="#212020"
android:textSize="30sp"
android:text="#string/name_of_place"
/>
<ImageView
android:layout_width="300dp"
android:layout_marginTop="30dp"
android:layout_height="230dp"
android:scaleType="centerCrop"
android:paddingLeft="10dp"
android:layout_gravity="center"
android:paddingRight="10dp"
android:id="#+id/recyclerImg"
android:contentDescription="#string/img"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="#615f5f"
android:textSize="18sp"
android:id="#+id/recyclerTotal"
android:text="#string/tsp"
/>
<TextView
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:text="#string/type"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:id="#+id/recyclerType"
android:layout_height="25dp"
android:textSize="18sp"
android:layout_marginBottom="5dp"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
Logcat is giving his error
11-21 20:37:32.885 9681-9681/com.example.ace.park E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ace.park, PID: 9681
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.ace.park.model
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.5:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.5:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.5:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.5:212)
at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:29)
at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:15)
at com.firebase.ui.common.BaseCachingSnapshotParser.parseSnapshot(BaseCachingSnapshotParser.java:35)
at com.firebase.ui.common.BaseObservableSnapshotArray.get(BaseObservableSnapshotArray.java:52)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:106)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:122)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
this is image of database structure
Related
This is the code I have been working on for a while. The only issue is I cannot seem to be able to get the sum of values input into the editText fields that are dynamically added into the program and then place them into a pie chart. The data is to be transferred from the second activity to the third where the third activity will add up all resource amounts and display them into a pie chart.
SecondActivity.class
package com.example.a4mob;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.drawerlayout.widget.DrawerLayout;
import java.util.ArrayList;
import java.util.List;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
private LinearLayout linearLayout;
private Button add;
//for button add resource
List<String> ColourList = new ArrayList<>();
ArrayList<Results> resultList = new ArrayList<>();
private Button submit;
private Number uinput;
#Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.secondactivity);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
// Define ColorDrawable object and parse color
// using parseColor method
// with color hash code as its parameter
ColorDrawable colorDrawable
= new ColorDrawable(Color.parseColor("grey"));
// Set BackgroundDrawable
actionBar.setBackgroundDrawable(colorDrawable);
//Adds more objects
linearLayout = findViewById(R.id.layout_list);
add = findViewById(R.id.CreateNew);
add.setOnClickListener(this);
ColourList.add("grey");
ColourList.add("green");
ColourList.add("blue");
ColourList.add("yellow");
// Creating submit button click listener
submit = findViewById(R.id.Submit);
submit.setOnClickListener(this);
}
public void onClick(View view){
switch (view.getId()){
case R.id.CreateNew:
addView();
break;
case R.id.Submit:
if(isValid()){
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", resultList);
intent.putExtras(bundle);
startActivity(intent);
}
break;
}
}
private boolean isValid() {
resultList.clear();
boolean valid = true;
for(int i = 0; i < linearLayout.getChildCount(); i++){
View resultView = linearLayout.getChildAt(i);
EditText resultName = (EditText) resultView.findViewById(R.id.RName);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) resultView.findViewById(R.id.ColourOP);
Results results = new Results();
if(!resultName.getText().toString().equals("")){
results.setResName(resultName.getText().toString());
}else{
valid = false;
break;
}
if(!resultNumber.getText().toString().equals("")){
results.setResAmount(Integer.parseInt(resultNumber.getText().toString()));
}else{
valid = false;
break;
}
if(COP.getSelectedItemPosition()!=0){
}else{
valid = false;
break;
}
resultList.add(results);
}
if(resultList.size() == 0){
valid = false;
Toast.makeText(this, "Complete all fields first", Toast.LENGTH_SHORT).show();
} else if(!valid){
Toast.makeText(this, "Enter details correctly", Toast.LENGTH_SHORT).show();
}
return valid;
}
public void addAmount(){
for(int i = 0; i < linearLayout.getChildCount(); i++) {
View resultView = linearLayout.getChildAt(i);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
Results results = new Results();
}
}
private void sub(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please input inventory space:");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
uinput = input.getInputType();
changeAct();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private void changeAct(){
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
private void addView(){
View newResource = getLayoutInflater().inflate(R.layout.row_add_data, null, false);
ImageView imageClose = (ImageView)newResource.findViewById(R.id.Remove);
TextView RN = (TextView) newResource.findViewById(R.id.RName);
TextView RA = (TextView) newResource.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) newResource.findViewById(R.id.ColourOP);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ColourList);
COP.setAdapter(arrayAdapter);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(newResource);
}
});
linearLayout.addView(newResource);
}
private void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
super.onPointerCaptureChanged(hasCapture);
}
}
ThirdActivity.class
package com.example.a4mob;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ThirdActivity extends AppCompatActivity {
RecyclerView recycle_results;
ArrayList<Results> resultList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
recycle_results = findViewById(R.id.res_results);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recycle_results.setLayoutManager(linearLayoutManager);
resultList = (ArrayList<Results>) getIntent().getExtras().getSerializable("list");
recycle_results.setAdapter(new ResultsAdapter(resultList));
}
}
Results.class
package com.example.a4mob;
import java.io.Serializable;
public class Results implements Serializable {
public String resourceName;
public int resourceAmount;
public int totalAmount;
public Results(){
}
public int getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(int totalAmount) {
this.totalAmount = totalAmount;
}
public int getResAmount() {
return resourceAmount;
}
public void setResAmount(int resourceAmount) {
this.resourceAmount = resourceAmount;
}
public Results(String resourceName, int resourceAmount){
this.resourceName = resourceName;
this.resourceAmount = resourceAmount;
}
public String getResName() {
return resourceName;
}
public void setResName(String resourceName) {
this.resourceName = resourceName;
}
}
ResultsAdapter.class
package com.example.a4mob;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.ResultsView> {
ArrayList<Results> resultList = new ArrayList<>();
int total;
public ResultsAdapter(ArrayList<Results> resultList) {
this.resultList = resultList;
}
#NonNull
#Override
public ResultsView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_results,parent,false);
return new ResultsView(view);
}
#Override
public void onBindViewHolder(#NonNull ResultsView holder, int position) {
Results results = resultList.get(position);
holder.resourceName.setText(results.getResName());
holder.resourceAmount.setText(String.valueOf(results.getResAmount()));
}
#Override
public int getItemCount() {
return resultList.size();
}
public class ResultsView extends RecyclerView.ViewHolder{
TextView resourceName, resourceAmount, resourceTotal;
public ResultsView(#NonNull View itemView) {
super(itemView);
resourceName = (TextView) itemView.findViewById(R.id.resNa);
resourceAmount = (TextView) itemView.findViewById(R.id.resAm);
resourceTotal = (TextView) itemView.findViewById(R.id.resTot);
}
}
}
thirdactivity.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="match_parent"
tools:context=".ThirdActivity">
<LinearLayout
android:id="#+id/layoutThird"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/res_results"
android:layout_width="match_parent"
android:layout_height="match_parent"></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
row_results.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="#color/white"
android:layout_margin="5dp"
android:layout_marginBottom="20dp"
app:cardCornerRadius="10dp"
app:cardElevation="10dp">
<LinearLayout
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginBottom="0dp">
<TextView
android:id="#+id/resNa"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Name"
android:textSize="18sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resAm"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resTot"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
I want to create an activity to search for users by full name. I created everything I needed and it worked properly, except for one thing. When I press search button the result are not show in recyclerview. I need to go back and the the results are shown. I need to do these 2 steps to see the results.
Yes the search bar and view holder are overlap, I will try to fixed later. Do you know how to make it so that once searched the results are displayed immediately without having to go back
This is my layout for view holder
<?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="75dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:id="#+id/parent_layout"
android:background="#drawable/recycler_view_border">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imageProfile"
android:layout_width="60dp"
android:layout_height="60dp"
android:tint="#808080"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
app:civ_border_color="#color/dark_blue"
app:civ_border_width="2dp"
app:srcCompat="#drawable/defaultimage"/>
<TextView
android:id="#+id/userFullName"
android:layout_toEndOf="#+id/imageProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="#string/fullname"
android:textSize="16sp"
android:textColor="#color/black"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonAdd"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="340dp"
android:background="#drawable/btn_background"
app:cornerRadius="8dp"
android:drawableTop="#drawable/ic_action_add" />
</RelativeLayout>
This is my layout for activity
<?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="match_parent"
tools:context=".SendFriendRequests">
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="13dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/searchUsername"
android:layout_width="318dp"
android:layout_height="45dp"
android:layout_marginTop="20dp"
android:background="#drawable/edt_background"
android:hint="#string/searchFriends"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="text"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="333dp"
android:layout_marginTop="-47dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_background"
android:drawableTop="#drawable/ic_action_search"
app:cornerRadius="8dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="580dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"
app:layout_constraintVertical_bias="0.99"
tools:layout_editor_absoluteX="-16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my adapter
package com.example.chatappjava;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class SendFriendRequestAdapter extends RecyclerView.Adapter<SendFriendRequestAdapter.ViewHolder> {
private static final String TAG = "ContactsAdapter";
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Context context;
public SendFriendRequestAdapter(ArrayList<UserData> arrayListUserData, Context context) {
this.arrayListUserData = arrayListUserData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_send_friend_request_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, #SuppressLint("RecyclerView") int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(context)
.asBitmap()
.load(arrayListUserData.get(position).image)
.into(holder.userProfileImage);
holder.userFullName.setText(arrayListUserData.get(position).name);
holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
PreparedStatement st1 = conn.prepareStatement(
" insert into FRIEND_REQUESTS values (?,?,?)");
st1.setString(1, arrayListUserData.get(position).friendId);
st1.setString(2, arrayListUserData.get(position).userId);
st1.setInt(3, 0);
st1.execute();
showToast("Friend request is sended");
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("IdAccount", arrayListUserData.get(position).userId);
context.startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), specificchat.class);
intent.putExtra("userId", arrayListUserData.get(position).userId);
intent.putExtra("friendId", arrayListUserData.get(position).friendId);
intent.putExtra("friendName", arrayListUserData.get(position).name);
intent.putExtra("friendImage", arrayListUserData.get(position).image);
context.startActivity(intent);
}
});
}
private void showToast(String message) {
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return arrayListUserData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircularImageView userProfileImage;
TextView userFullName;
RelativeLayout parentLayout;
Button buttonAdd;
public ViewHolder(View itemView) {
super(itemView);
userProfileImage = itemView.findViewById(R.id.imageProfile);
userFullName = itemView.findViewById(R.id.userFullName);
parentLayout = itemView.findViewById(R.id.parent_layout);
buttonAdd = itemView.findViewById(R.id.buttonAdd);
}
}
}
And this is my java class which use the adapter
package com.example.chatappjava;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SendFriendRequests extends AppCompatActivity {
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Button searchButton;
private EditText searchUsername;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userId = intent.getStringExtra("IdAccount");
setContentView(R.layout.activity_send_friend_request);
searchButton = findViewById(R.id.buttonSearch);
searchUsername = findViewById(R.id.searchUsername);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
Statement statement = conn.createStatement();
ResultSet resultat = statement.executeQuery("select ID, FULLNAME, IMAGE from USERS where ID not in (select FRIEND_ID from FRIENDSLIST where USER_ID = " + userId + ") and FULLNAME like '%" + searchUsername.getText().toString() + "%' and ID not in (select RECEIVER_ID from FRIEND_REQUESTS where SENDER_ID = " + userId + ")");
while (resultat.next()) {
arrayListUserData.add(new UserData(resultat.getString("FULLNAME"), resultat.getString("IMAGE"), resultat.getString("ID"), userId));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
initRecycleView();
}
});
}
private void initRecycleView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SendFriendRequestAdapter adapter = new SendFriendRequestAdapter(arrayListUserData, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I think it's the RecyclerView in your XML that needs to be adjusted at android:layout_height = "0dp"
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"/>
Here's the data in my database:
Here's the code of my project. I found no error. It is not displaying the contents in it, even it is showing a blank page.
Adapter
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import java.util.ArrayList;
public class MylistAdapter extends RecyclerView.Adapter<MylistAdapter.MylistViewHolder> {
private ArrayList<RequestUser> users;
class MylistViewHolder extends RecyclerView.ViewHolder{
private TextView dispname1;
private TextView dispphn1;
private TextView dispcity1;
private TextView dispaddr1;
private TextView dispnumber1;
private MylistViewHolder(#NonNull View itemView) {
super(itemView);
dispaddr1=itemView.findViewById(R.id.dispaddr);
dispcity1=itemView.findViewById(R.id.dispcity);
dispname1=itemView.findViewById(R.id.dispname);
dispphn1=itemView.findViewById(R.id.disphn);
dispnumber1=itemView.findViewById(R.id.dispnumber);
}
}
public MylistAdapter(ArrayList<RequestUser> usrs) {
this.users= usrs;
}
#Override
public MylistViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
MylistViewHolder mlvh=new MylistViewHolder(v);
return mlvh;
}
#Override
public void onBindViewHolder(#NonNull MylistViewHolder holder, int position) {
RequestUser curuser=users.get(position);
holder.dispphn1.setText(curuser.getRphn1());
holder.dispname1.setText(curuser.getRname1());
holder.dispcity1.setText(curuser.getRcity1());
holder.dispaddr1.setText(curuser.getRaddr1());
holder.dispnumber1.setText(curuser.getRnumber1());
}
#Override
public int getItemCount() {
return users.size();
}
}
Main Class
Which contains the main functionality
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Objects;
public class Transport extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
DatabaseReference dbreferance;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
private ArrayList<RequestUser> usrs=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transport);
firebaseAuth=FirebaseAuth.getInstance();
firebaseDatabase=FirebaseDatabase.getInstance();
dbreferance= FirebaseDatabase.getInstance().getReference().child("Donate");
dbreferance.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usrs.clear();
for(DataSnapshot child:dataSnapshot.getChildren())
{
//String id=child.getKey();
RequestUser usr=child.getValue(RequestUser.class);
usrs.add(usr);
//RequestUser usr= (RequestUser) child.getValue();
//usrs.add(usr);
//System.out.println(usr.rname1);
Toast.makeText(Transport.this,usr.getRphn1(),Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(this);
adapter=new MylistAdapter(usrs);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
XML Layouts
for the Recycler view and the card views
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/dispname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Line1"
android:textColor="#android:color/black"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="#+id/dispcity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/dispname"
android:textSize="25sp"
android:layout_marginStart="8dp"
android:text="Line2"
android:layout_marginLeft="8dp" />
<TextView
android:id="#+id/dispaddr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/dispcity"
android:textSize="15sp"
android:text="Line3"
android:layout_marginLeft="16dp"/>
<TextView
android:id="#+id/disphn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/dispaddr"
android:textSize="15sp"
android:text="Line4"
android:layout_marginLeft="24dp"/>
<TextView
android:id="#+id/dispnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/dispaddr"
android:textSize="15sp"
android:text="Line5"
android:layout_marginLeft="24dp"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Another Layout
ie for card view
<?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"
tools:context=".Transport">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="1dp"
tools:ignore="MissingConstraints" />
</RelativeLayout>
When we add listener Android create a separate thread for that and that thread run separately. So in your case we you are adding the listener android is creating the separate thread for that and then it immediately set the adapter for the recyclerView.
Create the adapter before adding the listener and set the adapter with recyclerView in the onDataChanged( ) method after the for loop.
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usrs.clear();
for(DataSnapshot child:dataSnapshot.getChildren())
{
//String id=child.getKey();
RequestUser usr=child.getValue(RequestUser.class);
usrs.add(usr);
//RequestUser usr= (RequestUser) child.getValue();
//usrs.add(usr);
//System.out.println(usr.rname1);
Toast.makeText(Transport.this,usr.getRphn1(),Toast.LENGTH_SHORT).show();
}
recyclerView.setAdapter(adapter);
}
So, I tried putting a recyclerView in a "popup" dialog using a firebaseRecyclerAdapter.
My problem is, that I know for sure the adapter gets filled because I was using the Logcat to tell me when it adds another "user" to the adapter, but it wont show anything in the recyclerview in the dialog.
I'm having this problem for a couple of days and couldn't find an answer yet, glad if you could help me :)
I'm using a main screen which changes fragments, and from a certain fragment I'm calling this specific dialog.
These are my files:
UserViewHolder - the class which holds the "sets" for the cardview:
public static class UserViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UserViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setName(String name)
{
TextView teacherName=(TextView) mView.findViewById(R.id.txtNameTea);
teacherName.setText(name);
}
public void setEmail(String email)
{
TextView txtEmailTea=(TextView) mView.findViewById(R.id.txtEmailTea);
txtEmailTea.setText(email);
}
public void setImage(final Context ctx, Uri imageUri, User cUser)
{
final ImageView imgProfileTea=(ImageView) mView.findViewById(R.id.imgProfileTea);
Picasso.with(ctx).load(cUser.getImageUri()).into(imgProfileTea);
if(imgProfileTea.getDrawable()==null) {
StorageReference load = FirebaseStorage.getInstance().getReference().child("usersProfilePic/" + cUser.getImageName());
load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri.toString()).into(imgProfileTea);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG);
}
});
}
}
}
Schedules - the fragment which calls the dialog from its toolbar:
package com.example.android.aln4;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.example.android.aln4.LoginActivity.myUser;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static java.lang.System.in;
import static com.example.android.aln4.navDrawerMain.studentsQuery;
public class Schedules extends Fragment {
private Toolbar ScheduleToolbar;
private Button addEvent;
//private TextView txt;
private RecyclerView mRecyclerViewStudentEvent;
private CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM-yyyy", Locale.getDefault());
private String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addEvent:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
mRecyclerViewStudentEvent = (RecyclerView) mView.findViewById(R.id.mRecyclerViewStudentEvent);
mRecyclerViewStudentEvent.setHasFixedSize(true);
mRecyclerViewStudentEvent.setLayoutManager(new LinearLayoutManager(getContext()));
setStudentsList();
mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
final EditText edtEventTitle = (EditText) mView.findViewById(R.id.edtEventTitle);
final TextView txtEventStartTime = (TextView) mView.findViewById(R.id.txtEventStartTime);
final TextView txtEventEndTime = (TextView) mView.findViewById(R.id.txtEventEndTime);
final EditText edtEventLocation = (EditText) mView.findViewById(R.id.edtEventLocation);
Button btnOfferEvent = (Button) mView.findViewById(R.id.btnOfferEvent);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
btnOfferEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int startHour = Integer.parseInt(txtEventStartTime.getText().toString().substring(0, 2));
int startMinute = Integer.parseInt(txtEventStartTime.getText().toString().substring(3, 5));
startTime.set(Calendar.HOUR_OF_DAY, startHour);
startTime.set(Calendar.MINUTE, startMinute);
int endHour = Integer.parseInt(txtEventEndTime.getText().toString().substring(0, 2));
int endMinute = Integer.parseInt(txtEventEndTime.getText().toString().substring(3, 5));
endTime.set(Calendar.HOUR_OF_DAY, endHour);
endTime.set(Calendar.MINUTE, endMinute);
String mId =/*dataSelected+*/ String.valueOf(startHour) + String.valueOf(startMinute);//+selectedUserID
EventCreation newEvent = new EventCreation(mId, startTime, endTime, edtEventTitle.getText().toString(), edtEventLocation.getText().toString(), R.color.colorPrimary);
dialog.dismiss();
}
});
dialog.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
ScheduleToolbar = (Toolbar) getView().findViewById(R.id.schedule_toolbar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
((AppCompatActivity) getActivity()).setSupportActionBar(ScheduleToolbar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
int year = cal.get(Calendar.YEAR);
getActivity().setTitle(month + "-" + year);
compactCalendar = (CompactCalendarView) getView().findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
long millis = System.currentTimeMillis() % 1000;
Event ev1 = new Event(Color.RED, millis, "First try");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
//put events into scroll view adapter
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getActivity().setTitle(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedules, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
private void setStudentsList() {
studentsQuery=mDatabaseReference.orderByChild("teacherNum").equalTo(myUser.getTeacherNum());
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,studentsQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName() + " " + model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()), model);
}
};
mRecyclerViewStudentEvent.setAdapter(firebaseRecyclerAdapter);
}
}
The dialog xml 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">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/title"/>
<EditText
android:id="#+id/edtEventTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="כותרת"
android:layout_marginRight="50dp"/>
<android.support.v7.widget.RecyclerView
android:layout_marginTop="50dp"
android:id="#+id/mRecyclerViewStudentEvent"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/clock"/>
<TextView
android:layout_width="wrap_content"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="שעת התחלה"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="50dp"
android:layout_marginTop="5dp"
android:text="21:00" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="25dp"
android:layout_marginRight="50dp"
android:background="#color/darkgray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:text="שעת סיום"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventEndTime"
android:layout_width="match_parent"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="30dp"
android:text="21:45" />
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/location"/>
<EditText
android:id="#+id/edtEventLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="מיקום תחילת השיעור"
android:layout_marginRight="50dp"/>
</RelativeLayout>
<Button
android:id="#+id/btnOfferEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="הצע שיעור"/>
</LinearLayout>
One more thing is that I know is that I'm already able to bring up users into the recyclerView in other fragments.. Here's the code in another fragment:
package com.example.android.aln4;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static com.example.android.aln4.navDrawerMain.teachersQuery;
public class TeachersList extends Fragment {
private RecyclerView mRecyclerViewTeacher;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("מורים");
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
mRecyclerViewTeacher=(RecyclerView) getView().findViewById(R.id.mRecyclerViewTeacher);
mRecyclerViewTeacher.setHasFixedSize(true);
mRecyclerViewTeacher.setLayoutManager(new LinearLayoutManager(getContext()));
setTeachersList();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.teachers_list_frag,container,false);
}
private void setTeachersList() {
teachersQuery=mDatabaseReference.orderByChild("type").equalTo("Teacher");
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,teachersQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName()+" "+model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()),model);
}
};
mRecyclerViewTeacher.setAdapter(firebaseRecyclerAdapter);
}
}
and its xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecyclerViewTeacher"
android:layout_marginTop="57dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
It's one of my first questions here so I apologize if I missed something :)
Any help would be appriciated.
Solved. All I did was regenerating the SHA1 in the firebase settings, and removing the setHasFixedSize line from Schedules activity and it worked just fine.
i work about a vtc app and I need to display on the main screen the orders of the client.
I chose the way of customing the list view with an adapter but when i launch the app nothing on the screen except the title of the page.
i divided the adapter code and the fragment code (yeah i work in a fragment) and i want to have your opinion about my code.
Here the Fragment :
package com.cmn.cmnvtc;
import android.Manifest;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainPageFragment1 extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout containerView;
private TextView NoCommand;
private UserLocalStore userLocalStore;
private List<Courses> coursesList;
private ListView lvCourses;
private CoursesAdapter coursesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main1, container, false);
userLocalStore = new UserLocalStore(getActivity());
NoCommand = (TextView) v.findViewById(R.id.NoCommand);
lvCourses = (ListView) v.findViewById(R.id.lvCourses);
coursesList = new ArrayList<>();
final Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
String origin = obj.getString("origin");
String destination = obj.getString("destination");
String date_depart = obj.getString("date_depart");
String heure_depart = obj.getString("heure_depart");
int nb_passagers = Integer.parseInt(obj.getString("nb_passagers"));
float prix = Float.parseFloat(obj.getString("prix"));
String mode_paiement = obj.getString("paiement");
String etat_paiement = obj.getString("course_payee");
Courses course = new Courses(origin, destination, date_depart, heure_depart, nb_passagers, prix
, mode_paiement, etat_paiement);
coursesList.add(course);
}
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
User currentUser = userLocalStore.getLoggedInUser();
final GetAllCourseRequest getAllCourse = new GetAllCourseRequest(currentUser.user_id,responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(getAllCourse);
coursesAdapter = new CoursesAdapter(getActivity(), coursesList);
lvCourses.setAdapter(coursesAdapter);
lvCourses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "CLicked", Toast.LENGTH_SHORT).show();
}
});
if (googleServicesAvailable()) {
containerView = (LinearLayout) v.findViewById(R.id.containerView);
askForPermission();
}
return v;
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvaibable = api.isGooglePlayServicesAvailable(getActivity());
if (isAvaibable == ConnectionResult.SUCCESS) {
return true;
} else if (api.isUserResolvableError(isAvaibable)) {
Dialog dialog = api.getErrorDialog(getActivity(), isAvaibable, 0);
dialog.show();
} else {
Toast.makeText(getActivity(), "Can't connect to play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private void explain() {
Snackbar.make(containerView, "Cette permission est nécessaire pour vous géolocalisez", Snackbar.LENGTH_LONG).setAction("Activer", new View.OnClickListener() {
#Override
public void onClick(View view) {
askForPermission();
}
}).show();
}
private void askForPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 2) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[0]) == false) {
displayOptions();
} else {
explain();
}
}
if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[1]) == false) {
displayOptions();
} else {
explain();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void displayOptions() {
Snackbar.make(containerView, "Vous avez désactivé la permission", Snackbar.LENGTH_LONG).setAction("Paramètres", new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
final Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}).show();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
My custom adapter :
package com.cmn.cmnvtc;
import android.content.Context;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Wild Shadow on 18/06/2017.
*/
public class CoursesAdapter extends BaseAdapter {
private List<Courses> coursesList;
private Context ctx;
public CoursesAdapter(Context context, List<Courses> coursesList) {
this.ctx = context;
this.coursesList = coursesList;
}
#Override
public int getCount() {
return coursesList.size();
}
#Override
public Object getItem(int position) {
return coursesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(ctx, R.layout.row_courses, null);
TextView adrOrigin = (TextView) v.findViewById(R.id.adrOriginList);
TextView adrDestinaiton = (TextView)
v.findViewById(R.id.adrDestList);
TextView dateDepart = (TextView) v.findViewById(R.id.dateDepList);
TextView heureDepart = (TextView)
v.findViewById(R.id.heureDepList);
ImageButton viewDetails = (ImageButton)
v.findViewById(R.id.viewDetailsCourse);
adrOrigin.setText(coursesList.get(position).getOrigin());
adrDestinaiton.setText(coursesList.get(position).getDestination());
dateDepart.setText(coursesList.get(position).getDate_depart());
heureDepart.setText(coursesList.get(position).getHeure_depart());
return v;
}
}
the model layout :
<?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"
android:padding="6dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_depart_courselist"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/adrOriginList"
android:textSize="17dp"
android:textColor="#000"
android:paddingTop="3dp"
android:text=" : Adresse de départ"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_destination_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/adrDestList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Adresse d'arrivée"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_date_depart_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dateDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : date de départ"
android:layout_marginBottom="3dp"
android:layout_marginRight="20dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_heure_dep_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heureDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Heure"
android:layout_marginBottom="3dp"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_details_courselist"
android:layout_marginLeft="65dp"
android:id="#+id/viewDetailsCourse"
android:paddingTop="5dp"
android:background="?android:selectableItemBackground"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and the listview :
<ScrollView 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="10dp"
android:theme="#style/AppTheme"
tools:context="com.cmn.cmnvtc.MainPageFragment1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="#+id/TitleListCommand"
android:textSize="25dp"
android:layout_marginBottom="15dp"
android:textColor="#727574"
android:text="Liste de mes courses "/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/TitleListCommand"
android:layout_alignParentStart="true"
android:id="#+id/lvCourses"></ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:textColor="#969696"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:textSize="15dp"
android:textAlignment="center"
android:id="#+id/NoCommand"
android:text=""
android:enabled="false"/>
</RelativeLayout>
</ScrollView>
I hope you will help me to find the error and if you want more, try to explain me how i can optimize my code. TY
You should call notifyDataSetChanged() in the ResponseListener after filling your list.
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
...
coursesList.add(course);
}
//notify adapter about change in data
coursesAdapter.notifyDataSetChanged();
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};