RecyclerView, each items has its own activity - android

I have a RecyclerView, it has items in it. I need each item to have its own Activity, that is, we have item1 by clicking on it, Activity1 opens, there is also item2 about clicking on it, Activity2 is opened. Can this be done somehow? If so, how? I managed to make it so that when I clicked, the same Fragment opened, and the text changes depending on which item was clicked. But it doesn't quite suit me.
Fragment where the RecyclerView is located
public class FragmentAttractionRecyclerView extends Fragment {
private RecyclerView mRec;
private AttractionsAdapter adapter;
private ArrayList<AttractionsItem> exampleList;
private RecyclerView.LayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_attraction_test_2, container, false);
}
#SuppressLint("InflateParams")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
createExampleList();
buildRecyclerView();
}
public void createExampleList() {
exampleList = new ArrayList<>();
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Baby островок", "Детский", "60₽","Максимальное кол-во детей","10","Возраст","С 1-го до 6 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Виражи", "Детский", "80₽","Максимальное кол-во пассажиров","24", "Возраст","От 4-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Вокруг света", "Детский", "50₽","Максимальное кол-во пассажиров","12","Возраст","От 3-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_interactive, "5D кинотеатр", "Интерактивный", "120₽","Максимальное кол-во пассажиров","","Возраст","С 6 лет"));
}
public void buildRecyclerView() {
mRec = requireView().findViewById(R.id.attraction_recycler);
adapter = new AttractionsAdapter(exampleList);
mLayoutManager = new LinearLayoutManager(getContext());
mRec.setLayoutManager(mLayoutManager);
mRec.setAdapter(adapter);
}
}
Adapter for RecyclerView
public class AttractionsAdapter extends RecyclerView.Adapter<AttractionsAdapter.AttractionsViewHolder> {
public ArrayList<AttractionsItem> mFavList;
public AttractionsAdapter(ArrayList<AttractionsItem> favList) {
mFavList = favList;
}
#NonNull
#Override
public AttractionsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_attraction, parent, false);
AttractionsViewHolder evh = new AttractionsViewHolder(v);
return evh;
}
public static class AttractionsViewHolder extends RecyclerView.ViewHolder {
public ImageView card_image_1, card_image_2;
public TextView card_text_1, card_text_2, card_text_3,attraction_menu_1_1,attraction_menu_1_2;
public CardView Card;
public AttractionsViewHolder(View itemView) {
super(itemView);
card_image_1 = itemView.findViewById(R.id.card_image_1);
card_image_2 = itemView.findViewById(R.id.card_image_2);
card_text_1 = itemView.findViewById(R.id.card_text_1);
card_text_2 = itemView.findViewById(R.id.card_text_2);
card_text_3 = itemView.findViewById(R.id.card_text_3);
attraction_menu_1_1 = itemView.findViewById(R.id.attraction_menu_1_1);
attraction_menu_1_2 = itemView.findViewById(R.id.attraction_menu_1_2);
Card = itemView.findViewById(R.id.Card);
}
}
#Override
public void onBindViewHolder(AttractionsViewHolder holder, int position) {
AttractionsItem currentItem = mFavList.get(position);
holder.card_image_1.setImageResource(currentItem.getImg1());
holder.card_image_2.setImageResource(currentItem.getImg2());
holder.card_text_1.setText(currentItem.get_attraction_name());
holder.card_text_2.setText(currentItem.get_attraction_type());
holder.card_text_3.setText(currentItem.get_attraction_cost());
holder.Card.setOnClickListener(v -> {
FragmentBlancAttraction fragment = new FragmentBlancAttraction(); // you fragment
FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
Bundle bundle = new Bundle();
bundle.putString("name", currentItem.get_attraction_name());
bundle.putString("menu_1_1", currentItem.get_attraction_menu_1_1());
bundle.putString("menu_1_2", currentItem.get_attraction_menu_1_2());
bundle.putString("menu_2_1", currentItem.get_attraction_menu_2_1());
bundle.putString("menu_2_2", currentItem.get_attraction_menu_2_2());
fragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.nav_default_enter_anim, R.animator.nav_default_exit_anim,
R.animator.nav_default_pop_enter_anim, R.animator.nav_default_pop_exit_anim);
fragmentTransaction.replace(R.id.fragment, fragment);// your container and your fragment
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
});
}
#Override
public int getItemCount() {
return mFavList.size();
}
}
public class AttractionsItem
{
private int mImg_1,mImg_2;
private final String mText_attraction_name;
private final String mText_attraction_type;
private final String mText_attraction_cost;
private final String mText_attraction_menu_1_1;
private final String mText_attraction_menu_1_2;
private final String mText_attraction_menu_2_1;
private final String mText_attraction_menu_2_2;
public AttractionsItem(int img1,int img2, String text_attraction_name, String text_attraction_type, String text_attraction_cost, String text_attraction_menu_1_1, String text_attraction_menu_1_2, String text_attraction_menu_2_1, String text_attraction_menu_2_2)
{
mImg_1 = img1;
mImg_2 = img2;
mText_attraction_name = text_attraction_name;
mText_attraction_type = text_attraction_type;
mText_attraction_cost = text_attraction_cost;
mText_attraction_menu_1_1 = text_attraction_menu_1_1;
mText_attraction_menu_1_2 = text_attraction_menu_1_2;
mText_attraction_menu_2_1 = text_attraction_menu_2_1;
mText_attraction_menu_2_2 = text_attraction_menu_2_2;
}
public int getImg1()
{
return mImg_1;
}
public int getImg2()
{
return mImg_2;
}
public String get_attraction_name()
{
return mText_attraction_name;
}
public String get_attraction_type()
{
return mText_attraction_type;
}
public String get_attraction_cost()
{
return mText_attraction_cost;
}
public String get_attraction_menu_1_1()
{
return mText_attraction_menu_1_1;
}
public String get_attraction_menu_1_2()
{
return mText_attraction_menu_1_2;
}
public String get_attraction_menu_2_1()
{
return mText_attraction_menu_2_1;
}
public String get_attraction_menu_2_2()
{
return mText_attraction_menu_2_2;
}
}

