I need to create recyclerview cardview in fragment from the data that is written in a DiagloFragment
What would you do? How can I create a recycler view with the list once I press the button "HECHO"?
IMAGE CAPTURE DATA
Can you explain to me what should I do or even post an example please (done by you or posted somewhere else)?
Beforehand thank you very much.
DialogFragment class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment_captura_dialog_act, container, false);
View v = inflater.inflate(R.layout.frag_capactividades, container, false);
Spinner spinnerA;
spinnerA = (Spinner)v.findViewById(R.id.spinnerConf);
bguardar = (Button) v.findViewById(R.id.bGuaradrPaga);
codigo = (EditText) v.findViewById(R.id.tCodData) ;
precio = (EditText) v.findViewById(R.id.tPrecioData);
preciounidadextra = (EditText) v.findViewById(R.id.preciouextra);
cantidadminima = (EditText) v.findViewById(R.id.tCanMinData);
primadominical = (EditText) v.findViewById(R.id.tPrimaData);
final String tipojornada = spinnerA.getSelectedItem().toString();
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
});
return v;
}
}
Card layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtcodigoMostrar"
android:layout_width="1dp"
android:layout_height="1dp"
android:visibility="invisible" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="16sp"
android:layout_marginTop="16sp"
android:src="#drawable/ajusted" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="10dp"
android:width="2dp"
android:gravity="right"
android:text="Apuntador"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtNombreMostrar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="4dp"
android:text="Nombre"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="10dp"
android:width="2dp"
android:gravity="right"
android:text="Precio"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtPrecioMostrar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="4dp"
android:text="Precio"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/btnEditar"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_width="100dp"
android:layout_height="30dp"
android:text="Editar"
android:textSize="14dp"
android:visibility="invisible" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Fragment class to cretae recyclerview:
public class empleado extends Fragment implements View.OnClickListener {
FloatingActionButton btndialog;
private SQLiteDatabase db;
RecyclerView idrecyclerview, recyclerView;
static List<ActividadesModel> listCont;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v5 = inflater.inflate(R.layout.activity_empleado, container, false);
RecyclerView recyclerView = v5.findViewById(R.id.idrecyclerviewCa);
//recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(viewAdapter);
return v5;
}
public empleado(String codigo,String precio,String preciounidadextra,String cantidadminima,String primadominical,String tipojornada){
}
public static void guardaempleado(String codigo, String precio, String preciounidadextra, String cantidadminima, String primadominical, String tipojornada){
listCont = new ArrayList<>();
listCont.add(new ActividadesModel("codigo", "precio", "preciounidadextra", "cantidadminima", "primadominical", "tipojornada"));
}
private void ShowMessage() {
final String[] actividades = {"act1", "act2", "act3", "act4", "act5"};
final int itemSelected = 0;
new AlertDialog.Builder(getContext())
.setTitle("Selecciona la actividad")
.setSingleChoiceItems(actividades, itemSelected, new DialogInterface.OnClickListener() {
#Override
// public void onClick(DialogInterface dialogInterface, int selectedIndex) {
public void onClick(DialogInterface dialog, int position) {
// String nombreselect = empleados[position];
Toast.makeText(getContext(), "Position: " + position, Toast.LENGTH_SHORT).show();
String nombreselect = actividades[position];
SharedPreferences sharedPrefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("actividad", nombreselect);
editor.commit();
// empleado.setText(empleadotext);
}
})
// .setNeutralButton("OK", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment dialogs = new CapturaDialogAct(); // creating new object
dialogs.show(fm, "dialog");
}
})
.show();
}
CaptureDialog class:
public class CapturaDialogAct extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
TextView textView;
Button bguardar;
EditText codigo,precio,preciounidadextra, cantidadminima,primadominical;
Adapter rvAdapter;
RecyclerView recyclerView;
private static RecyclerView.Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment_captura_dialog_act, container, false);
View v = inflater.inflate(R.layout.frag_capactividades, container, false);
Spinner spinnerA;
spinnerA = (Spinner)v.findViewById(R.id.spinnerConf);
bguardar = (Button) v.findViewById(R.id.bGuaradrPaga);
codigo = (EditText) v.findViewById(R.id.tCodData) ;
precio = (EditText) v.findViewById(R.id.tPrecioData);
preciounidadextra = (EditText) v.findViewById(R.id.preciouextra);
cantidadminima = (EditText) v.findViewById(R.id.tCanMinData);
primadominical = (EditText) v.findViewById(R.id.tPrimaData);
final String tipojornada = spinnerA.getSelectedItem().toString();
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
});
return v;
}
}
Model:
public class ActividadesModel implements Serializable {
private String codigo ,precio, preciounidadextra, cantidadminima, primadominical, tipojordana;
public ActividadesModel( String precio, String preciounidadextra, String cantidadminima, String primadominical, String codigo, String tipojordana){
this.codigo = codigo;
}
public String getCodigo()
{
return codigo;
}
public void setCodigo(String codigo){
this.codigo = codigo;
}
public String getPrecio(){
return precio;
}
public void setPrecio(){
this.precio = precio;
}
public String getPreciounidadextra(){
return preciounidadextra;
}
public void setPreciounidadextra(){
this.preciounidadextra = preciounidadextra;
}
public String getCantidadminima(){
return cantidadminima;
}
public void setCantidadminima(){
this.cantidadminima = cantidadminima;
}
public String getPrimadominical(){
return primadominical;
}
public void setPrimadominical(){
this.primadominical = primadominical;
}
public String getTipojordana(){
return tipojordana;
}
public void setTipojordana(){
this.tipojordana = tipojordana;
}
}
Add ADapter:
public class AdapterAct extends RecyclerView.Adapter<AdapterAct.MyViewHolder> implements Filterable {
private List<ActividadesModel> actividadesModelList = new ArrayList<>();
private Context context;
private List<ActividadesModel> actividadesArrayList;
private IAxiliarActividades iAxiliarActividades;
List<ActividadesModel> contactList;
public AdapterAct(Context context, List<ActividadesModel> listCont) {
this.context = context;
this.contactList = contactList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// return null;
View v;
v = LayoutInflater.from(context).inflate(R.layout.card_actividad, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(v);
return myViewHolder;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView precio;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.txtNombreMostrar);
precio = (TextView) itemView.findViewById(R.id.txtPrecioMostrar);
}
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
//Codigo para crear el listado de acitividades
}
#Override
public int getItemCount() {
return 0;
}
#Override
public Filter getFilter() {
return null;
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView nombre, precio;
public myViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
Please follow below steps to create interface listener for the the DialogFragment input to be returned to your fragment.
Step 1: Create an interface inside the CapturaDialogAct
DialogFragment, and an instance field of it:
Step 2: Modify the CapturaDialogAct to accept an argument of this
interface
Step 3: Trigger the interface method whenever you click the
DialogFragment button.
class CapturaDialogAct extends DialogFragment {
...
// Step 1
public interface OnSelectionListener {
void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada);
}
private OnSelectionListener mOnSelectionListener;
// Step 2
public CapturaDialogAct(OnSelectionListener listener) {
this.mOnSelectionListener = listener;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment_captura_dialog_act, container, false);
View v = inflater.inflate(R.layout.frag_capactividades, container, false);
//..... reset of code
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
// Step 3
if (mOnSelectionListener != null) {
mOnSelectionListener.onConfirmed(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
}
});
}
}
Step 4: at your fragment, change the instantiation of the DialogFragment to implement the interface and handle the returned text with its callback
Replace
DialogFragment dialogs = new CapturaDialogAct(); // creating new object
With
// Step 4
DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
});
UPDATE
It already performs all the steps, it does not mark an error but it does not create the cardview, I will add the adapter to the post
In Step 4 change the list of the RecyclerView adapter, and update the UI.
DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
listCont = new ArrayList<>();
listCont.add(new ActividadesModel(codigo, precio, preciounidadextra, cantidadminima, primadominical, tipojornada));
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
RecyclerView recyclerView = getView().findViewById(R.id.idrecyclerviewCa);
//recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(viewAdapter);
});
Edit
You get an error as you define the RecyclerView as a local variable to onCreateView, so you need to select the class RecyclerView field instead.
So, the change
public class empleado extends Fragment implements View.OnClickListener {
RecyclerView idrecyclerview, recyclerView; // this is the field class variable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v5 = inflater.inflate(R.layout.activity_empleado, container, false);
recyclerView = v5.findViewById(R.id.idrecyclerviewCa); // here is the change
Then, added dismiss() when you hit the dialog hide in order to hide it.
So, in your dialog fragment add dismiss() as below
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
// Step 3
if (mOnSelectionListener != null) {
mOnSelectionListener.onConfirmed(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
dismiss(); /// <<<<< here is the change
}
});
Also made the adapter as a fragment class field in order to use it when you dismiss the dialog so created AdapterAct mViewAdapter in empleado fragment
Here is the your entire fragment after this modificaiton
public class empleado extends Fragment implements View.OnClickListener {
//private static ArrayList<Object> listCont;
FloatingActionButton btndialog;
// public static TextView empleado;
private SQLiteDatabase db;
RecyclerView idrecyclerview, recyclerView;
static List<ActividadesModel> listCont;
private AdapterAct mViewAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v5 = inflater.inflate(R.layout.activity_empleado, container, false);
recyclerView = v5.findViewById(R.id.idrecyclerviewCa);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
listCont = new ArrayList<>();
mViewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(mViewAdapter);
return v5;
}
//public empleado(String codigo,String precio,String preciounidadextra,String cantidadminima,String primadominical,String tipojornada){
public empleado() {
// listCont = new ArrayList<>();
// listCont.add(new ActividadesModel("precio", "preciounidadextra", "cantidadminima", "primadominical", "codigo", "tipojornada"));
}
public static void guardaempleado(String codigo, String precio, String preciounidadextra, String cantidadminima, String primadominical, String tipojornada) {
listCont = new ArrayList<>();
listCont.add(new ActividadesModel(precio, preciounidadextra, cantidadminima, primadominical, codigo, tipojornada));
// new empleado();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//inflate menu
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle menu item clicks
int id = item.getItemId();
if (id == R.id.action_settings) {
//do your function here
Toast.makeText(getActivity(), "Sincronizar", Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_sort) {
//do your function here
Toast.makeText(getActivity(), "Buscar", Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_hoy) {
//do your function here
Toast.makeText(getActivity(), "Hoy", Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_anterior) {
//do your function here
Toast.makeText(getActivity(), "Ayer", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
private static String PREF_NAME = "prefs";
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
private Context mContext;
#Override
public void onViewCreated(View v5, Bundle savedInstanceState) {
//public void onClick(View v5) {
FloatingActionButton btndialog = (FloatingActionButton) v5.findViewById(R.id.floatingActionButton);
final String[] nivelItems = getResources().getStringArray(R.array.nivel);
final int itemSelected = 0;
try {
btndialog.setOnClickListener(new View.OnClickListener() {
// JSONObject js = createJsonObjectInv();
// JSONArray arr = js.getJSONArray("data");
//JSONArray arr3 = js.getJSONArray("data");
//String[] list = new String[arr.length()];
//String[] arr2 = arr.toString().replace("},{", " ,").split(" ");
//#Override
public void onClick(View v) {
try {
JSONObject js = createJsonObjectInv();
JSONArray arr = js.getJSONArray("data");
final String[] list = new String[arr.length()];
for (int i = 0; i <= arr.length() - 1; i++) {
JSONObject element = arr.getJSONObject(i);
String InvernaderoId = "\"invernaderoId\":\"" + element.getString("invernaderoId") + "\", ";
String Name = "\"name\":\"" + element.getString("name") + "\", ";
String Invernarder = "\"Invernarder\":\"" + element.getString("Invernarder") + "\"";
//list[i] = InvernaderoId + Name + Invernarder;
list[i] = Name.substring(8);
}
// final String[] empleados = {"Luis", "Daniel", "Juan", "Jose", "Cesar"};
// final String[] empleados = arr2;
new AlertDialog.Builder(getContext())
.setTitle("Selecciona el Invernadero")
// .setSingleChoiceItems(empleados, itemSelected, new DialogInterface.OnClickListener() {
.setSingleChoiceItems(list, -1, new DialogInterface.OnClickListener() {
#Override
// public void onClick(DialogInterface dialogInterface, int selectedIndex) {
public void onClick(DialogInterface dialog, int position) {
// String nombreselect = empleados[position];
Toast.makeText(getContext(), "Position: " + position, Toast.LENGTH_SHORT).show();
String empleadotext = list[position];
//empleado.setText(empleadotext);
// SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences sharedPrefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("inver", empleadotext);
editor.commit();
}
})
//.setPositiveButton("Ok", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ShowMessage();
}
})
.setNegativeButton("Cancel", null)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void ShowMessage() {
final String[] actividades = {"act1", "act2", "act3", "act4", "act5"};
final int itemSelected = 0;
new AlertDialog.Builder(getContext())
.setTitle("Selecciona la actividad")
.setSingleChoiceItems(actividades, itemSelected, new DialogInterface.OnClickListener() {
#Override
// public void onClick(DialogInterface dialogInterface, int selectedIndex) {
public void onClick(DialogInterface dialog, int position) {
// String nombreselect = empleados[position];
Toast.makeText(getContext(), "Position: " + position, Toast.LENGTH_SHORT).show();
String nombreselect = actividades[position];
SharedPreferences sharedPrefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("actividad", nombreselect);
editor.commit();
// empleado.setText(empleadotext);
}
})
// .setNeutralButton("OK", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
/* FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment dialogs = new CapturaDialogAct(); // creating new object
dialogs.show(fm, "dialog");
*/
FragmentManager fm = getActivity().getSupportFragmentManager();
/* DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
}
});*/
DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
/*
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setAdapter(viewAdapter);
*/
// RecyclerView recyclerView = getView().findViewById(R.id.idrecyclerviewCa);
//recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
mViewAdapter.addItem(new ActividadesModel(codigo, precio, preciounidadextra, cantidadminima, primadominical, tipojornada));
}
});
dialogs.show(fm, "dialog");
}
})
.show();
}
public JSONObject createJsonObjectInv() throws JSONException {
Cursor cursor = getAllDataInv();
JSONObject jobj;
JSONArray arr = new JSONArray();
cursor.moveToFirst();
while (cursor.moveToNext()) {
jobj = new JSONObject();
jobj.put("invernaderoId", cursor.getString(0));
jobj.put("name", cursor.getString(1));
jobj.put("Invernarder", cursor.getString(4));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
return jobj;
}
//Syncronizador de datos a servicio
public Cursor getAllDataInv() {
String selectQuery = "Select * from Invernadero";
SQLiteDatabase db = new MyHelper(getActivity()).getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Cursor cursor = db.rawQuery("select * from capturas where syncstatus= ?", new String[] {"0"});
return cursor;
}
#Override
public void onClick(View v) {
}
}
And for your adapter, added a new method called addItem that accepts a new row in the adapter and notifiy change in last item.
public class AdapterAct extends RecyclerView.Adapter<AdapterAct.MyViewHolder> implements Filterable {
private List<ActividadesModel> actividadesModelList;
private Context context;
private List<ActividadesModel> actividadesArrayList;
private IAxiliarActividades iAxiliarActividades;
List<ActividadesModel> contactList;
// Este es nuestro constructor (puede variar segĂșn lo que queremos mostrar)
private String[] mDataSet;
private List<ActividadesModel> listCont;
public AdapterAct(Context context, List<ActividadesModel> listCont) {
this.context = context;
this.contactList = listCont;
this.listCont = listCont;
}
public AdapterAct(String[] myDataSet) {
mDataSet = myDataSet;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// return null;
View v;
v = LayoutInflater.from(context).inflate(R.layout.card_actividad, parent, false);
return new MyViewHolder(v);
}
public void addItem(ActividadesModel item) {
this.listCont.add(item);
notifyItemChanged(listCont.size() - 1);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView precio;
public MyViewHolder(View itemView) {
super(itemView);
this.name = (TextView) itemView.findViewById(R.id.txtNombreMostrar);
this.precio = (TextView) itemView.findViewById(R.id.txtPrecioMostrar);
}
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
ActividadesModel actividadesModel = listCont.get(position);
//Codigo para crear el listado de acitividades
// holder.name.setText("nameprueba");
holder.precio.setText(actividadesModel.getCodigo());
holder.precio.setText(actividadesModel.getPrecio());
// holder.precio.setText("precio23");
}
#Override
public int getItemCount() {
return listCont == null ? 0 : listCont.size();
}
#Override
public Filter getFilter() {
return null;
}
}
I built an application that read contacts from a phone (in this case my phone). For the activity where contacts has been displayed, I used TabLayout along with a ViewPager. For displaying the contacts I used RecyclerView. The point is that I handle it how to read contacts and my next movement after that was to open an external activity (MessageToContact_Activity) after clicking on a contact. In present in this activity (MessageToContact_Activity) I want to send a message to the contact that I have selected and for that firstly I am trying to set the contact's name and number to the toolbar's title and subtitle. Instead of default ActionBar I've decided to use a toolbar because is more flexible. The problem is that I don't know how to get the values of name and number and use them into MessageToContact_Activity.
Here is the implementation for Contacts_Fragment:
public class Contacts_Fragment extends Fragment {
View v;
public Contacts_Fragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.contacts_fragment, container, false);
RecyclerView recyclerView = v.findViewById(R.id.recycleView_search);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager = linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
ContactsAdapter adapter = new ContactsAdapter(getContext(), getContacts());
recyclerView.setAdapter(adapter);
return v;
}
private List<ContactModel> getContacts() {
List<ContactModel> list = new ArrayList<>();
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_CONTACTS}, 1);
}
Cursor cursor = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.moveToNext()) {
list.add(new ContactModel(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
)), cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
return list;
}
}
Here is the implementation for ContactsAdapter:
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
private List<ContactModel> mListContacts;
public ContactsAdapter(Context context, List<ContactModel> listContacts){
this.mContext = context;
this.mListContacts = listContacts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.item_contact,parent, false);
final ViewHolder viewHolder = new ViewHolder(view);
viewHolder.item_contact.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Toast.makeText(mContext, "Test Click "+String.valueOf(viewHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
/*This is where I've tried to get them with setters and use them
with getters in MessageToContact_Activity*/
String name = mListContacts.get(viewHolder.getAdapterPosition()).getName();
String number = mListContacts.get(viewHolder.getAdapterPosition()).getNumber();
MessageToContact_Activity mC = new MessageToContact_Activity();
mC.setName(name);
mC.setNumber(number);
/*----------------------------------------------------------------------------*/
onContactClick(view);
}
});
return viewHolder;
}
public void onContactClick(View v){
Intent myIntent = new Intent(v.getContext(), MessageToContact_Activity.class);
mContext.startActivity(myIntent);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
TextView c_name, c_number;
c_name = holder.cV_name;
c_number = holder.cV_number;
c_name.setText(mListContacts.get(position).getName());
c_number.setText(mListContacts.get(position).getNumber());
}
#Override
public int getItemCount() {
return mListContacts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView cV_name, cV_number;
AppCompatImageButton messageButton;
private LinearLayout item_contact;
public ViewHolder(View itemView){
super(itemView);
cV_name = itemView.findViewById(R.id.name_contact);
cV_number = itemView.findViewById(R.id.phone_contact );
messageButton = itemView.findViewById(R.id.message_button);
item_contact = (LinearLayout) itemView.findViewById(R.id.contact_item_id);
}
}
}
Where you see some code between /**..*/ and /**..*/, I just tried to isolate my methods of getting the values of name and number and to use them for setting the title and subtitle from MessageToContact_Activity.
Here is the implementation for MessageToContact_Activity:
public class MessageToContact_Activity extends AppCompatActivity{
private String name, number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_to_contact);
Toolbar toolbar = findViewById(R.id.messageToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/*************************/
getSupportActionBar().setTitle(getName());
getSupportActionBar().setSubtitle(getNumber());
/*************************/
}
/*************************/
public MessageToContact_Activity(){}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
/*************************/
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
Here are the items of a contact :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Contact Name"
android:id="#+id/name_contact" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number"
android:id="#+id/phone_contact"/>
</LinearLayout>
Here is the output when I use getSupportActionBar().setTitle(getName()); and getSupportActionBar().setSubtitle(getNumber());
Here is the output when I use getSupportActionBar().setTitle("Name"); and getSupportActionBar().setSubtitle("Number");
I will be so thankful to anyone who could help me. I have a hunch that the solution is not so hard but I still don't know it. And forgive me if there are some things wrong in my code but I'm still at the beginning with android application development.
Activities are not created using new MyActivity(), instead they need to be launched using an intent, as in:
Intent i = new Intent(this, MyActivity.class);
startActivity(i);
If you need to pass to your new activity some parameters, you add them to your intent as extras, like so:
Intent i = new Intent(this, MyActivity.class);
i.putExtra("name", "Bob");
i.putExtra("number", "12345");
startActivity(i);
So in your case, you need to replace your onClick method with something like this:
#Override
public void onClick(View view) {
String name = mListContacts.get(viewHolder.getAdapterPosition()).getName();
String number = mListContacts.get(viewHolder.getAdapterPosition()).getNumber();
Intent myIntent = new Intent(v.getContext(), MessageToContact_Activity.class);
myIntent.putExtra("name", name);
myIntent.putExtra("number", number);
mContext.startActivity(myIntent);
}
Then in your MessageToContact_Activity you can access those extras via:
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
String number = extras.getString("number");
I have two activities. FirstActivity contains an onClick button which takes to SecondActivity. SecondActivity contains multiple EditText and a Save Button. After clicking save button I want to show all the data in the FirstActivity in ListView. I did it using TextView in FirstActivity but I am not able to use to ListAdapter.
public class MainActivity extends AppCompatActivity{
private ListView list_view;
List list;
private Button FloatingActionButton;
private TextView vortext;
private TextView nachtext;
private TextView strtext;
private TextView orttext;
private TextView text1;
private ArrayAdapter<String> ArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vortext = (TextView) findViewById(R.id.vortext);
nachtext = (TextView) findViewById(R.id.nachtext);
strtext = (TextView) findViewById(R.id.strtext);
orttext = (TextView) findViewById(R.id.orttext);
list = new ArrayList<String>();
vortext.setText(getIntent().getStringExtra("Vorname"));
nachtext.setText(getIntent().getStringExtra("Nachname"));
strtext.setText(getIntent().getStringExtra("Strasse"));
orttext.setText(getIntent().getStringExtra("Ort"));
list_view = (ListView) findViewById(R.id.list_view);
String [] strings = new String[] {};
ArrayAdapter<HashMap<String,String>> listItem = new ArrayAdapter<HashMap<String, String>>();
HashMap<String,String>map;
map = new HashMap<String, String>();
map.put();
listItem.add(map);
ArrayAdapter = new ArrayAdapter<String>(this,R.layout.listitem,strings);
FloatingActionButton myFab = findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(MainActivity.this, DetailActivity.class), 12);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 12) {
String vs = data.getExtras().getString("vs");
Log.d("MainActivity",vs);
String ns = data.getExtras().getString("ns");
Log.d("MainActivity",ns);
String ss = data.getExtras().getString("ss");
Log.d("MainActivity",ss);
String os = data.getExtras().getString("os");
Log.d("MainActivity",os);
}
}
}
Here this is my DetailsActivity
public class DetailActivity extends AppCompatActivity {
private EditText Vorname;
private EditText Nachname;
private EditText Strasse;
private EditText Ort;
private Button Save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Vorname = (EditText) findViewById(R.id.Vorname);
Nachname = (EditText)findViewById(R.id.Nachname);
Strasse = (EditText)findViewById(R.id.Strasse);
Ort = (EditText) findViewById(R.id.Ort);
Save = (Button) findViewById(R.id.Save);
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String vs = Vorname.getText().toString();
String ns = Nachname.getText().toString();
String ss = Strasse.getText().toString();
String os = Ort.getText().toString();
Intent intent = new Intent(getBaseContext(),MainActivity.class);
intent.putExtra("vs", vs);
intent.putExtra("ns",ns);
intent.putExtra("ss",ss);
intent.putExtra("os",os);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
Please run this sample, it may helps you
FirstActivity
public class FirstActivity extends AppCompatActivity {
private List<String> mCityList;
LinearLayoutManager mLinearLayoutManager;
RecyclerView mRecyclerView;
SampleDataAdapter adapter;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
mCityList=new ArrayList<String>();
mRecyclerView = (RecyclerView)findViewById(R.id.recycleView);
button = (Button)findViewById(R.id.buttonFirst);
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
adapter = new SampleDataAdapter(mCityList,this);
mRecyclerView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, 1);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
{
if (resultCode == Activity.RESULT_OK) {
ArrayList<String> returnValue = data.getStringArrayListExtra("LIST");
mCityList.addAll(returnValue);
adapter.notifyDataSetChanged();
}
}
}
}
list_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/buttonFirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
SecondActivity
public class SecondActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
button = (Button)findViewById(R.id.buttonSecond);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<String> list=new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("E");
list.add("G");
Intent intent = new Intent();
intent.putStringArrayListExtra("LIST",list);
setResult(RESULT_OK,intent);
finish();
}
});
}
}
second_Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/buttonSecond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:text="Second"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
SampleDataADapter
public class SampleDataAdapter extends RecyclerView.Adapter<SampleDataAdapter.Items> {
private List<String> list;
private Context context;
public SampleDataAdapter(List<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public SampleDataAdapter.Items onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_text, parent, false);
return new Items(view);
}
#Override
public void onBindViewHolder(final SampleDataAdapter.Items holder, int position) {
holder.mEventName.setText(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
public class Items extends RecyclerView.ViewHolder {
private TextView mEventName;
public Items(final View itemView) {
super(itemView);
mEventName = (TextView) itemView.findViewById(R.id.textView);
}
}
}
item_text.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="wrap_content"
android:id="#+id/constraintLayout"
tools:context="com.example.android.broadcasereceiver.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textColor="#android:color/black"
android:textStyle="bold"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/textView" />
</android.support.constraint.ConstraintLayout>
if you want to this with ListView just add in OnActivityResult
if (resultCode == Activity.RESULT_OK) {
ArrayList<String> returnValue = data.getStringArrayListExtra("LIST");
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, returnValue);
mListView.setAdapter(itemsAdapter);
}
enter code here
and remove SampleDataAdapter related code from FirstActivity and take ListView instead of RecyclerView
I found so many issues in your code. for ex- you didn't set adapter to your list, you were using two different list. So I modified your code. Please use this code. You need to take list as Global Variable, and you need to set adapter to your list view. And when you are taking your results back from second activity then add those elements in your list and call ArrayAdapter.notifyDataSetChanged();
to get new data in your listview.
public class MainActivity extends AppCompatActivity {
private ListView list_view;
List list;
private Button FloatingActionButton;
private TextView vortext;
private TextView nachtext;
private TextView strtext;
private TextView orttext;
private TextView text1;
private android.widget.ArrayAdapter<String> ArrayAdapter;
private ArrayList<String> strings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vortext = (TextView) findViewById(R.id.vortext);
nachtext = (TextView) findViewById(R.id.nachtext);
strtext = (TextView) findViewById(R.id.strtext);
orttext = (TextView) findViewById(R.id.orttext);
list = new ArrayList<String>();
vortext.setText(getIntent().getStringExtra("Vorname"));
nachtext.setText(getIntent().getStringExtra("Nachname"));
strtext.setText(getIntent().getStringExtra("Strasse"));
orttext.setText(getIntent().getStringExtra("Ort"));
list_view = (ListView) findViewById(R.id.list_view);
strings = new ArrayList<String>();
ArrayAdapter = new ArrayAdapter<String>(this, R.layout.listitem, strings);
list_view.setAdapter(ArrayAdapter);
com.google.android.material.floatingactionbutton.FloatingActionButton myFab = findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(MainActivity.this, DetailActivity.class), 12);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 12) {
String vs = data.getExtras().getString("vs");
Log.d("MainActivity", vs);
strings.add(vs);
String ns = data.getExtras().getString("ns");
Log.d("MainActivity", ns);
strings.add(ns);
String ss = data.getExtras().getString("ss");
Log.d("MainActivity", ss);
strings.add(ss);
String os = data.getExtras().getString("os");
Log.d("MainActivity", os);
strings.add(os);
ArrayAdapter.notifyDataSetChanged();
}
}
}
I'm trying to change the icon of a button in my recycler view every time the activity starts based off a boolean value in my custom object. I assume this has to be done within the adapter since not every groups button will have the same background.
Below is the code for my recycler view adapter:
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mRecipeTextSection.setOnClickListener(this);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
Toast.makeText(v.getContext(), recipeToGrocery.getRecipeName() + " added to grocery list.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View v){
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}
I know how to change the background of the button when it's clicked with
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
but it's obviously not going to save the state of that button when the activity restarts. I'm just not sure of how to check the boolean value for each group upon activity start up and change the button background accordingly.
I tried using
if(recipe.isInList()){
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
in the onBindViewHolder method but it didn't do anything, and I'm pretty sure that wouldn't be the correct place for it anyways. I know the boolean is working properly since I use it in other places and it works fine.
Here's the relevant XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/res/android"
android:layout_margin="7dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:id="#+id/recycled_item_section_view"
android:elevation="30dp"
android:background="#drawable/background_border"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Recipe name"
android:textSize="24dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_recipe_name"
android:paddingBottom="3dp"
android:maxWidth="275dip"
android:singleLine="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_below="#id/recipe_list_recycler_view_recipe_name"
android:id="#+id/recipe_list_recycler_view_serving_size"
android:paddingBottom="3dp"/>
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#mipmap/ic_playlist_add_black_24dp"
android:height="36dp"
android:padding="8dp"
android:layout_alignParentRight="true"
android:id="#+id/add_to_grocery_list"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_serving_size"
android:layout_alignParentLeft="true"
android:textSize="18dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_prep_time"
android:paddingBottom="3dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_prep_time"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:id="#+id/recipe_list_recycler_view_cook_time"/>
</RelativeLayout>
Recipe class:
public class Recipe implements Parcelable {
//These are all of the qualities a recipe contains, we will create an arraylist of this in the activity
private String mRecipeName;
private int mID;
private String mServings;
private String mPrepTime;
private String mCookTime;
private boolean isInList;
private List<String> mIngredients;
private List<String> mDirections;
public Recipe(){
}
public Recipe(int id, String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mID = id;
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public Recipe(String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public String getRecipeName() {
return mRecipeName;
}
public int getID() {
return mID;
}
public void setID(int id){
mID = id;
}
public String getServings() {
return mServings;
}
public String getPrepTime() {
return mPrepTime;
}
public void setRecipeName(String recipeName) {
mRecipeName = recipeName;
}
public void setServingSize(String servings) {
mServings = servings;
}
public void setPrepTime(String prepTime) {
mPrepTime = prepTime;
}
public void setServings(String servings) {
mServings = servings;
}
public List<String> getIngredients() {
return mIngredients;
}
public List<String> getDirections() {
return mDirections;
}
public String getCookTime() {
return mCookTime;
}
public void setCookTime(String cookTime) {
mCookTime = cookTime;
}
public void setIngredients(List<String> ingredients) {
mIngredients = ingredients;
}
public void setDirections(List<String> directions) {
mDirections = directions;
}
public boolean isInList() {
return isInList;
}
public void setInList(boolean inList) {
isInList = inList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mRecipeName);
dest.writeInt(this.mID);
dest.writeString(this.mServings);
dest.writeString(this.mPrepTime);
dest.writeString(this.mCookTime);
dest.writeByte(this.isInList ? (byte) 1 : (byte) 0);
dest.writeStringList(this.mIngredients);
dest.writeStringList(this.mDirections);
}
protected Recipe(Parcel in) {
this.mRecipeName = in.readString();
this.mID = in.readInt();
this.mServings = in.readString();
this.mPrepTime = in.readString();
this.mCookTime = in.readString();
this.isInList = in.readByte() != 0;
this.mIngredients = in.createStringArrayList();
this.mDirections = in.createStringArrayList();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel source) {
return new Recipe(source);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
}
And main activity class that uses the adapter:
public class RecipeList extends AppCompatActivity{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private int REQUEST_CODE=1;
private Button mNavigateGroceryButton;
RecipeDB dbHelper = new RecipeDB(this);
List<Recipe> recipes;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recipes = dbHelper.getAllRecipes();
setContentView(R.layout.activity_recipe_list);
mRecyclerView = (RecyclerView) findViewById(R.id.list_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
mNavigateGroceryButton = (Button) findViewById(R.id.navigate_to_groceries_button_list_view);
mNavigateGroceryButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(RecipeList.this, ExpandableListViewActivity.class);
//Log.d("Navigate", "navigate pressed" );
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
}
public boolean onOptionsItemSelected(MenuItem item){
//Handles menu buttons
switch (item.getItemId()){
case R.id.recipe_list_add_recipe_actionbar_button:
//This button creates a new empty Recipe object and passes it to the EditRecipe class
//The Recipe object is passed as a parcelable
Recipe passedRecipe = new Recipe();
Intent i = new Intent(RecipeList.this, EditRecipe.class);
i.putExtra("passed_recipe_key", (Parcelable) passedRecipe);
startActivityForResult(i, REQUEST_CODE);
return true;
default:
Log.d("Name,", "default called");
return super.onOptionsItemSelected(item);
}
}
public void addNewReRecipe(Recipe recipe){
dbHelper.addRecipe(recipe);
recipes = dbHelper.getAllRecipes();
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
}
//Makes the menu bar appear as it is in the action_bar_recipe_list_buttons menu layout file
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_recipe_list_buttons, menu);
return true;
}
//This code is called after creating a new recipe. This is only for creating, and not editing.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE){
if(resultCode == Activity.RESULT_OK) {
Recipe createdRecipe = data.getExtras().getParcelable("recipe_key");
addNewReRecipe(createdRecipe);
}
}
}
}
Looks like you need to declare your button at the top of your ViewHolder with your other views. So move the declaration from the top of your adapter:
private Button mAddToGroceriesButton;
Then in your onBindViewHolder method you can get a reference to your button through the holder and set the background:
if(recipe.isInList()) {
holder.mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
Try this,
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
mRecipeTextSection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
});
Recipe recipeToGrocery = mRecipeSet.get(position);
if(!recipeToGrocery.isInList()) {
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
else{
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_26dp);//set another image
}
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
notifyDataSetChanged();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}
I am trying to build a simple chat application. With chat conversation screen I'm using ListView with ArrayAdapter to store and show the message but when I receive or send new message, all of recent message is change to.
This is my adapter code:
public class MessageAdapter extends ArrayAdapter<Message> {
private Context context;
private ArrayList<Message> messages;
private DatabaseHelper databaseHelper;
private Message message;
#Override
public void add(Message object) {
messages.add(object);
super.add(object);
}
public MessageAdapter(Context context, int textViewResouceId, ArrayList<Message> messages) {
super(context, textViewResouceId);
this.context = context;
this.messages = messages;
databaseHelper = DatabaseHelper.getInstance(context);
}
public int getCount() {
return messages.size();
}
public Message getItem(int index) {
return messages.get(index);
}
public long getItemId(int position) {
return position;
}
#Override
public int getPosition(Message item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MessageViewHolder messageViewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.chat_item, parent, false);
messageViewHolder = new MessageViewHolder();
messageViewHolder.tv_userName = (TextView) convertView.findViewById(R.id.tv_chatName);
messageViewHolder.tv_message = (TextView) convertView.findViewById(R.id.tv_messageContent);
convertView.setTag(messageViewHolder);
} else {
messageViewHolder = (MessageViewHolder) convertView.getTag();
}
message = messages.get(position);
String username = databaseHelper.getUserByUserId(message.getUserId()).getUserName();
if (message.getUserId() == AppConfig.USER_ID) {
messageViewHolder.tv_message.setTextColor(Color.parseColor("#0066ff"));
messageViewHolder.tv_userName.setTextColor(Color.parseColor("#0066ff"));
} else {
messageViewHolder.tv_message.setTextColor(Color.parseColor("#000000"));
messageViewHolder.tv_userName.setTextColor(Color.parseColor("#000000"));
}
messageViewHolder.tv_userName.setText(username);
messageViewHolder.tv_message.setText(message.getMessage());
return convertView;
}
static class MessageViewHolder {
TextView tv_message;
TextView tv_userName;
}
}
This is my ListView Layout code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ScrollView
android:id="#+id/scroll_chat"
android:layout_width="match_parent"
android:layout_height="380dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:background="#null"
android:divider="#null"
android:stackFromBottom="true"
android:drawSelectorOnTop="false"
android:transcriptMode="alwaysScroll" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.92" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
And this is error when I send two message (the same error happen when I receive a message)
I think the problem is the way set the data to View but I cannot solve it.
Could anyone help me solve this issue.
This is chat screen when I close and open the activity again: It showed correct message.
This is Chatactivity code:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_send;
private static EditText txt_chat;
private String registId;
private Bundle bundle;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private ListView lv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
lv_message = (ListView) findViewById(R.id.listMessage);
// lv_message.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getMessges(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId());
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = Message.getInstance();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = Message.getInstance();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
}
In your ChatActivity. In onClickEvent
Try to change
Message messageObj = Message.getInstance();
to
Message messageObj = new Message();
You can read more about Singleton Pattern in here