Retrieving data according to key - Firebase - android

So I have a Firebase database as follows:
I have a recycler view list with job names. When the person clicks on an item, it has to expand to show more information about it. In order to do that I believe I have to retrieve the data based on the main children keys like Job1, Job2 etc. How would I do this? I have tried to look up on similar questions but I can't help feeling a bit lost since I'm only a beginner. I'd appreciate it if someone answered this with simple explanations to help me learn.
This is my main Home class:
package com.example.oddsynew;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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;
public class Home extends AppCompatActivity {
DatabaseReference myRef;
RecyclerView newJobList;
ArrayList<Job> list;
HomeAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
newJobList = (RecyclerView) findViewById(R.id.newJobs);
newJobList.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<Job>();
adapter = new HomeAdapter(Home.this, list);
newJobList.setAdapter(adapter);
myRef = FirebaseDatabase.getInstance().getReference().child("Jobs");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
String jobkey = ds.getKey();
Job j = ds.getValue(Job.class);
list.add(j);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Home.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
Followed by my adapter class:
package com.example.oddsynew;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
Context context;
ArrayList<Job> jobs;
public HomeAdapter(Context c, ArrayList<Job> j){
context = c;
jobs = j;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.job_row, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.recruiterName.setText(jobs.get(position).getRecruiter_name());
holder.jobName.setText(jobs.get(position).getJob_name());
holder.jobLocation.setText(jobs.get(position).getLocation());
holder.jobCharge.setText(jobs.get(position).getJob_charge());
Picasso.get().load(jobs.get(position).getProf_pic()).into(holder.profPic);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String recruiter_id; //I'm not sure what to do here.
}
});
}
#Override
public int getItemCount() {
return jobs.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView recruiterName, jobName, jobLocation, jobCharge;
ImageView profPic;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
recruiterName = itemView.findViewById(R.id.recruiterName);
jobName = itemView.findViewById(R.id.jobName);
jobLocation = itemView.findViewById(R.id.jobLocation);
jobCharge = itemView.findViewById(R.id.jobCharge);
profPic = itemView.findViewById(R.id.prof_pic);
}
}
}
And here is my model:
package com.example.oddsynew;
public class Job {
private String job_name;
private String recruiter_name;
private String location;
private String job_charge;
private String prof_pic;
public Job() {
}
public Job(String job_name, String recruiter_name, String location, String job_charge, String prof_pic) {
this.job_name = job_name;
this.recruiter_name = recruiter_name;
this.location = location;
this.job_charge = job_charge;
this.prof_pic = prof_pic;
}
public Job(String prof_pic) {
this.prof_pic = prof_pic;
}
public String getJob_name() {
return job_name;
}
public void setJob_name(String job_name) {
this.job_name = job_name;
}
public String getRecruiter_name() {
return recruiter_name;
}
public void setRecruiter_name(String recruiter_name) {
this.recruiter_name = recruiter_name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getJob_charge() {
return job_charge;
}
public void setJob_charge(String job_charge) {
this.job_charge = job_charge;
}
public String getProf_pic() {
return prof_pic;
}
public void setProf_pic(String prof_pic) {
this.prof_pic = prof_pic;
}
}
My Recycler View UI
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="14dp"
android:layout_marginRight="14dp"
android:elevation="90dp"
android:orientation="vertical"
app:cardCornerRadius="4dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#fff"
android:orientation="vertical">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginStart="12dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3" />
<TextView
android:id="#+id/recruiterName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="16dp"
android:fontFamily="#font/roboto"
android:textColor="#000"
android:textSize="14sp"
android:textStyle="normal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/prof_pic"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/jobName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:fontFamily="#font/roboto_bold"
android:textColor="#000"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/prof_pic"
app:layout_constraintTop_toBottomOf="#+id/recruiterName" />
<TextView
android:id="#+id/jobLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="24dp"
android:fontFamily="#font/roboto_light"
android:textColor="#000"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/prof_pic"
app:layout_constraintTop_toBottomOf="#+id/jobName"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/jobCharge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="16dp"
android:fontFamily="#font/roboto_light"
android:textColor="#000"
android:textSize="12sp"
app:layout_constraintBaseline_toBaselineOf="#+id/jobLocation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/jobLocation" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
EDIT: This is my recycler list view. I have retrived data from firebase and displayed it on the items. The first list item is info from Job1. When I click on the first item, it should go to another page lets call it "jobInfo" to display more information about that particular job. What I'm struggling with is how do I make sure information only about job1 is displayed when I click the first item. Sorry if I wasn't clear before.

In home activity:
myRef = FirebaseDatabase.getInstance().getReference().child("Jobs");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
String jobkey = ds.getKey();
Job j = ds.getValue(Job.class);
list.add(j);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Home.this, "Error", Toast.LENGTH_SHORT).show();
}
});
In Job model class implement Serializable
public class Job implements Serializable
In adapter click listener
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, jobInfo.class);
intent.putExtra("yourKey",jobs.get(position));
startActivity(intent);
}
});
In jobInfo activity
Job job = (Job) getIntent().getSerializableExtra("yourKey");
in job you will get all values