The positon param inside onBindViewHolder() method tells you which item of your RecyclerView clicked.
Use this to control your program and in out of onBindViewHolder() method you can get your item position by getAdapterPosition().
holder.Card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: {
// Start first activity.
break;
}
case 1: {
// Start Second activity.
break;
}
}
}
});

Related

RecyclerView cardview from dialogfragment in fragment page

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;
}
}

Dynamic Tabs with dynamic data in viewpager fragment

I need a help. I am developing dynamic tabs with dynamic data in viewpager fragment's list. Somehow i got the dynamic tabs and hit API in placeholder fragment to get the recyclerview list.
there are two issue. 1. design is overlapping the tabs and 2. its loading 3rd id data first.
here is the code.
here is main class
public class NewsFeed extends Fragment {
private static RecyclerView listView;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private RecyclerView recyclerView;
private ApiInterface apiInterface;
private List<BlogCatData> list = new ArrayList<BlogCatData>();
private BlogCatListAdaptor adapter;
private String item;
private ArrayList<BlogCatData> dataModelList = new ArrayList<BlogCatData>();
private ArrayList<String> CatTitleList = new ArrayList<>();
private static ArrayList<String> CatIdList = new ArrayList<>();
private View view1;
private View v;
// private ArrayAdapter<BlogCatData> adapter;
public NewsFeed() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_news_feed, container, false);
getAllBlogCat();
return v;
}
private void setViewIDs() {
tabLayout = v.findViewById(R.id.tabs);
viewPager = v.findViewById(R.id.container);
setUpViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
private void getAllBlogCat() {
// avi.show();
apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogCatModel> call = apiInterface.GETBlogCategory();
call.enqueue(new Callback<BlogCatModel>() {
#Override
public void onResponse(Call<BlogCatModel> call, retrofit2.Response<BlogCatModel> response) {
if (response.isSuccessful()) {
CatIdList.clear();
list = response.body().getDATA();
for (int i = 0; i < list.size(); i++) {
CatTitleList.add(list.get(i).getTITLE());
CatIdList.add(list.get(i).getID());
}
Log.v("CatTitle", CatTitleList.toString());
Log.v("CatId", CatIdList.toString());
setViewIDs();
// adapter.setPostList(list)
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogCatModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
for (int i = 0; i < CatTitleList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("id", CatIdList.get(i));
PlaceholderFragment categoryList = new PlaceholderFragment();
categoryList.setArguments(bundle);
sectionsPagerAdapter.addFragment(categoryList, CatTitleList.get(i));
}
sectionsPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(sectionsPagerAdapter);
}
public static class PlaceholderFragment extends Fragment {
private final static String TAG = PlaceholderFragment.class.getSimpleName();
private static String item;
private static ArrayList<String> dataModelList = new ArrayList<String>();
// private ArrayAdapter<Model> adapter;
private RecyclerView listView;
private List<BlogData> dataList = new ArrayList<>();
private BlogListAdaptor blogListAdaptor;
private static String id;
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
id = CatIdList.get(sectionNumber);
Bundle args = new Bundle();
args.putString("ID", id);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment__newsfeed_placeholder, container, false);
listView = view.findViewById(R.id.recycler_view);
getBlog(Id);
setBlog();
return view;
}
private void getBlog(String id) {
ApiInterface apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogModel> call = apiInterface.getNewsByCategory(id);
call.enqueue(new Callback<BlogModel>() {
#Override
public void onResponse(Call<BlogModel> call, retrofit2.Response<BlogModel> response) {
if (response.isSuccessful()) {
dataList = response.body().getDATA();
blogListAdaptor.setPostList(dataList);
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setBlog() {
blogListAdaptor = new BlogListAdaptor(getActivity(), dataList);
listView.setAdapter(blogListAdaptor);
listView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(linearLayoutManager);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 0);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getCount() {
return mFragmentTitleList.size();
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
}
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}
and here is the adapter class for recyclerview
public class BlogListAdaptor extends RecyclerView.Adapter<BlogListAdaptor.MyViewHlder> {
private Activity activity;
private List<BlogData> list;
private boolean valid;
private EditText name, email, phone, date, noOfGuest, msg;
private Spinner partyMode, timeSlot;
private AlertDialog alertDialog;
final Calendar myCalendar = Calendar.getInstance();
private String PartyModeStr, TimeSlotStr;
private String Id;
private String title;
public BlogListAdaptor(Activity activity, List<BlogData> list) {
this.activity = activity;
this.list = list;
}
public void setPostList(List<BlogData> dataList) {
list = dataList;
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.blog_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
myViewHlder.Title.setText(list.get(i).getTITLE());
myViewHlder.Author.setText(list.get(i).getAUTHOR());
if (list.get(i).getIMGSRC() != null)
Glide.with(activity).load(Constant.ImgRoot + list.get(i).getIMGSRC())
.into(myViewHlder.Image);
myViewHlder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, DetailActivity.class);
intent.putExtra("Id", list.get(i).getID());
intent.putExtra("Title", list.get(i).getTITLE());
intent.putExtra("Author", list.get(i).getAUTHOR());
intent.putExtra("Content", list.get(i).getCONTENT());
activity.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView Title, Author;
private ImageView Image;
private CardView cardview;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
Image = itemView.findViewById(R.id.image);
Title = itemView.findViewById(R.id.title);
Author = itemView.findViewById(R.id.author);
cardview = itemView.findViewById(R.id.cardview);
}
}
}
Please help me out, to call api...
fragment_newsfeed_placeholder
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
fragment_news_feed
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="center"
app:tabMode="scrollable"
app:tabTextColor="#ffffff" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tabs" />

RecyclerView not restored on orientation change

I am trying to make my app handle orientation changes. Right now I am working with a RecyclerView that has an CustomAdapter to handle the data. I have implemented onSaveInstanceState to save the data that is in the Adapter, but when I re-insert it after orientation change, the method onBindViewHolder is not called. I have confirmed the data is saved and the array lists are not empty and contain the data I need.
Here is the CustomAdapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private static final String TAG = "CustomAdapter";
private ArrayList<Words> mDataSet;
private RecyclerView mRecyclerView;
private PopupWindow mPopupWindow;
private int currentPos;
private String srcOld;
private String targetOld;
private TranslateActivityFragment mFragment;
private EditText mEditSrc;
private EditText mEditTarget;
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private TextView textView2;
private TextView textView3;
public ViewHolder(View v){
super(v);
textView = v.findViewById(R.id.adapter_textview1);
textView2 = v.findViewById(R.id.adapter_textview2);
textView3 = v.findViewById(R.id.adapter_textview3);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
mPopupWindow.showAtLocation(mRecyclerView, Gravity.CENTER,0,0);
mPopupWindow.setFocusable(true);
mPopupWindow.update();
currentPos = getAdapterPosition();
setCurrText();
}
private void setCurrText(){
Words tmp = mDataSet.get(currentPos);
srcOld = tmp.getW1();
targetOld = tmp.getW2();
mEditSrc.setText(srcOld);
mEditTarget.setText(targetOld);
}
});
}
public TextView getLeftTextView(){
return textView;
}
public TextView getCenterTextView(){return textView2;}
public TextView getRightTextView(){return textView3;}
}
public CustomAdapter(RecyclerView recyclerView, Context context, TranslateActivityFragment fragment){
mRecyclerView = recyclerView;
mDataSet = new ArrayList<Words>();
mFragment = fragment;
this.notifyDataSetChanged();
View v = LayoutInflater.from(mFragment.getActivity()).inflate(R.layout.edit_translate,null,false);
createPopupWindow(v, mFragment.getActivity());
setEditText(v);
}
private void setEditText(View v){
mEditSrc = v.findViewById(R.id.edit_src);
mEditTarget = v.findViewById(R.id.edit_target);
}
private void createPopupWindow(View v, Activity activity){
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
float width = 300*metrics.density;
float height = 200*metrics.density;
mPopupWindow = new PopupWindow(v,(int)width, (int)height);
Button buttonOk = v.findViewById(R.id.button_ok);
Button buttonCancel = v.findViewById(R.id.button_cancel);
Button buttonDelete = v.findViewById(R.id.button_delete);
buttonCancel.setOnClickListener(new CancelListener());
buttonOk.setOnClickListener(new OkListener());
buttonDelete.setOnClickListener(new DeleteListener());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType){
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.textview_layout, viewGroup,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position){
Log.d(TAG, "Element " + position + " set." + mDataSet.get(position).getW1());
viewHolder.getLeftTextView().setText(mDataSet.get(position).getW1());
viewHolder.getCenterTextView().setText(" - ");
viewHolder.getRightTextView().setText( mDataSet.get(position).getW2());
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public void addData(Words newData, RecyclerView recyclerView){
mDataSet.add(newData);
System.out.println("------ ADDING DATA--------");
this.notifyDataSetChanged();
if (mDataSet.size() > 0) {
recyclerView.smoothScrollToPosition(mDataSet.size() - 1);
}
}
public void dismissPopup(){
mPopupWindow.dismiss();
}
public void removeWord(){
mDataSet.remove(currentPos);
System.out.println("mDataSet.size(): " + mDataSet.size());
System.out.println("mFragment.getTranslater.getData.size(): " + mFragment.getTranslater().getWords().size());
mFragment.getTranslater().deleteWord(currentPos);
this.notifyDataSetChanged();
}
// Update the current word from EditTexts
public void updateWord(){
String src = mEditSrc.getText().toString();
String target = mEditTarget.getText().toString();
mDataSet.get(currentPos).setW1(src);
mDataSet.get(currentPos).setW2(target);
mFragment.getTranslater().updateWord(src, target, currentPos);
this.notifyDataSetChanged();
}
private class OkListener implements View.OnClickListener {
#Override
public void onClick(View view) {
updateWord();
dismissPopup();
}
}
private class CancelListener implements View.OnClickListener{
#Override
public void onClick(View view){
dismissPopup();
}
}
private class DeleteListener implements View.OnClickListener{
#Override
public void onClick(View view){
removeWord();
dismissPopup();
}
}
public ArrayList<Words> getWords(){
return mDataSet;
}
public ArrayList<String> getW1List() {
ArrayList<String> tmp = new ArrayList<>();
for (Words w : mDataSet){
tmp.add(w.getW1());
}
return tmp;
}
public ArrayList<String> getW2List(){
ArrayList<String> tmp = new ArrayList<>();
for (Words w : mDataSet){
tmp.add(w.getW2());
}
return tmp;
}
//
// Here is where I try to restore data.
//
public void restoreWords(ArrayList<String> w1, ArrayList<String> w2, RecyclerView recyclerView){
if (mDataSet == null){
mDataSet = new ArrayList<>();
}
System.out.println("Restoring words");
for (int i = 0; i < w1.size(); ++i){
Words tmp = new Words(w1.get(i), w2.get(i), 0,0,0,false);
addData(tmp, recyclerView);
}
}
}
Code in Fragment to handle the view:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new CustomAdapter(mRecyclerView, this.getContext(), this);
mRecyclerView.setAdapter(mAdapter);
if (savedInstanceState != null){
ArrayList<String> w1 = savedInstanceState.getStringArrayList(TranslateActivity.W1LIST);
ArrayList<String> w2 = savedInstanceState.getStringArrayList(W2LIST);
restoreWords(w1,w2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_translate, container, false);
mRecyclerView = root.findViewById(R.id.translate_recycle);
mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
return root;
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
mHelper = new Helper();
if (savedInstanceState == null) {
Intent intent = getActivity().getIntent();
source_lang = intent.getStringExtra(MainActivityFragment.SOURCE_LANG);
target_lang = intent.getStringExtra(MainActivityFragment.TARGET_LANG);
} else {
source_lang = savedInstanceState.getString(MainActivityFragment.SOURCE_LANG);
target_lang = savedInstanceState.getString(MainActivityFragment.TARGET_LANG);
}
key = mHelper.getKey(source_lang, target_lang);
mTranslater = new Translater(source_lang, target_lang, key);
setHasOptionsMenu(true);
setToolbarText();
}
public void restoreWords(ArrayList<String> w1, ArrayList<String> w2){
System.out.println("..................RESTORE WORDS....................");
mAdapter.restoreWords(w1, w2, mRecyclerView);
}
onCreate in Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
helper = new Helper();
mInAppPurchase = new InAppPurchase(this, this);
mInAppPurchase.setUpNoQuery();
setContentView(R.layout.activity_translate);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mFragment = new TranslateActivityFragment();
View v = LayoutInflater.from(getApplicationContext()).inflate(R.layout.start_purchase_ui, null, false);
createPopup(v, this);
getSupportFragmentManager().beginTransaction().replace(R.id.translate_layout, mFragment).commit();
}
I have looked around and seen some suggestions to change getItemCount to not return 0. That did not help and I do not really see how that can be the problem. Here it says for ListViews one must do the restoration in either onCreateView or onActivityCreated, that did not help either.
Note that notifyDataSetChangedis called in addData(Words word)
EDIT: I have changed the flow to the following:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_translate, container, false);
mRecyclerView = root.findViewById(R.id.translate_recycle);
mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CustomAdapter(mRecyclerView, this.getContext(), this);
mRecyclerView.setAdapter(mAdapter);
return root;
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
mHelper = new Helper();
if (savedInstanceState == null) {
// Create helper instance
// Get the input view from which we get the source word
textInput = v.findViewById(R.id.source_input);
// Extract the chosen langauges
Intent intent = getActivity().getIntent();
source_lang = intent.getStringExtra(MainActivityFragment.SOURCE_LANG);
target_lang = intent.getStringExtra(MainActivityFragment.TARGET_LANG);
} else {
source_lang = savedInstanceState.getString(MainActivityFragment.SOURCE_LANG);
target_lang = savedInstanceState.getString(MainActivityFragment.TARGET_LANG);
ArrayList<String> w1 = savedInstanceState.getStringArrayList(TranslateActivity.W1LIST);
ArrayList<String> w2 = savedInstanceState.getStringArrayList(W2LIST);
restoreWords(w1,w2);
}
key = mHelper.getKey(source_lang, target_lang);
mTranslater = new Translater(source_lang, target_lang, key);
setHasOptionsMenu(true);
setToolbarText();
}
More Information:
I have an EditText item from which I read the input and add to the mAdapter. After rotation, that does still work. It is only when I try to re-insert the saved data it doesn't work. So I suspect restoreWords are called from the wrong method?
So it seems like the solution was to do the restoration in the Activity instead of the Fragment. I did almost the same exactly as in my question. I overwrote onRestoreInstanceState and called restoreWords implemented as
public void restoreWords(ArrayList<String> w1, ArrayList<String> w2){
System.out.println("..................RESTORE WORDS....................");
for (int i = 0; i < w1.size(); ++i){
Words tmp = new Words(w1.get(i), w2.get(i), 0, 0, 0, false);
System.out.println(tmp.getW1() + " --- " + tmp.getW2());
mFragment.addWordToView(tmp);
}
System.out.println("-------------------Number of words in adapter: " + mFragment.getAdapter().getItemCount());
}
Then it magically worked. Can someone explain why?

