Android Studio online shopping - java

I have this problem with this app. The does not show me the Items quantity and price, But they show the name of the item, and I don't have any errors when I run the up.Please give me an advice if you can.
The cartactivity code :
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.bartertrader.Model.Cart;
import com.example.bartertrader.Prevalent.Prevalent;
import com.example.bartertrader.ViewHolder.CartViewHolder;
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 CartActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Button NextProcessBtn;
private TextView txtTotalAmount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
recyclerView= findViewById(R.id.cart_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
NextProcessBtn = (Button) findViewById(R.id.next_process_btn);
txtTotalAmount =(TextView) findViewById(R.id.total_price);
}
#Override
protected void onStart() {
super.onStart();
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions<Cart>options=
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartListRef.child("User View").child(Prevalent.currentOnlineUser.getPhone())
.child("Products"), Cart.class).build();
FirebaseRecyclerAdapter<Cart, CartViewHolder> adapter
= new FirebaseRecyclerAdapter<Cart, CartViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartViewHolder holder, int position, #NonNull Cart model) {
holder.txtProductName.setText(model.getPname());
holder.txtProductQuantity.setText("Quantity =" + model.getQuantity());
holder.txtProductPrice.setText("Price= " + model.getPrice() + "");
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout,parent,false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
}
Cart class
private String pid, pname, price , quantity ,discount;
public Cart() {
}
public Cart(String pid, String pname, String price, String quantity, String dicount) {
this.pid = pid;
this.pname = pname;
this.price = price;
this.quantity = quantity;
this.dicount = dicount;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getDicount() {
return dicount;
}
public void setDiscount(String discount) {
this.dicount = dicount;
}
}
Cardviewholder class
import android.view.View;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bartertrader.Interface.ItemClickListner;
import com.example.bartertrader.R;
public class CartViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtProductName, txtProductPrice, txtProductQuantity;
private ItemClickListner itemClickListner;
public CartViewHolder( View itemView) {
super(itemView);
txtProductName = itemView.findViewById(R.id.cart_product_name);
txtProductPrice = itemView.findViewById(R.id.cart_product_price);
txtProductQuantity = itemView.findViewById(R.id.cart_product_quantity);
}
#Override
public void onClick(View view) {
itemClickListner.onClick(view, getAdapterPosition(),false);
}
public void setItemClickListner(ItemClickListner itemClickListner) {
this.itemClickListner = itemClickListner;
}
}
I dont undestart why it show me the Name and the price and quantity are null

Your Firebase database is giving you Cart objects where the price and quantity is not set. You should ensure that you are setting this attributes where you are loading the records into Firebase.

Related

Retrieving Data From Firestore Firebase