I was able to make it work with this code in my job info class:
package com.example.oddsynew;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.squareup.picasso.Picasso;
public class JobInfo extends AppCompatActivity {
TextView jobName, jobCharge, jobLocation;
ImageView profPic;
String jobname, jobloc, jobcharge, profpic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_info);
jobName = (TextView) findViewById(R.id.jobName_info);
jobCharge = (TextView) findViewById(R.id.jobCharge_info);
jobLocation = (TextView) findViewById(R.id.jobLocation_info);
profPic = (ImageView) findViewById(R.id.prof_pic_info);
jobname = getIntent().getStringExtra("jobName");
jobloc = getIntent().getStringExtra("jobLocation");
jobcharge = getIntent().getStringExtra("jobCharge");
profpic = getIntent().getStringExtra("profPic");
jobName.setText(jobname);
jobCharge.setText(jobcharge);
jobLocation.setText(jobloc);
Picasso.get().load(profpic).into(profPic);
}
}
And adding this under setOnClickListener in my adapter class:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, JobInfo.class);
intent.putExtra("recruiterName",jobs.get(position).getRecruiter_name());
intent.putExtra("jobName",jobs.get(position).getJob_name());
intent.putExtra("jobCharge",jobs.get(position).getJob_charge());
intent.putExtra("jobLocation",jobs.get(position).getLocation());
intent.putExtra("profPic",jobs.get(position).getProf_pic());
context.startActivity(intent);
}
});
}

Related

Getting a fatal exception while working on firebase database and searchview