ViewPager returns wrong Object

The pager returns the 1st object in the array list, and keeps returning the 1st object even if i swing left and right, did a lot of debugging, and for some reason when the pager get's to getItem(int position) it start's going crazy, it FINDS the corresponding object , then looks a the previous object(pos-1) then does some other weird things and returns the 1st obj in arrayList.
This method is called within the ViewHolder of RecyclerViewAdapter
#Override
public void onClick(View v) {
Intent i = ProductPageActivity.newIntent(v.getContext(),mProduct.getId());
v.getContext().startActivity(i);
}
}
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private static final String ARGUMENT_PROD_ID = "prod_id";
private TextView mTitle,mDesc,mImgUrl,mPrice;
private List<Product> mProducts;
private Product product;
public static Fragment newInstance(UUID productID) {
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_PROD_ID,productID);
ProductFragment frag = new ProductFragment();
frag.setArguments(args);
return frag;
}
public ProductFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
UUID id = (UUID) getArguments().getSerializable(ARGUMENT_PROD_ID);
product = ProductHolder.get(getContext()).getProduct(id);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_fragment,container,false);
setWidgets(v);
setDataOnText();
return v;
}
private void setDataOnText(){
mTitle.setText(product.getTitle());
mDesc.setText(product.getDesc());
mPrice.setText(product.getPrice());
}
private void setWidgets(View v) {
mTitle = (TextView) v.findViewById(R.id.title);
mDesc = (TextView) v.findViewById(R.id.desc);
mPrice = (TextView) v.findViewById(R.id.price);
}
}
public class ProductPageActivity extends AppCompatActivity {
private static final String PRODUCT_ID = "com.example.cmd.testproject.Activitys.ProductPageActivity.product_id";
private UUID productId;
private ViewPager mPager;
private List<Product> mProducts;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_page_activity);
productId = (UUID) getIntent().getSerializableExtra(PRODUCT_ID);
mPager = (ViewPager) findViewById(R.id.viewPager);
mProducts = ProductHolder.get(this).getProducts();
FragmentManager fragmentManager = getSupportFragmentManager();
mPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Product pr = mProducts.get(position);
return ProductFragment.newInstance(pr.getId());
}
#Override
public int getCount() {
return mProducts.size();
}
});
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(productId)) {
mPager.setCurrentItem(i);
break;
}
}
}
public static Intent newIntent(Context packageContext, UUID productID) {
Intent intent = new Intent(packageContext, ProductPageActivity.class);
intent.putExtra(PRODUCT_ID, productID);
return intent;
}
}
public class ProductHolder {
private static final String TAG = "ProductHolder";
private static ProductHolder sProductHolder;
private List<Product> mProducts;
public static ProductHolder get(Context ctx) {
if(sProductHolder == null) {
sProductHolder = new ProductHolder(ctx);
}
return sProductHolder;
}
private ProductHolder(Context ctx) {
mProducts = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Product product = new Product("Product = " + i, "Desc = "
+ i, "ImgUrl = " + i, "Price = " + i + 2.2);
mProducts.add(product);
}
}
public Product getProduct(UUID prodId) {
for (Product pr:mProducts) {
if(pr.getId().equals(prodId));
return pr;
}
return null;
}
public List<Product> getProducts() {
return mProducts;
}
}

