problem in open another activity from a custom adapter in java - 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) {.........}

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

SharedPreferences Data spreads on every Fragment

I got a problem with the date of my SharedPreferences. I am using 5 Fragment wher you can dynamically add item to a RecyclerView. The Problem is that when ever I save my data on a particular fragment and reload the app the value that has been saved loads into every single Fragment of mine.It actually save the data to the Fragment it is on.I am using Gson to save my ArrayList of items
This is my Fragment (Fragment0 from 5 in total, the others are just copied and refactored)
package com.example.barryblack;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FragmentPage0 extends Fragment {
private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment0, container, false);
loadData();
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(500);
mAdapter = new ExampleAdapter(items);
recyclerView.setAdapter(mAdapter);
taskText = view.findViewById(R.id.tv_country);
insertbtn = view.findViewById(R.id.button_insert);
editTask = view.findViewById(R.id.editTask);
stateButton = view.findViewById(R.id.tv_button);
insertbtn.setEnabled(false);
editTask.addTextChangedListener(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) {
String taskInput = editTask.getText().toString().trim();
insertbtn.setEnabled(!taskInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
task = editTask.getText().toString().trim();
}
});
insertbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
SaveData();
editTask.setText(null);
}
});
return view;
}
private void SaveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<MyItem>>() {
}.getType();
items = gson.fromJson(json, type);
if (items == null) {
items = new ArrayList();
}
}
public void InsertItem() {
items.add(new MyItem(task, stateButton));
mAdapter.notifyItemInserted(items.size());
}
private void CreateExampleList() {
items = new ArrayList<MyItem>();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = 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) {
items.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
SaveData();
}
};
}
This is my Adapter. I think the problem is inside the OnCreateViewHolder but im not quiet sure
package com.example.barryblack;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<MyItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
private EditText topicName;
public Button mButton;
private int clicks = 1;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TOPIC = "topic";
public static final String CLICKS = "clicks";
public ExampleViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_country);
mButton = itemView.findViewById(R.id.tv_button);
topicName = itemView.findViewById(R.id.editText);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicks++;
if (clicks % 2 == 0) {
mButton.setBackgroundResource(R.drawable.button_green);
}else
mButton.setBackgroundResource(R.drawable.button_red);
}
});
}
}
public ExampleAdapter(ArrayList<MyItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
MyItem currentItem = mExampleList.get(position);
holder.mTextView.setText(currentItem.getTaskText());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Use this for your fragments. So every fragment has his own SharedPreferences
private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";
private static final String SHARED_PREFS_FRAGMENT_B = "fragmentB";
...
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A , MODE_PRIVATE);

Store data in 'REALM DATABASE' and show in a recyclerview