I'm trying to use a Searchview with Recylerview and firebase database, i've been following some tutorial and i've followed the video correctly so I don't know why i'm getting an error,i have three classn one is an adapater and a helper and the main one, the error i get is:
2021-05-12 03:16:12.931 31658-31658/com.example.search E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.search, PID: 31658
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.search.Deal
in the following line:
list.add(ds.getValue(Deal.class));
this is my main activity:
package com.example.search;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Deal> list;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ref = FirebaseDatabase.getInstance().getReference().child("medicines");
recyclerView = findViewById(R.id.rv);
searchView = findViewById(R.id.searchview);
}
#Override
protected void onStart() {
super.onStart();
if(ref != null){
ref.addValueEventListener(new ValueEventListener() {
#NonNull
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
list = new ArrayList<>();
for(DataSnapshot ds : snapshot.getChildren()){
list.add(ds.getValue(Deal.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if (searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str) {
if (!str.equals("")){
ArrayList<Deal>myList = new ArrayList<>();
for (Deal object : list){
if(object.getDisease().toLowerCase().contains(str.toLowerCase())){
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(myList);
recyclerView.setAdapter(adapterClass);
}
}
}
and this is my "helper" class which i called deal:
package com.example.search;
public class Deal {
private String disease, medication;
public Deal() {
}
public Deal(String disease, String medication) {
this.disease = disease;
this.medication = medication;
}
public String getDisease() {
return disease;
}
public void setDisease(String disease) {
this.disease = disease;
}
public String getMedication() {
return medication;
}
public void setMedication(String medication) {
this.medication = medication;
}
}
this is my adapater class:
package com.example.search;
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 java.util.ArrayList;
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
ArrayList<Deal> list;
public AdapterClass(ArrayList<Deal> list){
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_holder, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.disease.setText(list.get(position).getDisease());
holder.medicine.setText(list.get(position).getMedication());
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView disease, medicine;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
disease = itemView.findViewById(R.id.disease);
medicine = itemView.findViewById(R.id.medication);
}
}
}
and this is my main activity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<androidx.appcompat.widget.SearchView
android:id="#+id/searchview"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:padding="10dp"
android:layout_margin="5dp"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:autofillHints="Search here"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
</LinearLayout>
and my card view layout
<?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"
android:layout_margin="5dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/disease"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:padding="10dp"
android:text="disease_name" />
<TextView
android:id="#+id/medication"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="solution"
android:padding="10dp"
/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000"
/>
</androidx.cardview.widget.CardView>
that's all there is to the whole app so i dont get why the app keeps crashing, this is what my firebase database looks like
{
"medicines" : {
"disease" : "maleria",
"medication" : "aspirin"
}
}
I was getting different exceptions before and I changed the rules in database and debugged the app and now I'm getting this error been stuck on it for two hours, Honestly no clue, I've already tried checking if I wrote things wrong and if the names I added in my helper(deal)class match with the ones in firebase etc., and they do so I don't know
Since your Deal class defines properties disease and mediation, there seems to be only one Deal object under medicines.
So with your current data, you shouldn't be using a loop over getChildren in the onDataChange, and simple do:
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
list = new ArrayList<>();
list.add(snapshot.getValue(Deal.class));
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}

image (only) is not appears in RecyclerView stored in FireBase Storage , while other items is appears

I am unable to display the image (only) in RecyclerView stored in Firebase Storage, while I'm displaying the other text data in the recyclerView.
I browse through a lot of questions but i didn't find the answer for me .
hint: all roles for Realtime Database , Firebase Storage is set either to [true or test mode]
hint : below is the link for out put image :
https://i.stack.imgur.com/dagbA.jpg
data model
import com.google.firebase.database.Exclude;
public class House {
#Exclude
private String key;
//owner name
private String name ;
//location
private String Location;
//image
private String imageUrl;
/*all start with [RealState] (realTimeDatabase/storage)*/
/*
* [RealStateData] - database
* [RealStatePictures] - storage
* */
public House() {
//required
}
public House(String name, String location, String imageUrl) {
if (name.trim().equals("") || name.isEmpty()){
name = "realState company";
}
this.name = name;
Location = location;
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Exclude
public String getKey() {
return key;
}
#Exclude
public void setKey(String key) {
this.key = key;
}
}
Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import com.techmarinar.royalhomes.data.House;
import java.util.List;
public class HouseAdapter extends RecyclerView.Adapter<HouseAdapter.HouseHolder> {
private static final String TAG = "HouseAdapter";
private Context mContext;
private List<House> houseList;
public HouseAdapter(Context mContext, List<House> houseList) {
this.mContext = mContext;
this.houseList = houseList;
}
public void setUploads(List<House> uploads) {
this.houseList = uploads;
this.notifyDataSetChanged();
}
#NonNull
#Override
public HouseHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(mContext)
.inflate(R.layout.list_item,parent,false);
return new HouseHolder(v);
}
#Override
public void onBindViewHolder(#NonNull HouseHolder holder, int position) {
//house object
House house = houseList.get(position);
holder.name.setText(house.getName());
holder.location.setText(house.getLocation());
// holder.image.setImageURI(Uri .parse(house.getImageUrl());
String imageUrl = house.getImageUrl();
Glide.with(mContext)
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.centerCrop()
.into(holder.image);
}
#Override
public int getItemCount() {
return houseList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class HouseHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView name;
private TextView location ;
public HouseHolder(#NonNull View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.xHouseImage);
name = (TextView) itemView.findViewById(R.id.xHouseName);
location = (TextView) itemView.findViewById(R.id.xHouseLocation);
}
}
}
MainActicity -- recyclerclass
package com.techmarinar.royalhomes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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 com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.techmarinar.royalhomes.data.House;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
//widget
private RecyclerView mRecycler;
private ProgressBar mProgress;
//firebase Element
private StorageReference storageReference;
private DatabaseReference databaseReference;
//Adapters var
private List<House> houseList;
private HouseAdapter mAdapter;
private ValueEventListener getFirebaseData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set Widget
setupUIWidget();
//init firebase
initiateFireBaseElement();
//set recyclerView
setupRecyclerView();
//get data from fire(storage/fireDataBase);
getHousesDataFromFireBase();
//setup Item Touch Helper
setupItemTouchHelper(mRecycler , mAdapter);
}
private void setupUIWidget() {
setTitle("home");
//widget
mProgress = (ProgressBar) findViewById(R.id.progress_circular);
mRecycler = (RecyclerView) findViewById(R.id.recycler);
FloatingActionButton mActionButton = (FloatingActionButton) findViewById(R.id.floatingBtn);
//ActionButton
mActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this, "wow", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this , EditHouse.class));
}
});
}
private void initiateFireBaseElement() {
//fireBase reference
databaseReference = FirebaseDatabase.getInstance().getReference("RealStateData");
storageReference= FirebaseStorage.getInstance().getReference("RealStatePictures") ;
}
private void setupRecyclerView() {
Log.d(TAG, "setupRecyclerView: ");
houseList = new ArrayList<>();
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mRecycler.setHasFixedSize(true);
//mRecycler.setHasStableIds(true);
//init adapter
mAdapter = new HouseAdapter(MainActivity.this,houseList);
//set adapter to the recyclerView
mRecycler.setAdapter(mAdapter);
}
private void getHousesDataFromFireBase() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
houseList.clear();
for (DataSnapshot data : snapshot.getChildren()) {
//init house object
House houseValues = data.getValue(House.class);
// houseValues.setKey(data.getKey());
//fill the list
houseList.add(houseValues);
}
//notify the adapter
mAdapter.setUploads(houseList);
//mAdapter.notifyDataSetChanged();
//hide the progressBar
mProgress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: " + error.getMessage());
Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
//hide progressbar
mProgress.setVisibility(View.INVISIBLE);
}
});
}
private void setupItemTouchHelper(RecyclerView mRecycler, HouseAdapter mAdapter) {
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
}).attachToRecyclerView(mRecycler);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu
MenuItem addNewHouse , deleteHouse , updateHouse;
addNewHouse= menu.add(0,1,1,"add house");
addNewHouse.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
addNewHouse.setIcon(R.drawable.ic_baseline_supervised_user_circle_24);
updateHouse= menu.add(0,2,2,"update house");
deleteHouse= menu.add(0,3,3,"delete house");
addNewHouse.setOnMenuItemClickListener(this);
updateHouse.setOnMenuItemClickListener(this);
deleteHouse.setOnMenuItemClickListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case 1:
Toast.makeText(this, "new house", Toast.LENGTH_SHORT).show();
return true;
case 2:
Toast.makeText(this, "update house data", Toast.LENGTH_SHORT).show();
return true;
case 3:
Toast.makeText(this, "delete house data", Toast.LENGTH_SHORT).show();
return true;
default:return false;
}
}
}
here is xml files
List item:
<?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"
android:layout_margin="2dp"
app:cardBackgroundColor="#color/purple_200"
app:cardElevation="12dp"
app:cardCornerRadius="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp">
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#color/purple_200"/>
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<ImageView
android:id="#+id/xHouseImage"
android:layout_width="match_parent"
android:layout_height="220dp"
android:adjustViewBounds="true" />
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<TextView
android:id="#+id/xHouseLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house Location"
android:layout_margin="4dp"
android:layout_marginStart="6dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="33sp"/>
<TextView
android:id="#+id/xHouseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house owner name"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/black"
android:textSize="16sp"
android:gravity="top|center_vertical" />
</LinearLayout>
</androidx.cardview.widget.CardView>
recycler
<?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=".MainActivity"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_goneMarginBottom="8dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.029" />
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.446"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.406" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_home_work_24"
android:backgroundTint="#color/white"
android:foregroundGravity="bottom|right"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try this applyDefaultRequestOptions Method for Center crop of the image
Glide.with(mContext)
.applyDefaultRequestOptions(RequestOptions().centerCrop())
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.into(target!!)
the problem was in Manifest.xml security issuess.
solution :
adding
android:usesCleartextTraffic="true"
to the application section