I am working on an Inventory Management app for which I tried to retrieve data from my fire store database but I am not able to get why . I created a Adapter file and and Data file and linked them with main file
My Code for Main Activity file
package com.example.inventorymanagment;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import java.util.ArrayList;
public class Measure extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<data> itemList;
adapter adapter;
FirebaseFirestore db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_measure);
recyclerView= findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
db = FirebaseFirestore.getInstance();
itemList= new ArrayList<>();
adapter= new adapter(Measure.this,itemList);
recyclerView.setAdapter(adapter);
getdata();
}
#SuppressLint("NotifyDataSetChanged")
private void getdata() {
db.collection("Inventory").orderBy("Name", Query.Direction.ASCENDING)
.addSnapshotListener((value, error) -> {
if(error!=null){
Log.e("Firestore error",error.getMessage());
return;
}
for(DocumentChange dc : value.getDocumentChanges()){
if(dc.getType() == DocumentChange.Type.ADDED){
itemList.add(dc.getDocument().toObject(data.class));
}
adapter.notifyDataSetChanged();
}
});
}
}
Code for Adapter file
package com.example.inventorymanagment;
import android.content.Context;
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 adapter extends RecyclerView.Adapter<adapter.MyViewHolder>{
Context context;
ArrayList<data> itemList;
public adapter(Context context, ArrayList<data>itemList)
{
this.context = context;
this.itemList = itemList;
}
#NonNull
#Override
public adapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
data data = itemList.get(position);
holder.Name.setText(data.Name);
holder.Quantity.setText(String.valueOf(data.Quantity));
}
#Override
public int getItemCount() {
return itemList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Name, Quantity;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Name=itemView.findViewById(R.id.name);
Quantity=itemView.findViewById((R.id.quantity));
}
}
}
My Code for Data file
package com.example.inventorymanagment;
public class data {
String Name;
long Quantity;
public data(){}
public data(String name, long quantity) {
Name = name;
Quantity = quantity;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public long getQuantity() {
return Quantity;
}
public void setQuantity(long quantity) {
Quantity = quantity;
}
}
please help me find my error
In onBindViewHolder(#NonNull MyViewHolder holder, int position) {
data data = itemList.get(position);
holder.Name.setText(data.Name);
holder.Quantity.setText(String.valueOf(data.Quantity));
try setting data.getName() instead of data.Name

Loop and Changing TextView in CardView within RecyclerView outside of onBindViewHolder

I want to loop through all CardViews and change the text and color of a TextView within a single CardView item using a button click. The following code seems to produce the desired results but I'm not certain that it's the most effective code or even accurate (index).
CustomAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {
private Context context;
private List<MyModel> list;
public CustomAdapter(Context context, List<MyModel> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.single_items, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
holder.textName.setText(list.get(position).getName());
holder.textAge.setText(String.valueOf(list.get(position).getAge()));
}
#Override
public int getItemCount() {
return list.size();
}
}
CustomViewHolder
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView textName, textAge;
public CustomViewHolder(#NonNull View itemView) {
super(itemView);
textName = itemView.findViewById(R.id.textName);
textAge = itemView.findViewById(R.id.textAge);
}
}
MainActivity
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
List<MyModel> myModelList;
CustomAdapter customAdapter;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
}
private void loadData() {
recyclerView = findViewById(R.id.recycler_main);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
myModelList = new ArrayList<>();
myModelList.add(new MyModel("Joe", 21));
myModelList.add(new MyModel("Jane", 26));
myModelList.add(new MyModel("Kyle", 19));
myModelList.add(new MyModel("Scott", 30));
customAdapter = new CustomAdapter(this, myModelList);
recyclerView.setAdapter(customAdapter);
}
public void onClickBtn(View v)
{
String searchString = "Kyle";
for (int x = recyclerView.getChildCount(), i = 0; i < x; ++i) {
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(recyclerView.getChildAt(i));
TextView txtName = holder.itemView.findViewById(R.id.textName);
if (txtName.getText().toString().equals(searchString.toString())) {
txtName.setText("Found " + txtName.getText().toString());
txtName.setTextColor(Color.GREEN);
customAdapter.notifyItemChanged(x);
}
}
}
}
MyModel
public class MyModel {
String name = "";
int age = 0;
public MyModel(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
It's important that I iterate through the list in button click event. Functionality to be changed later. Really appreciate any advice and feedback. Thanks a lot.

Firebase data retrieve and passing it from fragment to new activity not working

I am developing an android app which shows the user with the latest jobs from various fields. When the jobs are displayed and when the user clicks on view more, the job description is not getting displayed.
I have passed data from fragment to new activity and displaying it in the new activity. There is no error but the details are not getting displayed. I have attached the code and the firebase database structure.
Here is the WorkFragment.java file which shows the jobs in recyclerview.
WorkFragment.java
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
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 com.google.firebase.database.annotations.Nullable;
import java.util.ArrayList;
public class WorkFragment extends Fragment {
DatabaseReference databaseReference;
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
ArrayList<Jobs> jobs;
MyAdapter adapter;
ProgressDialog pd;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_work, container, false);
recyclerView = view.findViewById(R.id.work);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
pd = new ProgressDialog(getContext());
pd.setMessage("Loading Jobs for you...");
pd.show();
jobs = new ArrayList<Jobs>();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("Jobs");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Jobs j = ds.getValue(Jobs.class);
jobs.add(j);
}
pd.dismiss();
adapter = new MyAdapter(getContext(), jobs);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
return view;
}
}
Here is the MyAdapter.java class which does the job for recyclerview.
MyAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
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 MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<Jobs> jobs;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
public MyAdapter(Context c, ArrayList<Jobs> 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, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.jobtitle.setText(jobs.get(position).getJobtitle());
holder.jobtype.setText(jobs.get(position).getJobtype());
holder.companyname.setText(jobs.get(position).getCompany());
holder.location.setText(jobs.get(position).getLocation());
holder.jobdate.setText(jobs.get(position).getJobdate());
holder.viewmore.setText(jobs.get(position).getViewmore());
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Jobs");
holder.viewmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String jobtitle = dataSnapshot.child("jobtitle").getValue(String.class);
String company = dataSnapshot.child("company").getValue(String.class);
String location = dataSnapshot.child("location").getValue(String.class);
String jobtype = dataSnapshot.child("jobtype").getValue(String.class);
String startDate = dataSnapshot.child("startdate").getValue(String.class);
String salary = dataSnapshot.child("salary").getValue(String.class);
String about = dataSnapshot.child("about").getValue(String.class);
String responsiblities = dataSnapshot.child("responsiblities").getValue(String.class);
String musthave = dataSnapshot.child("musthave").getValue(String.class);
String seniority = dataSnapshot.child("seniority").getValue(String.class);
Intent intent = new Intent(context, JobDescription.class);
intent.putExtra("JOBTITLE", jobtitle);
intent.putExtra("COMPANY", company);
intent.putExtra("LOCATION", location);
intent.putExtra("JOBTYPE", jobtype);
intent.putExtra("STARTDATE", startDate);
intent.putExtra("SALARY", salary);
intent.putExtra("ABOUT", about);
intent.putExtra("RESPONSIBLITIES", responsiblities);
intent.putExtra("MUSTHAVE", musthave);
intent.putExtra("SENIORITY", seniority);
context.startActivity(intent);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return jobs.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView jobtitle, jobtype, companyname, location, jobdate, viewmore;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
jobtitle = (TextView) itemView.findViewById(R.id.jobTitle);
jobtype = (TextView) itemView.findViewById(R.id.jobType);
companyname = (TextView) itemView.findViewById(R.id.companyName);
location = (TextView) itemView.findViewById(R.id.location);
jobdate = (TextView) itemView.findViewById(R.id.jobDate);
viewmore = (TextView) itemView.findViewById(R.id.viewMore);
}
}
}
Here is the Job.class.
Jobs.java
public class Jobs {
private String jobtitle, jobtype, company, location, jobdate, viewmore, startdate, salary, about, responsiblities, musthave, seniority;
public Jobs() {
}
public Jobs(String jobtitle, String jobtype, String company, String location, String jobdate, String viewmore, String startdate, String salary, String about, String responsiblities, String musthave, String seniority) {
this.jobtitle = jobtitle;
this.jobtype = jobtype;
this.company = company;
this.location = location;
this.jobdate = jobdate;
this.viewmore = viewmore;
this.startdate = startdate;
this.salary = salary;
this.about = about;
this.responsiblities = responsiblities;
this.musthave = musthave;
this.seniority = seniority;
}
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getJobtype() {
return jobtype;
}
public void setJobtype(String jobtype) {
this.jobtype = jobtype;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getJobdate() {
return jobdate;
}
public void setJobdate(String jobdate) {
this.jobdate = jobdate;
}
public String getViewmore() {
return viewmore;
}
public void setViewmore(String viewmore) {
this.viewmore = viewmore;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String getResponsiblities() {
return responsiblities;
}
public void setResponsiblities(String responsiblities) {
this.responsiblities = responsiblities;
}
public String getMusthave() {
return musthave;
}
public void setMusthave(String musthave) {
this.musthave = musthave;
}
public String getSeniority() {
return seniority;
}
public void setSeniority(String seniority) {
this.seniority = seniority;
}
}
Here is the JobDescription.java which shows the details of job. In this class, Iam getting details from fragment and displaying it.
JobDescription.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class JobDescription extends AppCompatActivity {
TextView jobtitle, company, location, startDate, salary, aboutText, responsiblityText, musthaveText, jobtypetext, seniority;
Button applyNow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_description);
getSupportActionBar().setTitle("Job Description");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
jobtitle = (TextView) findViewById(R.id.jobTitle);
company = (TextView) findViewById(R.id.company);
location = (TextView) findViewById(R.id.location);
startDate = (TextView) findViewById(R.id.startDate);
salary = (TextView) findViewById(R.id.salary);
aboutText = (TextView) findViewById(R.id.aboutText);
responsiblityText = (TextView) findViewById(R.id.responsiblityText);
musthaveText = (TextView) findViewById(R.id.musthaveText);
jobtypetext = (TextView) findViewById(R.id.jobtypetext);
seniority = (TextView) findViewById(R.id.seniority);
applyNow = (Button) findViewById(R.id.applyBtn);
jobtitle.setText(getIntent().getStringExtra("JOBTITLE"));
company.setText(getIntent().getStringExtra("COMPANY"));
location.setText(getIntent().getStringExtra("LOCATION"));
startDate.setText(getIntent().getStringExtra("STARTDATE"));
salary.setText(getIntent().getStringExtra("SALARY"));
aboutText.setText(getIntent().getStringExtra("ABOUT"));
responsiblityText.setText(getIntent().getStringExtra("RESPONSIBLITIES"));
musthaveText.setText(getIntent().getStringExtra("MUSTHAVE"));
jobtypetext.setText(getIntent().getStringExtra("JOBTYPE"));
seniority.setText(getIntent().getStringExtra("SENIORITY"));
}
}
Here is the firebase database structure.
In your adapter you dont need to add valueeventlistner , all you need is to pass data to descriptionactivity as shown below
holder.viewmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, JobDescription.class);
intent.putExtra("JOBTITLE", jobs.getJobtitle);
intent.putExtra("COMPANY", jobs.getcompany);
context.startActivity(intent);
}
});

