Why does Input from an AlertDialog not show in RecyclerView? - java

I want to take input from an AlertDialog box and set it to 2 variables then use those variables as an argument to make a list using recyclerview.
With the code in its this state it brings up the dialogbox and when i enter information and press "add" nothing shows onto the screen.
Here is my Java file:
public class tab1Expenses extends Fragment {
List<ExRow> expenseList = new ArrayList<>();
RecyclerView recyclerView;
ExpensesAdapter mAdapter;
Button btnEx;
EditText txtExName;
EditText txtExAmount;
public void expenseData() {
ExRow exs = new ExRow(txtExNa, txtExAm);
expenseList.add(exs);
mAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button) rootView.findViewById(R.id.btnEx);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mAdapter = new ExpensesAdapter(expenseList);
RecyclerView.LayoutManager mLayoutManager = new RecyclerView.LayoutManager() {
#Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return null;
}
};
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setCancelable(true)
.setTitle("Enter Expense:")
.setView(view)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
expenseData();
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
}
Here is the related XML file:
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:width="800dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
</ScrollView>
And the XML file for adding inputs:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/exName"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:editable="false"
android:hint="Expense Name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/exAmount"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:hint="Expense Amount" />
</LinearLayout>

You need to get the reference for txtExName and txtExAmount from view not rootview. So from your latest code remove these lines
txtExName = (EditText) rootView.findViewById(R.id.exName);
txtExAmount = (EditText) rootView.findViewById(R.id.exAmount);
and add these lines on same spot.
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);

OK, so as I can see the issue is due to it not being able to find EditText named txtExName, and txtExAmount. So,
cut these two lines:
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
txtExName = (EditText) rootView.findViewById(R.id.exName); //<---This one
txtExAmount = (EditText) rootView.findViewById(R.id.exAmount); // <--And this one
and replace them with these:
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
Hope it helps.

where are yours EditTexts in you XML file posted?
Probably it's return null because it's not finding any EditText:
String txtExNa = (txtExAmount.getText()).toString(); //here is crash, i think
Sorry my english and I hope this help!

OK so this may be final answer. I will try to cover up everything you are trying to do.
//This is tab1expense.xml (Without toolbar)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
//This is add_ex.xml (Used in popup)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/exName"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:editable="false"
android:hint="Expense Name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/exAmount"
android:textColorLink="#android:color/holo_green_light"
android:textColorHighlight="#android:color/holo_green_light"
android:hint="Expense Amount" />
</LinearLayout>
//Now a Class called ExRow.java
public class ExRow{
String str_txtExNa,str_txtExAm;
ExRow(String str_txtExNa, String str_txtExAm){
this.str_txtExNa=str_txtExNa;
this.str_txtExAm=str_txtExAm;
}
public String getNa()
{
return str_txtExNa;
}
public String getAm()
{
return str_txtExAm;
}
}
//Now your tab1Expenses.java
public class tab1Expenses extends Fragment {
ArrayList<ExRow> expenseList = new ArrayList<>();
RecyclerView recyclerView;
ExpensesAdapter mAdapter;
Button btnEx;
EditText txtExName;
EditText txtExAmount;
public void expenseData(String txtExNa,String txtExAm) {
ExRow exs = new ExRow(txtExNa, txtExAm);
expenseList.add(exs);
mAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button) rootView.findViewById(R.id.btnEx);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mAdapter = new ExpensesAdapter(expenseList);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setCancelable(true)
.setTitle("Enter Expense:")
.setView(view)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
expenseData(txtExName.getText().toString(),txtExAmount`enter code here`.getText().toString() );
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
}
//row_item_view.xml (Layout for row View of RecyclerView)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/row_name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
<TextView
android:id="#+id/row_amount"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
</LinearLayout>
//Finally the Adapter Class i.e, ExpensesAdapter.java
public class ExpensesAdapter extends RecyclerView.Adapter<ExpensesAdapter.ViewHolder> {
private ArrayList<ExRow> expenseList;
// Constructor of the class
public ExpensesAdapter(ArrayList<ExRow> expenseList) {
this.expenseList = expenseList;
}
// get the size of the list
#Override
public int getItemCount() {
return expenseList == null ? 0 : expenseList.size();
}
// specify the row layout file
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_view, parent, false);
ViewHolder myViewHolder = new ViewHolder(view);
return myViewHolder;
}
// load data in each row element
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
holder.row_name.setText(expenseList.get(listPosition).getNa());
holder.row_amount.setText(expenseList.get(listPosition).getAm());
}
// Static inner class to initialize the views of rows
static class ViewHolder extends RecyclerView.ViewHolder{
public TextView row_name,row_amount;
public ViewHolder(View itemView) {
super(itemView);
row_name = (TextView) itemView.findViewById(R.id.row_name);
row_amount = (TextView) itemView.findViewById(R.id.row_amount);
}
}
}
Hope this finally solves the issue.