I want to store my data in realm database, then retrieve and show it in a recyclerview. All my code is correct in my point of view but it gives me an error about null pointer exception. Despite my efforts I was unable to solve it.
Main Activty Class
package com.deitel.realmrecyclerviewspinnerpriority;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.deitel.realmrecyclerviewspinnerpriority.Adapter.AdapterClass;
import com.deitel.realmrecyclerviewspinnerpriority.Database.RelmHelper;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
Realm realm;
EditText text_name;
EditText text_details;
ImageButton btn_ascending,btn_descending;
RecyclerView rv;
Spinner spinner;
TextView text_data;
Button btn_save,btn_view;
ArrayList<String> itemslist;
AdapterClass addapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_name = findViewById(R.id.text_name);
text_details = findViewById(R.id.text_details);
text_data=findViewById(R.id.text_data);
btn_save=findViewById(R.id.btn_show);
btn_view=findViewById(R.id.btn_view);
btn_save = findViewById(R.id.btn_show);
rv = findViewById(R.id.recyclerview);
btn_ascending=findViewById(R.id.btn_ascending);
btn_descending=findViewById(R.id.btn_descneding);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
final RelmHelper helper=new RelmHelper(realm);
itemslist=helper.retrievedata();
addapter = new AdapterClass(MainActivity.this,itemslist);
rv.setAdapter(addapter);
spinner = findViewById(R.id.spinner);
final ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
arrayList.add(6);
arrayList.add(7);
arrayList.add(8);
arrayList.add(9);
arrayList.add(10);
arrayList.add(11);
arrayList.add(12);
arrayList.add(13);
final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, arrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ModelClass md=new ModelClass();
md.setName(text_name.getText().toString());
md.setDetails(text_details.getText().toString());
/*save data*/
RelmHelper helper=new RelmHelper(realm);
helper.savedata(md);
}
});
}
}
```
MY REALM HELPER CLASS
```
package com.deitel.realmrecyclerviewspinnerpriority.Database;
import android.view.Display;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmResults;
public class RelmHelper {
Realm realm;
public RelmHelper(Realm realm) {
this.realm = realm;
}
public void savedata(final ModelClass modelClass){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ModelClass md=realm.copyToRealm(modelClass);
}
});
}
public ArrayList<String> retrievedata(){
ArrayList<String> modelclassdata=new ArrayList<>();
RealmResults<ModelClass> modelClass=realm.where(ModelClass.class).findAll();
for (ModelClass MD:modelClass){
modelclassdata.add(MD.getName());
modelclassdata.add(MD.getDetails());
// modelclassdata.add(MD.getPriority());
}
return modelclassdata;
}
}
```
Model Class
```
package com.deitel.realmrecyclerviewspinnerpriority.Modelclass;
import io.realm.RealmObject;
public class ModelClass extends RealmObject {
private String name;
private String details;
// private int priority;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
// public int getPriority() {
// return priority;
// }
//
// public void setPriority(int priority) {
// this.priority = priority;
// }
}
```
Adapter Class
```[![enter image description here][1]][1]
package com.deitel.realmrecyclerviewspinnerpriority.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import com.deitel.realmrecyclerviewspinnerpriority.R;
import java.util.ArrayList;
import java.util.List;
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.Viewholder> {
ArrayList<String> modelClassList;
Context context;
public AdapterClass(#NonNull Context context,ArrayList<String> modelClassList){
this.modelClassList=modelClassList;
this.context=context;
}
#NonNull
#Override
public AdapterClass.Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_cardview_layout, viewGroup, false);
Viewholder holder = new Viewholder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull AdapterClass.Viewholder holder, final int position) {
holder.textView_name.setText("Name :" + modelClassList.get(position));
holder.textView_details.setText("Details : " + modelClassList.get(position));
// holder.textView_priority.setText("Priority : " + modelClassList.get(position));
// holder.btn_delete.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// modelClassList.remove(position);
// notifyItemRemoved(position);
// notifyItemRangeChanged(position,modelClassList.size());
// notifyDataSetChanged();
// }
// });
}
#Override
public int getItemCount() {
return modelClassList.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView textView_name;
TextView textView_details;
TextView textView_priority;
ImageButton btn_delete;
public Viewholder(#NonNull View view) {
super(view);
textView_name = view.findViewById(R.id.textview_name);
textView_details = view.findViewById(R.id.textview_details);
textView_priority = view.findViewById(R.id.textview_priotity);
btn_delete=view.findViewById(R.id.btn_delete);
}
}
}

I'm keep getting error. incompatible types: ArrayList<StudentDetails> cannot be converted to ArrayList<AndroidTargets>