problem in open another activity from a custom adapter in java

I need to open another activity from a custom adapter, just like a list and then when I click on that, it will take to another activity and get a data from database and show it in the text view,
the problem is in SearchAdapter.java in the context.startActivity(intent);
here's my searchAdapter.java
package Adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
//import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.manualdiagnosiskeperawatan.R;
import com.example.manualdiagnosiskeperawatan.isiDiagnosis;
import java.util.List;
import Model.Daftar;
class SearchViewHolder extends RecyclerView.ViewHolder{
public TextView judul, diagnosis;
public SearchViewHolder(View itemView) {
super(itemView);
judul = itemView.findViewById(R.id.judul);
diagnosis = itemView.findViewById(R.id.textViewIsi);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
{
private Context context;
private List<Daftar> data;
public SearchAdapter(Context context, List<Daftar> data) {
this.context = context;
this.data = data;
}
#Override
public SearchViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(final SearchViewHolder holder, final int position)
{
holder.judul.setText(data.get(position).getJudul());
//open activity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, data.get(position).getDiagnosis(),Toast.LENGTH_SHORT).show();
//this code, isn't working
Intent intent = new Intent(context, isiDiagnosis.class);
intent.putExtra("did",data.get(position).getDid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
}
and here is my isiDiagnosis.java which will be opened when I clicked the list from the SearchAdapter.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
import Model.Daftar;
public class isiDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
List<Daftar> daftars = new ArrayList<>();
private TextView judul, diagnosis;
private String DID = "judul";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_isi_diagnosis);
DID = getIntent().getStringExtra("judul");
database = new Database(this);
diagnosis = (TextView) findViewById(R.id.textViewIsi);
//init DB
loadData(DID);
}
private void loadData(String did) {
//i don't really know how to code, just see from the youtube, so i made this myself
// database.getDiagnosis();
// String diagnosis = daftars.get(database.getDiagnosis());
// database.getDiagnosis(diagnosis.setText());
}
}
here's my searchDiagnosis.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.ListViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Adapter;
import android.widget.ListView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
public class searchDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
#Override
protected void onStart() {
super.onStart();
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_diagnosis);
//init view
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar =(MaterialSearchBar) findViewById(R.id.search_bar);
//init DB
database = new Database(this);
//Setup search bar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled) {
// recyclerView.setAdapter(adapter);
//if close Search, just restore default
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//Init adapter default set all result
adapter = new SearchAdapter(this,database.getDaftar());
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDataByJudul(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getJudul();
materialSearchBar.setLastSuggestions(suggestList);
}
}
here's my Daftar.class
package Model;
public class Daftar {
public int id;
public String did, judul, diagnosis;
public Daftar(int id,String did, String judul, String diagnosis) {
this.id = id;
this.did = did;
this.judul = judul;
this.diagnosis = diagnosis;
}
public Daftar() {
}
public int getId() {
return id;
}
public String getDid() {
return did;
}
public void setDid(String did) {
this.did = did;
}
public void setId(int id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
}
Look I don't know what kind of database is this, but I know that you are not receiving the intent extra correctly:
In your isiDiagnosis:
............
//get the did like this
DID = getIntent().getStringExtra("did");
.......
loadData(DID);
//loading the data is up to you according to the database
private void loadData(String did) {.........}

I can't fetch phone's contacts into listview in android app

I want to fetch all my phone contacts into a listview of my app. What i did here is i have an activity where i put a listview & i want display all my contacts there, so for that created a data model & an adapter, but every time i get this error,
I don't know what is the error,
FATAL EXCEPTION: main
Process: com.example.theroos.messageism, PID: 25858
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.theroos.messageism.UserObject
My FindUserActivity is,
FindUserActivity.java
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class FindUserActivity extends AppCompatActivity {
private RecyclerView mUserList;
private RecyclerView.Adapter mUserListAdapter;
private RecyclerView.LayoutManager mUserListLayoutManager;
ArrayList<UserObject>userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_user);
userList = new ArrayList<>();
initializeRecyclerView();
getcontactlist();
}
private void getcontactlist(){
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null,null);
while(phones.moveToNext()){
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
UserObject mContacts = new UserObject(name,phone);
userList.add(mContacts);
mUserListAdapter.notifyDataSetChanged();
}
}private void initializeRecyclerView() {
mUserList = findViewById(R.id.contacts_listview);
mUserList.setNestedScrollingEnabled(false);
mUserList.setHasFixedSize(false);
mUserListLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL,false);
mUserList.setLayoutManager(mUserListLayoutManager);
mUserListAdapter = new UserListAdapter(userList);
mUserList.setAdapter(mUserListAdapter);
}
}
My data model is,
UserObject.java
public class UserObject {
private String name;
private String phone;
public UserObject(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName() { return name;}
public String getPhone() { return phone;}
}
UserListAdapter.java
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.TextView;
import java.util.ArrayList;
public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.UserListViewHolder> {
ArrayList<UserObject> userList;
public UserListAdapter(ArrayList<UserObject> userList){
this.userList = userList;
}
#NonNull
#Override
public UserListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View layoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_user,null,false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
UserListViewHolder rcv = new UserListViewHolder(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(#NonNull UserListViewHolder holder, int position) {
holder.mName.setText(userList.get(position).getName());
holder.mPhone.setText(userList.get(position).getPhone());
}
#Override
public int getItemCount() {
return userList.size();
}
public class UserListViewHolder extends RecyclerView.ViewHolder {
TextView mName, mPhone;
public UserListViewHolder(View View) {
super(View);
mName = View.findViewById(R.id.name);
mPhone = View.findViewById(R.id.phone);
}
}
}
I have tried several ways but i can't find any solution. Please help.

Categories