Related

RecyclerView not showing (displaying)

RecyclerView is not showing at all. Only the TextView is displayed.
I looked at other questions and used all answers from previous questions.
Other answers suggested that recycler's width can't be set wrap content or that setAdapter should be called after setting layout manager and I meet these conditions.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.main_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
final MainAdapter adapter = new MainAdapter();
recyclerView.setAdapter(adapter);
List<FirebaseProduct> firebaseProductList = new ArrayList<>();
firebaseProductList = getData(); //Here is my Firebase code
adapter.setList(firebaseProductList);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/main_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/aktualne_produkty"
android:gravity="center"
android:background="#color/colorPrimary"
android:textAppearance="#style/TextAppearance.AppCompat.Large">
</TextView>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/main_recycler"
android:layout_height="wrap_content"
android:layout_width="match_parent"
tools:listitem="#layout/card_main"
android:layout_below="#id/main_text"/>
</RelativeLayout>
MainAdapter
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainHolder> {
private List<FirebaseProduct> productList = new ArrayList<>();
#NonNull
#Override
public MainHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_main, parent, false);
return new MainHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MainHolder holder, int position) {
FirebaseProduct product = productList.get(position);
Log.d("Prod holder", "name - " + product.getProductName());
Log.d("Prod holder", "num - " + product.getProductNumber());
holder.nameView.setText(product.getProductName());
holder.numView.setText(product.getProductNumber());
}
#Override
public int getItemCount() {
return productList.size();
}
public void setProductList(List<FirebaseProduct> productList1){
this.productList = productList1;
notifyDataSetChanged();
}
public List<FirebaseProduct> getList(){
return productList;
}
public static class MainHolder extends RecyclerView.ViewHolder{
private TextView nameView;
private TextView numView;
public MainHolder(View itemView){
super(itemView);
nameView = itemView.findViewById(R.id.product_name);
numView = itemView.findViewById(R.id.product_count);
}
}
}
card_main
<androidx.cardview.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:layout_weight="3">
<TextView
android:id="#+id/product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
</TextView>
<TextView
android:id="#+id/product_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/product_name">
</TextView>
</RelativeLayout>
<ImageView
android:id="#+id/product_image"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:contentDescription="#string/product_description">
</ImageView>
</LinearLayout>
</androidx.cardview.widget.CardView>
You are calling adapter.setList(firebaseProductList); in MainActivity but the function name in MainAdapter is setProductList(). So change it to adapter. setProductList(firebaseProductList)
Also, you want to be sure getData(); in MainActivity should return a non-empty list. you can verify it using debugger or by just adding a log statement before adapter.setList(firebaseProductList). like this:
Log.d("LIST_SIZE", firebaseProductList.size()); //this will print list size
adapter.setList(firebaseProductList); //you have to change it to adapter. setProductList(firebaseProductList)

ListViewAdapter context on fragment activity error, what should I do?