The idea is to make a list from Firebase clickable when it is populated in the RecyclerView but I get this error:
error: incompatible types: ArrayList cannot be converted to ArrayList"
at the line which contains "adapter = new TargetDataAdapter(list,this);" in the showstudentdetails activity.
This is the showstudentdetails code:
package com.example.helpresponse;
import android.app.ProgressDialog;
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.view.View;
import android.widget.AdapterView;
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.List;
//Note that you can implement more than one interfaces, that's one of its beauty.
public class ShowStudentDetailsActivity extends AppCompatActivity implements HandleClick {
private DatabaseReference databaseReference;
ProgressDialog progressDialog;
private ArrayList<StudentDetails> list = new ArrayList<>();
private RecyclerView recyclerView;
private TargetDataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_student_details);
initRecyclerView();
initProgressDialog("Loading Data from Firebase Database");
progressDialog.show();
databaseReference = FirebaseDatabase.getInstance().getReference("Police").child("Chats");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
StudentDetails studentDetails = dataSnapshot.getValue(StudentDetails.class);
list.add(studentDetails);
}
adapter = new TargetDataAdapter(list,this);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
private void initProgressDialog(String msg){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(msg);
}
private void initRecyclerView(){
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
#Override
public void onItemClick(int index){
Intent intent = new Intent(this, MapsActivity.class);
int myData = index;
intent.putExtra("myDataKey", myData);
startActivity(intent);
}
}
this is the android targets
package com.example.helpresponse;
public class AndroidTargets {
public String FIELD1;
public Long FIELD2;
public String FIELD3;
}
this is the adapter
package com.example.helpresponse;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class TargetDataAdapter extends RecyclerView.Adapter<TargetDataAdapter.TargetViewHolder> {
private ArrayList<AndroidTargets> targetsArrayList;
private HandleClick mHandleClick;
/*Note that the constructor now take two params which helps us get ride of setmHandleClick() method.*/
public TargetDataAdapter(ArrayList<AndroidTargets> mTargetData, HandleClick handleClick) {
targetsArrayList = mTargetData;
mHandleClick = handleClick;
}
#NonNull
#Override
public TargetViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.target_row, viewGroup, false);
return new TargetViewHolder(v);
}
/* There is an interesting way to make below code neater by abstracting it back to the Activity incharge, let me know if you want that...priority now is to focus on fixing your issue. */
#Override
public void onBindViewHolder(#NonNull TargetViewHolder viewHolder, int i) {
viewHolder.androidTargetName.setText(targetsArrayList.get(i).FIELD1);
viewHolder.androidTargetNumber.setText(String.format(Locale.getDefault(), "API Level: %d", targetsArrayList.get(i).FIELD2));
viewHolder.androidTargetShortName.setText(targetsArrayList.get(i).FIELD3);
viewHolder.myClickableView.setClickable(true);
viewHolder.myClickableView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mHandleClick.onItemClick(i);
}
});
}
#Override
public int getItemCount() {
if (targetsArrayList == null)
return 0;
return targetsArrayList.size();
}
public static class TargetViewHolder extends RecyclerView.ViewHolder {
protected TextView androidTargetName;
protected TextView androidTargetNumber;
protected TextView androidTargetShortName;
protected LinearLayout myClickableView;
public TargetViewHolder(#NonNull View itemView) {
super(itemView);
myClickableView = itemView.findViewById(R.id.linearLayout);
androidTargetShortName = itemView.findViewById(R.id.textView2);
androidTargetName = itemView.findViewById(R.id.textView3);
androidTargetNumber = itemView.findViewById(R.id.textView4);
}
public interface IHomeSelector {
void onCategorySelected(int postion);
}
}
}
this is the Studentdetails
package com.example.helpresponse;
/**
* Created by Juned on 7/25/2017.
*/
public class StudentDetails {
private String name;
public String message;
public String latitude;
public String longitude;
public StudentDetails() {
// This is default constructor.
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getStudentName() {
return name;
}
public void setStudentName(String name) {
this.name = name;
}
}
You are getting that error because you are passing in the following line of code:
adapter = new TargetDataAdapter(list,this);
To the TargetDataAdapter constructor a list which is declared to be of type ArrayList<StudentDetails> and in your adapter, the list is of type ArrayList<AndroidTargets>, hence the error. To solve this, you should pass a list of the same data type, more precisely, of type ArrayList<AndroidTargets>. So all the objects in the list must be of type AndroidTargets and not of type StudentDetails.
If you to display a list of StudentDetails objects then you need to create another adapter that accepts a list of type StudentDetails.

RecyclerView is not displaying any data from the firestore

I have list of Categories of Subjects in my firestore database and i want it to be displayed in my app ( which i thought can be done by recyclerView).But my RecyclerView is not populating any data.You can see my code below:
Question_list.java
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 com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
public class Question_list extends AppCompatActivity {
private static final String TAG ="Firelog" ;
private RecyclerView mMainList;
private FirebaseFirestore mFirestore;
private CategoryAdapter categoryAdapter;
private List<Categories> list_category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_list);
mMainList = (RecyclerView)findViewById(R.id.main_list_id);
//mMainList.setHasFixedSize(true);
mMainList.setLayoutManager(new LinearLayoutManager(this));
mMainList.setAdapter(categoryAdapter);
mFirestore = FirebaseFirestore.getInstance();
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
mFirestore.collection("Questions").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(e!=null){
Log.d(TAG, "Error: "+ e.getMessage());
}
for(DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
if(doc.getType() == DocumentChange.Type.MODIFIED){
//String document = doc.getDocument().getString("Category");
Categories categories = doc.getDocument().toObject(Categories.class);
list_category.add(categories);
Log.d(TAG, "Category: "+ categories);
categoryAdapter.notifyDataSetChanged();
}
}
}
});
}
}
CategoryAdapter.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.List;
public class CategoryAdapter extends
RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
public List<Categories> list_categorie;
public CategoryAdapter(List<Categories> list_categorie){
this.list_categorie = list_categorie;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_list,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.mCategoryText.setText(list_categorie.get(position).getCategory());
}
#Override
public int getItemCount() {
return list_categorie.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View mview;
public TextView mCategoryText;
public ViewHolder(View itemView) {
super(itemView);
mview = itemView;
mCategoryText = (TextView)mview.findViewById(R.id.category_text_id);
}
}
}
Categories.java
public class Categories {
String category;
public Categories(){}
public Categories(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
}
Above are my all java classes. I haven't uploaded my XML file as i think the problem is in the java class.
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
list_category should be initialized before passing it to the adapter
list_category = new ArrayList<>();
categoryAdapter = new CategoryAdapter(list_category);

Categories