How to put values from a textview in a row of a listview to a fragment

Working on android app' and I want to pass value from my textview that is in a row of a listview and put it in a fragment. I hear about convertView.gettag and settag method put I don't know how to deal with.
My code:
public class EvaluationsFragment extends CustomFragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private Patient mPatient;
private View myView;
private Context context;
private Button btnAjoutEvaluation;
private ListView evaluations_historic_liste;
private List<Evaluation>mEvaluation;
private EvaluationDto mEvaluationDto;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
myView = inflater.inflate(R.layout.fragment_evaluations, container,false);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
init();
}
private void init(){
evaluations_historic_liste = (ListView)myView.findViewById(R.id.evaluations_historic_liste);
btnAjoutEvaluation = (Button)myView.findViewById(R.id.evaluations_add__btn);
btnAjoutEvaluation.setOnClickListener(this);
TypeEvaluation mNouveauTypeEvaluation;
mPatient =((DossierActivity)mRootActivity).mPatient;
mEvaluationDto = new EvaluationDto(mRootActivity.getApplicationContext());
evaluations_historic_liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EvaluationAdapter.EvaluationItem item = (EvaluationAdapter.EvaluationItem)view.getTag();
openDetailEvaluation(item);
}
});
mEvaluationDto.open();
try{
mEvaluation = mEvaluationDto.getEvaluationsByPatientId(mPatient.getId());
}catch (SQLException e) {
Log.e(Constants.APP_LOG_TAG, e.getMessage());
ACRA.getErrorReporter().handleException(e);
} finally{
mEvaluationDto.close();
}
if(mEvaluation != null && mEvaluation.size() >0){
evaluations_historic_liste.setAdapter(new EvaluationAdapter(mRootActivity,mEvaluation));
}else {
evaluations_historic_liste.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case (R.id.evaluations_add__btn):
openNewEvaluation();
break;
}
}
public void openNewEvaluation(){
Fragment fragment = new EvaluationNouvelleFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new EvaluationNouvelleFragment());
fragmentTransaction.commit();
}
public void openDetailEvaluation(EvaluationAdapter.EvaluationItem item){
EvaluationAdapter evaluationAdapter = new EvaluationAdapter();
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle args = new Bundle();
args.putString(EvaluationDetailHistoriqueFragment.DATA_RECEIVE, /*HERE I NEED TO PUT item_evaluation_nom.setText()*/ );
detail.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.content_frame, detail).commit();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class EvaluationAdapter extends BaseAdapter {
private Context mcontext;
private List<EvaluationItem> mItems = new ArrayList<EvaluationItem>();
public EvaluationAdapter(){}
public EvaluationAdapter(Context context, List<Evaluation> values) {
this.mcontext = context;
for (Evaluation e : values) {
mItems.add(new EvaluationItem(e));
}
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public EvaluationItem getItem(int position) {
return mItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
EvaluationItemHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mcontext).inflate(R.layout.list_items_historic_evaluations, parent, false);
holder = new EvaluationItemHolder();
holder.item_evaluation_date = (TextView) convertView.findViewById(R.id.item_evaluation_date);
holder.item_evaluation_nom = (TextView) convertView.findViewById(R.id.item_evaluation_nom);
holder.item_evaluation_personnel = (TextView) convertView.findViewById(R.id.item_evaluation_personnel);
holder.item_evaluation_score = (TextView) convertView.findViewById(R.id.item_evaluation_score);
holder.item_evaluation_date_reevaluation = (TextView) convertView.findViewById(R.id.item_evaluation_date_reevaluation);
convertView.setTag(holder);
}else{
holder = (EvaluationItemHolder)convertView.getTag();
}
final EvaluationItem item = getItem(position);
int score = (item.getScoreTV()).intValue();
holder.item_evaluation_date.setText( + " " + item.getDateTV());
holder.item_evaluation_nom.setText(item.getTypeEvalTV());
if (item.getPersonnelTV() != null) {
holder.item_evaluation_personnel.setText( + " " + item.getPersonnelTV());
}
holder.item_evaluation_score.setText( + String.valueOf(score));
if (item.getDateReevalTV() != null) {
holder.item_evaluation_date_reevaluation.setText( item.getDateReevalTV());
}
// convertView.setTag(1,item.getTypeEvalTV());
return convertView;
}
public class EvaluationItem {
private String dateTV;
private String typeEvalTV;
private String personnelTV;
private Double scoreTV;
private String dateReevalTV;
public String getDateTV() {return dateTV;}
public void setDateTV(String dateTV) {
this.dateTV = dateTV;
}
public String getTypeEvalTV() {
return typeEvalTV;
}
public void setTypeEvalTV(String typeEvalTV) {
this.typeEvalTV = typeEvalTV;
}
public String getPersonnelTV() {
return personnelTV;
}
public void setPersonnelTV(String personnelTV) {
this.personnelTV = personnelTV;
}
public Double getScoreTV() {
return scoreTV;
}
public void setScoreTV(Double scoreTV) {
this.scoreTV = scoreTV;
}
public String getDateReevalTV() {
return dateReevalTV;
}
public void setDateReevalTV(String dateReevalTV) {
this.dateReevalTV = dateReevalTV;
}
public EvaluationItem(Evaluation e){
this.dateTV = e.getDate();
this.typeEvalTV = e.getTypeEvaluation().getLibelle();
this.personnelTV = e.getPersonnelLibelle();
this.scoreTV = e.getScore();
this.dateReevalTV = e.getDateReevaluation();
}
}
}
public static class EvaluationItemHolder{
public TextView item_evaluation_date;
public TextView item_evaluation_nom;
public TextView item_evaluation_personnel;
public TextView item_evaluation_score;
public TextView item_evaluation_date_reevaluation;
}
}
You were doing good, you need a Bundle to do this.
First of all create a String where you can keep the value of
holder.item_evaluation_nom.getText();
Then for example you do this :
String itemEvaluation = holder.item_evaluation_nom.getText();
This is the correct Bundle
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle bundle = new Bundle();
bundle.putString("text", itemEvaluation);
detail.setArguments(bundle);
Then to retrieve this you do this :
Bundle bundle = this.getArguments();
if (bundle != null) {
String itemEvaluation = bundle.getString("text", "");
}
hope it helps.
EDIT
You'll need to add an Adapter to your evaluations_historic_liste list.
You can do this doing :
evaluations_historic_liste.setAdapter(new EvaluationAdapter(getActivity(),mEvaluation));
mEvaluation is the List that you have to put data on it.
Then in your ListView add this :
evaluation_historic_liste.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id){
String itemEvaluation = (String) ((TextView)view.findViewById(R.id.item_evaluation_nom)).getText();
//or
String itemEvaluation=(evaluation_historic_liste.getItemAtPosition(position).toString());
}
}

Categories

Resources