Good night android masters. Please help me. maybe those of you who understand better than me can help me solve the problem I'm facing right now.
1 https://imgur.com/S2TU08q
I made a listview on the fragment. I stopped because I was confused how I proceeded. maybe the code below can help you solve my problem!
This is the fragment I made. I name it Frag_Tour.java
public class Frag_Tour extends Fragment {
ListView listView;
ListViewAdapterTour adapter;
String[] judul1;
String[] judul2;
String[] durasi;
String[] harga;
int[] gambarTour;
ArrayList<Model> arrayList = new ArrayList<Model>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_tour, container, false);
judul1 = new String[]{"Paket Hemat", "Paket Reguler", "Paket Honeymoon"};
judul2 = new String[]{"Wisata Belitung", "Wisata Belitung", "Wisata Belitung"};
durasi = new String[]{"3 Hari 2 Malam", "4 Hari 3 Malam", "3 Hari 1 Malam"};
harga = new String[]{"Rp 750.000/pax", "Rp 750.000/pax", "Rp 750.000/pax"};
gambarTour = new int[]{
R.drawable.mercusuar_1, R.drawable.mercusuar_2, R.drawable.mercusuar_3
};
listView = rootView.findViewById(R.id.listView);
for (int i = 0; i < judul1.length; i++) {
Model model = new Model(judul1[i], judul2[i], durasi[i], harga[i], gambarTour[i]);
arrayList.add(model);
}
adapter = new ListViewAdapterTour(this, arrayList);
listView.setAdapter((ListAdapter) arrayList);
return rootView;
}
}
this is the xml file. frag_tour.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent_view"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
[2] https://imgur.com/ehPanZM
this is the ListViewAdapter that I have created. I named it ListViewAdapterTour.java
public class ListViewAdapterTour extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
List<Model> modellist;
ArrayList<Model> arrayList;
public ListViewAdapterTour (Context context, List<Model> modellist) {
mContext = context;
this.modellist = modellist;
inflater = LayoutInflater.from(mContext);
this.arrayList = new ArrayList<Model>();
this.arrayList.addAll(modellist);
}
public class ViewHolder {
TextView Judul1, Judul2, Durasi, Harga;
ImageView GambarTour;
}
#Override
public int getCount() {
return modellist.size();
}
#Override
public Object getItem(int i) {
return modellist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.row_tour, null);
holder.Judul1 = view.findViewById(R.id.judul1);
holder.Judul2 = view.findViewById(R.id.judul2);
holder.Durasi = view.findViewById(R.id.durasi);
holder.Harga = view.findViewById(R.id.harga);
holder.GambarTour = view.findViewById(R.id.GambarTour);
view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}
holder.Judul1.setText(modellist.get(position).getJudul1());
holder.Judul2.setText(modellist.get(position).getJudul2());
holder.Durasi.setText(modellist.get(position).getDurasi());
holder.Harga.setText(modellist.get(position).getHarga());
holder.GambarTour.setImageResource(modellist.get(position).getGambartour());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (modellist.get(position).getJudul1().equals("Paket Hemat 3 Hari 2 Malam")){
Intent intent = new Intent(mContext, TourDetail.class);
intent.putExtra("contentTv","PAKET HEMAT");
mContext.startActivity(intent);
}
}
});
return view;
}
}
and this is the xml file. row_tour.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:focusableInTouchMode="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="#dimen/spacing_middle"
android:layout_weight="1"
app:cardCornerRadius="2dp"
app:cardElevation="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="170dp"
android:orientation="vertical">
<ImageView
android:id="#+id/GambarTour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="#drawable/mercusuar_1"
tools:ignore="ContentDescription" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/overlay_dark_20" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#id/GambarTour"
android:layout_margin="#dimen/spacing_medium"
android:orientation="vertical"
tools:ignore="UselessParent">
<TextView
android:id="#+id/judul1"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Paket Hemat"
android:textColor="#color/White"
android:textStyle="bold" />
<TextView
android:id="#+id/judul2"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wisata Belitung"
android:textColor="#color/White"
android:textStyle="bold" />
<TextView
android:id="#+id/durasi"
style="#style/TextAppearance.AppCompat.Caption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/_3_hari_2_malam"
android:textColor="#color/White" />
</LinearLayout>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignEnd="#id/GambarTour"
android:layout_alignRight="#id/GambarTour"
android:layout_margin="#dimen/spacing_medium"
android:src="#drawable/ic_favorite_border"
android:tint="#color/White" />
<TextView
android:id="#+id/harga"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/GambarTour"
android:layout_alignRight="#id/GambarTour"
android:layout_alignBottom="#id/GambarTour"
android:layout_margin="#dimen/spacing_large"
android:background="#drawable/gradient_green"
android:padding="#dimen/spacing_xmedium"
android:text="Rp 750.000/pax"
android:textColor="#color/White" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
[3] https://imgur.com/h7WiBgK
and this is the code for the model.java that I use
package com.androidrion.sejengkalapp;
class Model {
private String judul1;
private String judul2;
private String durasi;
private String harga;
private int gambartour;
//constructor
Model(String judul1, String judul2, String durasi, String harga, int gambartour) {
this.judul1 = judul1;
this.judul2 = judul2;
this.durasi = durasi;
this.harga = harga;
this.gambartour = gambartour;
}
//getters
String getJudul1() {
return this.judul1;
}
String getJudul2() {
return this.judul2;
}
String getDurasi() {
return this.durasi;
}
String getHarga() {
return this.harga;
}
int getGambartour() {
return this.gambartour;
}
}
I hope the teachers and masters about Android can help me in solving this problem. what I want is row_tour.xml which I have designed to be listview in frag_tour.xml
[4] https://imgur.com/VLzOUiK
The context should be the activity holding the fragment. So instead of this in your adapter constructor, use getActivity()
adapter = new ListViewAdapterTour(getActivity(), arrayList);