How to make a specific item respond to click in recyclerView

i have a news app which i want when the news item (cardview) is clicked on, it should open another activity. unfortunately, nothing happens when the news item in the card view is clicked on, only when the background (recycler layout) is clicked on then the activity comes up.
i want when the news item on the cardview is clicked on, an activity should open and not when the background is clicked.
newsAdapter.java
package wami.ikechukwu.kanu;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class newsAdapter extends RecyclerView.Adapter<newsAdapter.viewHolder> {
private ArrayList<dataModel> mDataModel;
private Context context;
private onclicklistener clicklistener;
public newsAdapter(Context context, ArrayList<dataModel> mDataModel, onclicklistener clicklistener) {
this.context = context;
this.mDataModel = mDataModel;
this.clicklistener = clicklistener;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view =
LayoutInflater.from(context).inflate(R.layout.recyclerview_layout,
viewGroup, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final newsAdapter.viewHolder viewHolder, final int i) {
dataModel dataModel = mDataModel.get(i);
viewHolder.mTextView.setText(dataModel.getTitle());
viewHolder.mTextDescrip.setText(dataModel.getDescrip());
Glide.with(context).load(dataModel.getImage()).into(viewHolder.mImageView);
}
#Override
public int getItemCount() {
return mDataModel.size();
}
public interface onclicklistener {
void onItemClick(int position);
}
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
}
MainActivity.java
package wami.ikechukwu.kanu;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import dmax.dialog.SpotsDialog;
public class MainActivity extends AppCompatActivity implements newsAdapter.onclicklistener {
private final String KEY_AUTHOR = "author";
private final String KEY_TITLE = "title";
private final String KEY_DESCRIPTION = "description";
private final String KEY_URL = "url";
private final String KEY_URL_TO_IMAGE = "urlToImage";
private final String KEY_PUBLISHED_AT = "publishedAt";
//this string is appended to the url
String urlLink = "buhari";
ArrayList<dataModel> list;
private RecyclerView recyclerView;
private newsAdapter mAdapter;
private RecyclerView.LayoutManager mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
list = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
mAdapter = new newsAdapter(getApplicationContext(), list, this);
mLayout = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayout);
recyclerView.setAdapter(mAdapter);
jsonParser();
}
private void jsonParser() {
final AlertDialog progressDialog = new SpotsDialog(this, R.style.customProgressDialog);
progressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://newsapi.org/v2/everything?q=" + urlLink + "&language=en&sortBy=publishedAt&pageSize=100&apiKey=655446a36e784e79b2b62adcad45be09", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
//Using a for loop to get the object (data) in the JSON
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
dataModel dataModel = new dataModel();
dataModel.setTitle(jsonObject.getString(KEY_TITLE));
dataModel.setImage(jsonObject.getString(KEY_URL_TO_IMAGE));
dataModel.setDescrip(jsonObject.getString(KEY_DESCRIPTION));
list.add(dataModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "it worked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, news_detail.class);
startActivity(intent);
}
}
recyclerview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/recyclerviewlayout"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:focusable="true"
app:cardCornerRadius="5dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:orientation="vertical">
<TextView
android:id="#+id/layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="1"
android:padding="5dp"
android:textColor="#F000"
android:textSize="17sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/layout_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="#string/Recyclerview_ImageContent"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/layout_descrip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="3"
android:padding="5dp"
android:textColor="#F000"
android:textSize="15sp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimaryDark" />
</LinearLayout>
</android.support.v7.widget.CardView>
activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
In order to set onclick listener in recycler view, you have to follow as below
inner class ViewHolderItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
clicklistener.onItemClick(adapterposition)
}
}
}
OnclickListener will work in Init block
I think should add setOnClickListener method in an onBindViewHolder
And in that you should call another activity with passing your parameter.
Example :- (in onBindViewHolder)
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call activity.
Intent intent = new Intent(activity, anotherActivityname.class);
// For passing values
intent.putExtra(key,value);
startActivity(intent);
}
});
You have to modify your viewHolder in newsAdapter like following.
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public CardView yourCardView;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
yourCardView= itemView.findViewById(R.id.recyclerviewlayout);
// here you set on click listerner to your cardview.
yourCardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
Hope it helps you.
How to make a specific item respond to click in recyclerView?
So for this make your card view clickable false and make your new item(View inside cardview) clickable true:
<Cardview..
android:clickable="false">
...............
......
<View..
android:clickable="true"/>
</Cardview>