RecyclerView not replacing detail pane with fragment on item click

Everytime I click a recycler view item on a tablet, it opens an activity rather than replacing the detail pane with a fragment.
The following line of code is what I use to detect wheter the detail pane is present:
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
Any ideas on the correct location to put this line of code?
activity XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
>
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
sw600dp 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">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/detailBackgroundToolbar"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<View
android:id="#+id/divider"
android:layout_width="1dp"
android:layout_height="0dp"
android:background="?attr/dividerColor"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<android.widget.Toolbar
android:id="#+id/detailBackgroundToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="3"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="4dp"
app:cardCornerRadius="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar_dualline"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toBottomOf="#+id/detailBackgroundToolbar" />
</android.support.constraint.ConstraintLayout>
Fragment class
public class MyFragment extends Fragment {
public MyFragment() {}
List<Product> wcList;
RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
*/
public boolean mTwoPane;
public static MyFragment newInstance() {
return new MyFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
mRecyclerView = view.findViewById(R.id.recyclerView_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));
myList = new ArrayList<>();
String[] items = getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product desserts = new Product();
desserts.setProductName(items[n]);
wdessertsc.setProductDescriptions(itemDescriptions[n]);
myList.add(desserts);
}
MyListAdapter listAdapter = new MyListAdapter(getActivity(), myList);
mRecyclerView.setAdapter(listAdapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
super.onActivityCreated(savedInstanceState);
}
}
Adapter class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
public boolean mTwoPane;
private Context mCtx;
private List<Product> myList;
public MyListAdapter(Context mCtx, List<Product> myList) {
this.mCtx = mCtx;
this.myList = myList;
}
#NonNull
#Override
public MyListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.listitem_dualline, parent,false);
return new MyListAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyListAdapter.MyViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
final Product product = myList.get(holder.getAdapterPosition());
holder.textviewTitle.setText(product.getProductName());
holder.textviewSubtitle.setText(product.getPRoductDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Fragment newFragment;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
newFragment = new FragmentProduct1();
} else {
newFragment = new FragmentProdcut2();
}
MyActivity activity = (MyActivity) v.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
intent = new Intent(v.getContext(), Product1Activity.class);
} else {
intent = new Intent(v.getContext(), Product2Activity.class);
}
mCtx.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return myList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayout;
TextView textviewTitle, textviewSubtitle;
StationViewHolder(View itemView) {
super(itemView);
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
relativeLayout = itemView.findViewById(R.id.listitem_relativelayout);
textviewTitle = itemView.findViewById(R.id.listitem_title);
textviewSubtitle = itemView.findViewById(R.id.listitem_subtitle);
}
}
}
This line mTwoPane = itemView.findViewById(R.id.detail_container) != null; from your view holder will always be false.
Why?
Because, your detail_container is not part of your view holder's item container, so itemView will always return null for your view. instead pass your boolean flag from your fragment to your adapter !
I think you are checking item two pan with recyclerview item xml
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
That you can check while constructing recyclerview adapter and save it from the activity content view itself.

How to show the time when an item in a recyclerview was created?

I want to make this:
I have a RecyclerView, wherein for each item I create I want to show the time when the item was created. I want to display the time within this item.
My code:
public class VerIncidencia extends AppCompatActivity {
private FirebaseRecyclerAdapter mAdapter;
private DatabaseReference mDatabase;
String idIncidencia;
String idEmpresa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_incidencia);
String uid = FirebaseAuth.getInstance().getUid();
idIncidencia = getIntent().getStringExtra("INCIDENCIA_KEY");
idEmpresa = getIntent().getStringExtra("EMPRESA_KEY");
mDatabase = FirebaseDatabase.getInstance().getReference().child("incidencia").child(uid);
RecyclerView recyclerView = findViewById(R.id.list_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Query postsQuery = mDatabase;
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Incidencia>()
.setQuery(postsQuery, Incidencia.class)
.setLifecycleOwner(this)
.build();
mAdapter = new FirebaseRecyclerAdapter<Incidencia, IncidenciaViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull IncidenciaViewHolder holder, final int position, #NonNull final Incidencia empresa) {
holder.departamento.setText(empresa.departamento);
holder.prioridad.setText(empresa.prioridad);
holder.motivo.setText(empresa.motivo);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(VerIncidencia.this, VerIncidenciaCompleta.class);
intent.putExtra("INCIDENCIA_KEY", getRef(position).getKey());
startActivity(intent);
}
});
}
#Override
public IncidenciaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_incidencia, parent, false);
return new IncidenciaViewHolder(view);
}
};
recyclerView.setAdapter(mAdapter);
}
}
ViewHolder:
public class IncidenciaViewHolder extends RecyclerView.ViewHolder{
TextView departamento;
TextView prioridad;
TextView motivo;
public IncidenciaViewHolder(View itemView) {
super(itemView);
departamento = itemView.findViewById(R.id.departamento);
prioridad = itemView.findViewById(R.id.prioridad);
motivo = itemView.findViewById(R.id.motivo);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardView
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="wrap_content"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/departamento"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="-40dp"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/prioridad"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="30dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/motivo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="85dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>

Add item to RecyclerView from AlertDialog input

I'm currently having trouble with adding a second+ items to a RecyclerView after inputting data in an alertdialog box.
I can enter 1 set of data but when I try to add more, it doesn't do anything.
This is my Java file for the fragment i'm working with:
public class tab1Expenses extends Fragment {
List<ExRow> expenseList = new ArrayList();
RecyclerView recyclerView;
ExpensesAdapter mAdapter;
Button btnEx;
EditText txtExName;
EditText txtExAmount;
public void expenseData() {
String Na = txtExName.getText().toString();
String Am = txtExAmount.getText().toString();
ExRow exs = new ExRow(Na, Am);
expenseList.add(exs);
mAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button) rootView.findViewById(R.id.btnEx);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mAdapter = new ExpensesAdapter(expenseList);
final RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
txtExName = (EditText) view.findViewById(R.id.exName);
txtExAmount = (EditText) view.findViewById(R.id.exAmount);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setCancelable(true)
.setTitle("Enter Expense:")
.setView(view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
expenseData();
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
}
And the Java file for the adapter:
public class ExpensesAdapter extends RecyclerView.Adapter<ExpensesAdapter.MyViewHolder> {
private List<ExRow> expenseList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, amount;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.name);
amount = (TextView) view.findViewById(R.id.amount);
}
}
public ExpensesAdapter(List<ExRow> expenseList) {
this.expenseList = expenseList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.expense_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ExRow expense = expenseList.get(position);
holder.title.setText(expense.getTitle());
holder.amount.setText(expense.getAmount());
}
#Override
public int getItemCount() {
return expenseList.size();
}
}
The XML to format the recyclerview list items:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/name"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentLeft="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/amount"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="wrap_content" />
</RelativeLayout>
And this is the XML for the fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ojemz.expensetracker.tab1Expenses"
android:background="#android:color/darker_gray">
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:width="800dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="450dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="450dp"
android:scrollbars="vertical"
android:keepScreenOn="true"
android:isScrollContainer="true" />
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
This is what I currently see AFTER adding a 2nd input
You can't do so:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</ScrollView>
Your RecyclerView has 0 height now. You need to add a some fixed height to it and set a scroll behaviour. Or you can use NestedScrollView or write LayoutManager with the full height expansion.
See this thread for details.
ADDED
Use this XML instead of your but I wrote it without IDE so it can contain some errors.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ojemz.expensetracker.tab1Expenses"
android:background="#android:color/darker_gray">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:keepScreenOn="true" />
<Button
android:text="Add Expense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_gravity="bottom|center_horizontal"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light"
android:textColorLink="#android:color/holo_green_light" />
</FrameLayout>
I solved my problem. It was to do with the height of the relative layout for the recycler items. It was on match parent, i switched to wrap content and it now displays the inputs on the screen

Categories