Firebase Data not showing in App

I am slightly new to Firebase implementation, and would appreciate any help in the display of my Firebase data in my Android application. There are no specifics in "what data" should be displayed, I am simply attempting to populate the entire database into the application. There are also NOT specific user auth's, the database is shared by all users for the sake of this application.
Here is my Cart.java (Where I would like the data to populate)
package edu.phoenix.mbl402.week2apptt2163;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class sunglass1 extends AppCompatActivity {
private FirebaseAuth mAuth;
private String TAG;
int minteger = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sunglass2);
mAuth = FirebaseAuth.getInstance();
Button button = (Button) findViewById(R.id.addcart);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Octagon Glasses");
myRef.setValue("$64");
Toast.makeText(getBaseContext(), "Added to Cart", Toast.LENGTH_SHORT).show();
}
});
Button button2 = (Button) findViewById(R.id.viewcart);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCart();
}
});
}
public void openCart() {
Intent intent = new Intent(this, cart.class);
startActivity(intent);
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}}
Here is the cart.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_main"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</RelativeLayout>
Here is my cartadapter.java:
package edu.phoenix.mbl402.week2apptt2163;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class cartadapter extends RecyclerView.Adapter<cartadapter.MyViewHolder> {
private List<cartitems> cartList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, price;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
price = (TextView) view.findViewById(R.id.price);
}
}
public cartadapter(List<cartitems> moviesList) {
this.cartList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cart_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
cartitems items = cartList.get(position);
holder.title.setText(items.getTitle());
holder.price.setText(items.getPrice());
}
#Override
public int getItemCount() {
return cartList.size();
}
}
And of course, cartitems.java:
package edu.phoenix.mbl402.week2apptt2163;
public class cartitems {
private String title, price;
public cartitems() {
}
public cartitems(String title, String price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getPrice() {
return price;
}
public void setPrice(String year) {
this.price = price;
}
}
Here is the cart_list_row.xml:
<?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="wrap_content"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="#dimen/row_padding_vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/row_padding_vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textColor="#color/title"
android:textSize="40dp"
android:text="Your Cart"
android:gravity="center"
android:textStyle="bold" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="#+id/price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title" />
</RelativeLayout>
Thank you for absolutely any help,
if you don't use authentication and no error(or Exception) comes then i think you must set auth == null in firebase console database rule part.and if you also done it then check variable name of the class cartitems should same as firebase variable.

Firebase Recycler Adapter not working with recycler view of children

I have a database where my data looks like this.
I have used Firebase Recycler Adapter to the info for S1, S2 and so on, to represent that data in a recycler view. However the data is not showing only in my application. The application is for a teacher to see whether the student is present or not by retrieving data from Firebase.
AttendaceFrag.java
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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.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;
public class AttendanceFrag extends Fragment {
RecyclerView recyclerView;
DatabaseReference databaseReference;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_attendance_frag, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
databaseReference = FirebaseDatabase.getInstance().getReference().child("Student");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
Toast.makeText(getContext(), "Data to show", Toast.LENGTH_LONG).show();
startShowing();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return v;
}
private void startShowing() {
FirebaseRecyclerAdapter<Student, AttendanceFrag.RequestViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Student, AttendanceFrag.RequestViewHolder>(
Student.class,
R.layout.custom_row,
AttendanceFrag.RequestViewHolder.class,
databaseReference
) {
#Override
protected void populateViewHolder(AttendanceFrag.RequestViewHolder viewHolder, Student model, int position) {
viewHolder.setName(model.getName());
viewHolder.setAp(model.getAp());
viewHolder.setRegno(model.getRegno());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class RequestViewHolder extends RecyclerView.ViewHolder {
View mView;
public RequestViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView stname = (TextView) mView.findViewById(R.id.st_name);
stname.setText(name);
}
public void setRegno(String regno) {
TextView stregno = (TextView) mView.findViewById(R.id.st_regno);
stregno.setText(regno);
}
public void setAp(String ap) {
TextView stap = (TextView) mView.findViewById(R.id.st_ap);
stap.setText(ap);
}
}
}
Student.java
public class Student {
private String name, regno,ap;
public Student(String name, String regno, String ap) {
this.name = name;
this.regno = regno;
this.ap = ap;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegno() {
return regno;
}
public void setRegno(String regno) {
this.regno = regno;
}
public String getAp() {
return ap;
}
public void setAp(String ap) {
this.ap = ap;
}
}
activity_attendance_frag.xml
<?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:padding="3dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xxx.AttendanceFrag">
<TableLayout
android:id="#+id/table_lay"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow
android:id="#+id/firstrow"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:background="#drawable/r1"
android:text="Sr. No."
android:id="#+id/srnohead"
android:textAlignment="center"
android:padding="5dp"
android:textColor="#color/colorPrimaryDark"
/>
<TextView
android:padding="5dp"
android:textAlignment="center"
android:background="#drawable/r1"
android:text="Reg. Number"
android:layout_width="135dp"
android:id="#+id/regNohead"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="Name"
android:textAlignment="center"
android:layout_height="wrap_content"
android:layout_width="120dp"
android:id="#+id/namehead"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="P/A"
android:layout_height="wrap_content"
android:id="#+id/attnhead"
android:textColor="#color/colorPrimaryDark"/>
</TableRow>
</TableLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/table_lay"
android:layout_alignParentStart="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
custom_row.xml
<?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="match_parent"
android:weightSum="1"
android:padding="3dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#drawable/r1"
android:text="Sr. No."
android:id="#+id/st_sr"
android:textAlignment="center"
android:padding="5dp"
android:textColor="#color/colorPrimaryDark"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="135dp"
android:padding="5dp"
android:textAlignment="center"
android:background="#drawable/r1"
android:text="Reg. Number"
android:id="#+id/st_regno"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="Name"
android:textAlignment="center"
android:layout_height="wrap_content"
android:layout_width="120dp"
android:id="#+id/st_name"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:layout_width="wrap_content"
android:padding="5dp"
android:background="#drawable/r1"
android:text="P/A"
android:layout_height="wrap_content"
android:id="#+id/st_ap"
android:textColor="#color/colorPrimaryDark"/>
</LinearLayout>
put this in your App level gradle : implementation 'com.firebaseui:firebase-ui-database:3.2.1'
In your onStart method put this :
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Blog")
.limitToLast(50);
FirebaseRecyclerOptions<BlogModel> options =
new FirebaseRecyclerOptions.Builder<BlogModel>()
.setQuery(query, BlogModel.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<BlogModel, BlogViewHolder>(options) {
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_blog, parent, false);
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(BlogViewHolder holder, int position, BlogModel model) {
holder.setTitleBlog(model.getTitle());
holder.setTitleDesc(model.getDescription());
holder.setImage(getApplicationContext(), model.getImage_url());
}
};
adapter.startListening();
mRecycler.setAdapter(adapter);
}
in your BlogViewHolder put this :
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View view;
public BlogViewHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setTitleBlog(String title) {
TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
tvTitle.setText(title);
}
public void setTitleDesc(String desc) {
TextView tvDesc = (TextView) view.findViewById(R.id.tv_desc);
tvDesc.setText(desc);
}
public void setImage(Context context, String url) {
ImageButton ib = (ImageButton) view.findViewById(R.id.ib_blog);
Picasso.with(context).load(url).into(ib);
}
}
And your are all set to go :)
Your database reference pointing wrong node you can use it like this:
FirebaseDatabase.getInstance().getReferenceFromUrl("https://facapp-bee2.firebaseio.com/");
Then .child("Faculty/Student") and recylerview don't use addValueListener. Here you can find how to use recycler view in firebase

Categories

Resources