Fragment TextView is not able to be updated from parcelable object - android

In my fragment, I have a textView which I want to set to a specific String. I want to get the String for the textView from an object, which I send to the fragment as a parcelable.
I can retrieve the parcelable object and use the object to get the String (when I log it, the correct String is displayed). But when I want to use this to set the textView, the textView doesn't change.
Any ideas why this happens and how I can fix it?
Thanks!
Edit1: I added the activity the fragment is located in to, maybe the error is here?
Edit2: I added the Data class (the parcelable object). But removed the content of the constructor just to keep it easy to read.
public class NavigationFragment extends Fragment {
private static final String TAG = "NavigationFragment";
public NavigationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle bundle = this.getArguments();
if(bundle!=null) {
Data data = (Data) bundle.getParcelable("data");
TextView stopTitle = (TextView) view.findViewById(R.id.stopTitle);
final String name = data.getTourName();
Log.d(TAG, name);
stopTitle.setText(name);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context=".DoTourActivity">
<TextView
android:id="#+id/stopTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="stopTitle"
android:textSize="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="365dp"
android:layout_height="158dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.492"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/stopTitle"
tools:src="#drawable/placeholder_pic" />
<TextView
android:id="#+id/stopDescription"
android:layout_width="384dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="24dp"
android:text="stopDescriptionstopDescriptionstopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescriptionstopDescriptionstopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription stopDescription"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="395dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="8dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/stopDescription">
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#android:drawable/ic_menu_mylocation" />
<TextView
android:id="#+id/locationAdress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="locationAdress"
android:textSize="23dp" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#android:drawable/ic_dialog_map" />
</LinearLayout>
<EditText
android:id="#+id/pincode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="8dp"
android:ems="10"
android:inputType="number"
android:text="pincode"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout" />
<Button
android:id="#+id/confirmButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="confirm"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pincode" />
</android.support.constraint.ConstraintLayout>
public class DoTourActivity extends AppCompatActivity {
private static final String TAG = "DoTourActivity";
private SectionStatePagerAdapter sectionStatePagerAdapter;
private ViewPager viewPager;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_tour);
//Fragment management
sectionStatePagerAdapter = new SectionStatePagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
//Setup actionbar
Toolbar myToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(myToolbar);
//get chosen location & build tour
Fragment fragment = new NavigationFragment();
String location = getIntent().getStringExtra("location");
Bundle bundle = new Bundle();
Data data = new Data(location);
bundle.putParcelable("data", data);
fragment.setArguments(bundle);
//launch fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.commit();
}
public void setupViewPager (ViewPager viewPager) {
SectionStatePagerAdapter adapter = new SectionStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new NavigationFragment(), "navFragment");
adapter.addFragment(new QuestionFragment(), "qesFragment");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// switch(item.getItemId())
return super.onOptionsItemSelected(item);
}
}
public class Data implements Parcelable {
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Data createFromParcel(Parcel in) {
return new Data(in);
}
public Data[] newArray(int size) {
return new Data[size];
}
};
private String tourName;
int tourID;
int possiblePoints;
int stops;
Spot[] spots;
//while playing tour
int points = 0;
// Constructor
public Data(String tour){
}
public String getTourName() {
return tourName;
}
public void setTourName(String tourName) {
this.tourName = tourName;
}
public int getTourID() {
return tourID;
}
public void setTourID(int tourID) {
this.tourID = tourID;
}
public int getPossiblePoints() {
return possiblePoints;
}
public void setPossiblePoints(int possiblePoints) {
this.possiblePoints = possiblePoints;
}
public int getStops() {
return stops;
}
public void setStops(int stops) {
this.stops = stops;
}
public Spot[] getSpots() {
return spots;
}
public void setSpots(Spot[] spots) {
this.spots = spots;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
// Parcelling part
public Data(Parcel in){
this.tourName = in.readString();
this.tourID = in.readInt();
this.possiblePoints = in.readInt();
this.stops = in.readInt();
this.spots = in.createTypedArray(Spot.CREATOR);
this.points = in.readInt();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.tourName);
dest.writeInt(this.tourID);
dest.writeInt(this.possiblePoints);
dest.writeInt(this.stops);
for(Spot s : spots){
dest.writeParcelable(s, flags);
}
dest.writeInt(this.points);
}
}

Thanks to #Mike M. this is solved.
The problem was with the activity in which the fragments were hosted. In there I created two different NavigationFragments which I added to the activity. The updating of the TextView happen on the wrong one.

I see from another answer that there was a problem with fragment instances, but I believe you also have a problem with your Parcelable implementation.
public Data(Parcel in){
...
this.spots = in.createTypedArray(Spot.CREATOR);
...
}
#Override
public void writeToParcel(Parcel dest, int flags) {
...
for(Spot s : spots){
dest.writeParcelable(s, flags);
}
...
}
These two calls need to be mirrored, and they currently are not. Rather than iterating over the array yourself, you should use the writeTypedArray() method:
public Data(Parcel in){
...
this.spots = in.createTypedArray(Spot.CREATOR);
...
}
#Override
public void writeToParcel(Parcel dest, int flags) {
...
dest.writeTypedArray(spots, flags);
...
}
If you look at the implementations for writeTypedArray() and createTypedArray(), you'll see that part of the work is to write a flag that indicates the size of the array, so that the code knows how many instances to read out on the other side. Your implementation does not include this step, so the two will be incompatible.

Related

Expandable Recycler view doesnt show my items

I want to use an expandableRecyler but when i use the adapter it doesnt work. It doesnt give me any error or anything. just doesnt appear on the screen
I have this Fragment where i call the recyclerView
public class RecFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
Button btaddrec;
Dialog alerta;
View v;
RecyclerView rvRec;
public RecFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RecFragment.
*/
// TODO: Rename and change types and number of parameters
public static RecFragment newInstance(String param1, String param2) {
RecFragment fragment = new RecFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_rec, container, false);
rvRec = v.findViewById(R.id.recyclerviewRec);
btaddrec = (Button) v.findViewById(R.id.btaddRec);
initData();
setRecycler();
btaddrec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), MainActivity.listarec.size() + "", Toast.LENGTH_SHORT).show();
}
});
return v;
}
private void setRecycler(){
RecyclerRec recyclerRec = new RecyclerRec(MainActivity.listarec);
rvRec.setLayoutManager(new LinearLayoutManager(getActivity()));
rvRec.setAdapter(recyclerRec);
rvRec.setHasFixedSize(true);
}
private void initData(){
MainActivity.listarec.add(new Recordatorio("Homework","Math and Science Homewowk","14:00"));
MainActivity.listarec.add(new Recordatorio("Homework","Math and Science Homewowk","14:00"));
}
}
Function initData add some objects to my list (i have checked that it works with the Button, my list has 2 items)
Function setRecycler set the adapter for the recyclerview
This is my class RecyclerRec
public class RecyclerRec extends RecyclerView.Adapter<RecyclerRec.RecVh>{
ArrayList<Recordatorio> listarec;
public RecyclerRec (ArrayList<Recordatorio> lista){
this.listarec = lista;
}
#NonNull
#Override
public RecVh onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rec_layout,parent,false);
return new RecVh(v);
}
#Override
public void onBindViewHolder(#NonNull RecVh holder, int position) {
Recordatorio rec = listarec.get(position);
holder.tvTitulo.setText(rec.getTitulo());
holder.tvCuerpo.setText(rec.getCuerpo());
holder.tvHora.setText(rec.getHora());
boolean expanded = rec.isExpanded();
holder.expandable.setVisibility(expanded ? View.VISIBLE : View.GONE);
}
#Override
public int getItemCount() {
return listarec.size();
}
public class RecVh extends RecyclerView.ViewHolder {
TextView tvTitulo,tvCuerpo,tvHora;
LinearLayout linearLayout;
ConstraintLayout expandable;
public RecVh(#NonNull View itemView) {
super(itemView);
tvTitulo = itemView.findViewById(R.id.tvTituloRec);
tvCuerpo = itemView.findViewById(R.id.tvCuerpo);
tvHora = itemView.findViewById(R.id.tvHoraRec);
linearLayout = itemView.findViewById(R.id.linearlayotuexpand);
expandable = itemView.findViewById(R.id.expandableRec);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Recordatorio rec = listarec.get(getAdapterPosition());
rec.setExpanded(!rec.isExpanded());
notifyItemChanged(getAdapterPosition());
}
});
}
}
}
XML of fragment
<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"
tools:context=".Fragments.ClasesFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewRec"
android:layout_width="match_parent"
android:layout_height="451dp"
android:layout_marginTop="50dp" />
<Button
android:id="#+id/btaddRec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="160dp"
android:layout_marginTop="520dp"
android:text="Añadir" />
(Framelayout tag is closed correctly, dunno why stackoverflow doesnt write it with ctrl+k)
XML of my item/row
<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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/tvTituloRec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:padding="10dp"
android:text="Titulo Recordatorio"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#android:color/black"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvHoraRec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hora"
android:textSize="17dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/expandableRec"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tvTituloRec">
<TextView
android:id="#+id/tvCuerpo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="Cuerpo del recordatorio"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
All seems to be in order but when i run the app it doesnt appear and doesnt give me any error.

Display data from json in RecyclerView of Fragment using AsyncTask?

I have the following classes:
CategoryFragment.java
public class CategoryFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "category_name";
// TODO: Rename and change types of parameters
private int mParam1;
public CategoryFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #return A new instance of fragment CategoryFragment.
*/
// TODO: Rename and change types and number of parameters
public static CategoryFragment newInstance(int param1) {
CategoryFragment fragment = new CategoryFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity();
View view = inflater.inflate(R.layout.listado_noticias, container, false);
RecyclerView rw_noticias = view.findViewById(R.id.rw_noticias);
new LoadArticlesTask().execute(MainScreen.mPrefs,MainScreen.hasRemember,view,context,rw_noticias);
return null;
}
}
listado_noticias.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/constraintLayout"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rw_noticias"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
LoadArticlesTask.java
public class LoadArticlesTask extends AsyncTask<Object, Void, List<Article>> {
private static final String TAG = "LoadArticlesTask";
private View view;
private Context context;
private RecyclerView rw_noticias;
#Override
protected List<Article> doInBackground(Object... params) {
SharedPreferences sp = (SharedPreferences)params[0];
boolean hasRemember = (boolean)params[1];
view = (View)params[2];
context = (Context)params[3];
rw_noticias = (RecyclerView)params[4];
List<Article> res = null;
Properties ini = new Properties();
ini.setProperty(RESTConnection.ATTR_SERVICE_URL,Constants.URL_SERVICE);
ini.setProperty(RESTConnection.ATTR_REQUIRE_SELF_CERT,Constants.CERT_VALUE);
ModelManager.configureConnection(ini);
String strIdUser;
String strApiKey;
String strIdAuthUser;
if(hasRemember){
strIdUser = sp.getString("pref_apikey","");
strApiKey = sp.getString("pref_IdUser","");
strIdAuthUser = sp.getString("pref_strIdAuthUser","");
}else {
strIdUser = ModelManager.getLoggedIdUSer();
strApiKey = ModelManager.getLoggedApiKey();
strIdAuthUser = ModelManager.getLoggedAuthType();
}
//ModelManager uses singleton pattern, connecting once per app execution in enough
if (!ModelManager.isConnected()){
// if it is the first login
if (strIdUser==null || strIdUser.equals("")) {
try {
ModelManager.login(Constants.USER, Constants.PASS);
} catch (AuthenticationError e) {
Log.e(TAG, e.getMessage());
}
}
// if we have saved user credentials from previous connections
else{
ModelManager.stayloggedin(strIdUser,strApiKey,strIdAuthUser);
}
}
//If connection has been successful
if (ModelManager.isConnected()) {
try {
// obtain 6 articles from offset 0
res = ModelManager.getArticles(6, 0);
for (Article article : res) {
// We print articles in Log
Log.i(TAG, String.valueOf(article));
}
} catch (ServerCommunicationError e) {
Log.e(TAG,e.getMessage());
}
}
return res;
}
#Override
protected void onPostExecute(List<Article> articles) {
super.onPostExecute(articles);
Log.i("Articles", articles.toString());
for (Article article : articles) {
// We print articles in Log
Log.i("Articles", String.valueOf(article));
}
refreshList(articles,view);
}
public void refreshList(List<Article> data, View view){
if (data == null){
return;
}
for (Article article : data) {
// We print articles in Log
Log.i("Articles_rl", String.valueOf(article));
}
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rw_noticias.setLayoutManager(layoutManager);
ArticlesAdapter articlesAdapter = new ArticlesAdapter(data);
rw_noticias.setAdapter(articlesAdapter);
((ArticlesAdapter)rw_noticias.getAdapter()).updateData(data);
}
}
ArticlesAdapter.java
public class ArticlesAdapter extends RecyclerView.Adapter<ArticlesAdapter.ArticleViewHolder>{
private List<Article> articulos;
public ArticlesAdapter(List<Article> articulos){
this.articulos = articulos;
}
#NonNull
#Override
public ArticleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout_article, parent, false);
return new ArticleViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ArticleViewHolder holder, int position) {
Bitmap imagen = null;
holder.category.setText(articulos.get(position).getCategory());
holder.title.setText(articulos.get(position).getTitleText());
holder.resumen.setText(articulos.get(position).getAbstractText());
try {
imagen = SerializationUtils.base64StringToImg(articulos.get(position).getImage().getImage());
} catch (ServerCommunicationError serverCommunicationError) {
serverCommunicationError.printStackTrace();
}
holder.thumbnail.setImageBitmap(imagen);
}
#Override
public int getItemCount() {
return articulos.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void updateData(List<Article>data){
articulos.clear();
articulos.addAll(data);
notifyDataSetChanged(); //notify to repaint the list
}
public void articlesFilterCategory(String category){
for (Article a : articulos){
if(!category.equals("ALL") && !a.getCategory().equals(category)){
articulos.remove(a);
}
}
}
public static class ArticleViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView category;
TextView title;
TextView resumen;
ImageView thumbnail;
public ArticleViewHolder(#NonNull View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.card_article);
category = (TextView)itemView.findViewById(R.id.category_noticia);
resumen = (TextView)itemView.findViewById(R.id.resumen_noticia);
thumbnail = (ImageView)itemView.findViewById(R.id.thumbnail);
}
}
}
card_layout_article.xml
<androidx.cardview.widget.CardView 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?attr/selectableItemBackground"
android:ellipsize="end"
android:id="#+id/card_article"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingHorizontal="1dp">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="231dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="1dp"
android:layout_marginTop="1dp"
android:adjustViewBounds="true"
android:background="#drawable/a15877171854035"
android:cropToPadding="true"
android:scaleType="fitXY"
android:src="#drawable/degradado" />
<View
android:layout_width="match_parent"
android:layout_height="233dp"
android:background="#drawable/degradado" />
<TextView
android:id="#+id/title_noticia"
android:layout_width="193dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thumbnail"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="107dp"
android:layout_marginEnd="107dp"
android:layout_marginBottom="95dp"
android:text="Nuevo caso de coronavirus"
android:textAlignment="center"
android:textColor="#color/cardview_light_background"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/category_noticia"
android:layout_width="91dp"
android:layout_height="31dp"
android:layout_alignBottom="#+id/thumbnail"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="11dp"
android:layout_marginEnd="316dp"
android:layout_marginBottom="145dp"
android:text="NATIONAL"
android:textAlignment="center"
android:textColor="#color/cardview_light_background"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="#+id/resumen_noticia"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_alignBottom="#+id/thumbnail"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:layout_marginBottom="-1dp"
android:text="Nuevo caso de coronavirus"
android:textAlignment="viewStart"
android:textColor="#color/cardview_light_background"
android:textSize="11dp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
In the log.i that I have in the Post Execute of the async task I can see how the articles are formed (The Article class has a toString () function).
But I can't get the articles to be seen in the RecyclerView. What am I doing wrong?
Capture: Main screen with recyclerView empty...
Thanks!
Pass the instance of RecyclerView like -
new LoadArticlesTask().execute(MainScreen.mPrefs, MainScreen.hasRemember, view, rw_noticias, context);
Receive this on LoadArticlesTask as you are doing with View.
Don't re-initialize/use this code inside your class -
RecyclerView rw_noticias = view.findViewById(R.id.rw_noticias);
In your card_layout_article.xml, make height wrap_content for cardview:
<androidx.cardview.widget.CardView 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
........
........
Also in the layout of your recycler view instead of ConstraintLayout try to use RelativeLayout as the parent:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/constraintLayout"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rw_noticias"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

DialogFragment show only the Buttons even the layout has more

As the picture show the DialogFragment It´s all white except for the Buttons. I have tried all kinds of layout parrams and ConstraintLayout settings but the white background feels like it´s some z-order thing,
Please advice
This is what the ANdroid Studio layout editor look likes
My xml:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:srcCompat="http://schemas.android.com/tools"
android:id="#+id/place_search_dialog"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:visibility="visible">
<ImageView
android:id="#+id/place_search_dialog_header_image_IV"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:contentDescription=""
android:scaleType="centerCrop"
app:layout_constraintBottom_toTopOf="#+id/guideline478"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
srcCompat:src="#drawable/place_picker_dialog_nobackground"/>
<Button
android:id="#+id/btn_place_dialog_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:padding="10dp"
android:text="#string/cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/btn_place_dialog_ok"/>
<Button
android:id="#+id/btn_place_dialog_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:padding="10dp"
android:text="#string/ok"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btn_place_dialog_cancel"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintStart_toStartOf="parent"/>
<android.support.constraint.Guideline
android:id="#+id/guideline355"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.66"/>
<ImageView
android:id="#+id/imageView_street"
android:layout_width="74dp"
android:layout_height="48dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/btn_place_dialog_cancel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.348"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/place_search_dialog_header_image_IV"
app:layout_constraintVertical_bias="0.581"
app:srcCompat="#drawable/avatar"/>
<android.support.constraint.Guideline
android:id="#+id/guideline478"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.28"/>
</android.support.constraint.ConstraintLayout>
UPDATE
This is the DialogFragment
public class GooglePlaceDetailsDialogFragment extends DialogFragment {
private View mRootView;
private BasePlace place;
private Unbinder unbinder;
RequestResponse requestResponse;
private PlaceDetails placeDetails;
public interface ShowPlaceListener {
void onShowPlace(BasePlace item);
}
private ShowPlaceListener mShowPlaceListener;
public static GooglePlaceDetailsDialogFragment newInstance(BasePlace item) {
GooglePlaceDetailsDialogFragment fragment = new GooglePlaceDetailsDialogFragment();
fragment.setPlace(item);
return fragment;
}
// Called to do initial creation of a fragment. This is called after onAttach and before onCreateView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mShowPlaceListener = (ShowPlaceListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement Callback ShowPlaceListener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.dialog_fragment_show_google_place_details, container);
ImageView imageViewStreet = mRootView.findViewById(R.id.imageView_street);
// Just unpack the details to make it smoother
this.requestResponse = place.requestResponse;
this.placeDetails = place.requestResponse.placeDetails;
unbinder = ButterKnife.bind(this, mRootView);
getDialog().setTitle("lkjkjlkj ");
if (placeDetails.url.equals("")) {
if (LogManager.isDebugable()) {
Picasso.with(getActivity()).setIndicatorsEnabled(true);
}
Picasso.with(getActivity())
.load(R.drawable.anon_user_48dp)
.transform(new CircleTransformation())
.into(imageViewStreet);
} else {
if (LogManager.isDebugable()) {
Picasso.with(getActivity()).setIndicatorsEnabled(true);
}
Picasso.with(getActivity())
.load(placeDetails.url)
.transform(new CircleTransformation())
.into(imageViewStreet);
}
return mRootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
}
#OnClick(R.id.btn_place_dialog_ok)
public void onSearchClicked() {
if (mShowPlaceListener != null) {
mShowPlaceListener.onShowPlace(place);
}
dismiss();
}
#OnClick(R.id.btn_place_dialog_cancel)
public void onCancelClicked() {
dismiss();
}
private void setPlace(BasePlace place) {
this.place = place;
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
This is the creation
GooglePlaceDetailsDialogFragment dialog = GooglePlaceDetailsDialogFragment.newInstance(item);
dialog.setTargetFragment(this, 0);
DialogUtils.showDialogFragment(getFragmentManager(), dialog);
Util..
public class DialogUtils {
private static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment,
String fragmentTag, boolean onlyIfNotDuplicate) {
// If only showing non duplicates dialogs, make sure the fragment isn't already in the manager
boolean doesFragmentExist = fragmentManager.findFragmentByTag(fragmentTag) != null;
if (!(onlyIfNotDuplicate && doesFragmentExist)) {
dialogFragment.show(fragmentManager, fragmentTag);
}
return fragmentTag;
}
public static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment,
boolean onlyIfNotDuplicate) {
return showDialogFragment(fragmentManager, dialogFragment, generateFragmentTag(dialogFragment), onlyIfNotDuplicate);
}
private static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment,
String fragmentTag) {
return showDialogFragment(fragmentManager, dialogFragment, fragmentTag, true);
}
public static String showDialogFragment(FragmentManager fragmentManager, DialogFragment dialogFragment) {
return showDialogFragment(fragmentManager, dialogFragment, generateFragmentTag(dialogFragment));
}
private static String generateFragmentTag(Fragment fragment) {
return fragment.getClass().getName();
}
}
ok when I replace the srcCompat:src= with app:srcCompat=` the images show, Strange that AS did not complain abut this typo

List view inside Fragment is not getting populated

I am trying to populate a ListView and display it under Fragment. I see that the count is returning correctly (greater than 0) after calling the adapter. Initially I had an issue with getView not being called but it was in a way resolved by changing layout_height to wrap_content as suggested by one of the article. I see that getView is now called while swiping for one Fragment to another. But getView doesn't get called when the Fragment is initially loaded. and also I don't ListView is displayed on screen regardless of any action.
First Fragment:
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
//private ListView mListView;
GridView grid;
String[] web = {
"Doctors","Movies","Dentists"} ;
int[] imageId = {
R.mipmap.doctors,
R.mipmap.dentists,
R.mipmap.restaurants
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
CustomGrid adapter = new CustomGrid(view.getContext(), iconSize);
GridView gridview = (GridView) view.findViewById(R.id.grid);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(), "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
ListItemMainFragment nextFrag = new ListItemMainFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(((ViewGroup) getView().getParent()).getId(), nextFrag);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);// it will anim while calling fragment.
ft.addToBackStack(null); // it will manage back stack of fragments.
ft.commit();
}
});
return view;
}
}
Next Fragment:
public class ListItemMainFragment extends Fragment implements Item.DataListener {
private ListView mListView;
private ItemAdapter adapter;
public ListItemMainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_item_main, container, false);
mListView = (ListView) view.findViewById(R.id.item_list_view);
mListView.setAdapter(adapter);
//final String DBReference = "all/" + position + "/" + web[+position];
final String DBReference = "all/0/Doctors";
Item.getRecipesFromDB(ListItemMainFragment.this, DBReference);
return view;
}
#Override
public void newDataReceived(ArrayList<Item> itemList) {
adapter = new ItemAdapter(getActivity(), itemList);
mListView.setAdapter(adapter);
Log.d("records ", String.valueOf((adapter.getCount())));
}
}
Adapter:
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Item> mDataSource;
public ItemAdapter(Context context, ArrayList<Item> items) {
Log.d("MyApp", "I am here1000A");
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//1
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Object getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item_detail, parent, false);
Log.d("MyApp", "I am here1000");
TextView titlePrefixTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_title_prefix);
TextView titleTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_title);
TextView specialityTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_speciality);
TextView addressTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_address);
TextView distanceTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_distance);
TextView timingsTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_timings);
TextView contactTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_contact);
// Get thumbnail element
//ImageView thumbnailImageView =
// (ImageView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_thumbnail);
Item item = (Item) getItem(position);
titlePrefixTextView.setText(String.valueOf(position+1) + ".");
titleTextView.setText(item.title);
specialityTextView.setText(item.speciality);
addressTextView.setText(item.address);
distanceTextView.setText(item.distance);
timingsTextView.setText(item.timings);
contactTextView.setText(item.contact);
return rowView;
}
}
Item.java:
public class Item {
public String title;
public String speciality;
public String timings;
public String address;
public String contact;
public String distance;
public interface DataListener {
void newDataReceived(ArrayList<Item> itemList);
}
public Item () {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
public String getTitle() {
return title;
}
public String getSpeciality() { return speciality; }
public String getTimings() {
return timings;
}
public String getAddress() { return address; }
public String getContact() { return contact; }
public String getDistance() { return distance; }
public static void getRecipesFromDB(final DataListener dataListener, String DBReference){
final ArrayList<Item> itemList = new ArrayList<>();
final DatabaseReference mDatabase;
final Item item = new Item();
mDatabase = FirebaseDatabase.getInstance().getReference(DBReference);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("There are " + snapshot.getChildrenCount() + " recipes");
Log.d("MyApp", "I am here100");
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Item post = postSnapshot.getValue(Item.class);
Item item = new Item();
item.title = post.getTitle();
item.speciality = post.getSpeciality();
item.timings = post.getTimings();
item.address = post.getAddress();
item.contact = post.getContact();
item.distance = post.getDistance();
itemList.add(item);
}
// Transaction complete, sending to listener
dataListener.newDataReceived(itemList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
}
}
ListView:
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
tools:context="com.ferainc.kudla.ListItemMainFragment">
<ListView
android:id="#+id/item_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
ListView Item detail:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#android:color/holo_green_light"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:id="#+id/list_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#android:color/holo_green_light">
<TextView
android:id="#+id/item_list_title_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:textSize="18sp"
android:textColor="#android:color/holo_red_light"
tools:text="Title" />
<TextView
android:id="#+id/item_list_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_toEndOf="#id/item_list_title_prefix"
android:textSize="18sp"
android:textColor="#android:color/holo_red_light"
tools:text="Title" />
<TextView
android:id="#+id/item_list_speciality"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_title"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:textColor="#000000" />
<View
android:id="#+id/center_divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/item_list_speciality"
android:background="#android:color/darker_gray" />
<TextView
android:id="#+id/item_list_contact_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/center_divider"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Ph:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_contact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/center_divider"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_contact_prefix"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_address_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_contact"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Address:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_contact"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_address_prefix"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_distance_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_address"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Distance:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_address"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_distance_prefix"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_timings_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_distance"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Timings:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_timings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_distance"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_timings_prefix"
android:textColor="#fff092b0" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I am not sure what you wanted by Item.getRecipesFromDB(ListItemMainFragment.this, DBReference);
as there is no code regarding "Items" it your Fragment.
But it think it doesn't populate your ListView.
So after ListView initialisation you have to create an adapter (it is missing in your onCreateView). And then set it onto ListView.
You also may try to call newDataReceived() from onCreteView.
But I suggest you to create the Adapter in onCreteView and then in newDataReceived() you can just update data and call notifyDataSetChanged() instead of creating new one each time

Passing data from Recycler view onClick to Detail Activity with android databinding

I am having a list of items populating through recyclerview with android databinding technique and now I want to pass and populate the same data in detail Activity not getting the right thing to do such. So, kindly help to do this.
public class Fragment extends Fragment {
private FirebaseRecyclerAdapter adapter;
private Firebase mFirebaseRef = new Firebase("https://xyz.firebaseio.com/category/").child("list");
public Fragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.recycler_view, container, false);
final RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
adapter = new FirebaseRecyclerAdapter<List, ViewHolder>List.class, R.layout.fragment,
ViewHolder.class, mFirebaseRef) {
#Override
protected void populateViewHolder(ViewHolder viewHolder, List list, int i) {
FragmentBinding binding = viewHolder.getBinding();
binding.setList(list);
}
};
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
return rootView;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public FragmentBinding binding;
public ViewHolder(View itemView) {
super(itemView);
binding = DataBindingUtil.bind(itemView);
itemView.setOnClickListener(this);
}
public FragmentBinding getBinding() {
return binding;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
**// need help here**
v.getContext().startActivity(intent);
}
}
#BindingAdapter("quantity")
public static void setQuantityText(TextView view, int quantity) {
view.setText(String.valueOf(quantity));
}
public static class Handlers {
public static void increment(View view, int max) {
FragmentBinding binding = DataBindingUtil.findBinding(view);
binding.setQuantity(Math.max(max, binding.getQuantity() + 1));
}
public static void decrement(View view, int min) {
FragmentBinding binding = DataBindingUtil.findBinding(view);
binding.setQuantity(Math.min(min, binding.getQuantity() - 1));
}
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="List"
type="com.xyz.www.android.model.List"/>
<variable
name="quantity"
type="int"/>
<variable
name="Handlers"
type="com.xyz.www.android.ui.fragments.Fragment.Handlers"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/activity_horizontal_margin"
android:paddingEnd="#dimen/activity_horizontal_margin"
android:paddingTop="8dp">
<ImageView
android:layout_width="76dp"
android:layout_height="76dp"
android:contentDescription="#string/content_description"
app:imageUrl="#{List.productImageUrl}"
android:padding="8dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginTop="8dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="72dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productTitle}"
android:textSize="16sp"
android:textColor="#android:color/primary_text_light"
app:font="#{`Roboto-Regular.ttf`}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productSku}"
android:textSize="13sp"
android:paddingTop="8dp"
app:font="#{`Roboto-Regular.ttf`}"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Rs"
android:textSize="14sp"
android:paddingTop="8dp"
android:paddingEnd="2dp"
android:paddingStart="2dp"
app:font="#{`Roboto-Regular.ttf`}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productSellingPrice}"
android:textSize="14sp"
android:paddingTop="8dp"
android:paddingStart="2dp"
android:paddingEnd="2dp"
android:textColor="#android:color/primary_text_light"
app:font="#{`Roboto-Regular.ttf`}"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentEnd="true"
android:paddingTop="16dp"
android:paddingBottom="16dp">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/decrease" />
<TextView
android:layout_width="32dp"
android:layout_height="wrap_content"
app:font="#{`Roboto-Regular.ttf`}"
app:quantity="#{quantity}"
android:textAlignment="center" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/increase" />
</LinearLayout>
</RelativeLayout>
#JsonIgnoreProperties(ignoreUnknown=true)
public class List extends BaseObservable {
String productTitle;
String productSku;
String productImageUrl;
String productDescription;
String productMrp;
String productSellingPrice;
public List() {
}
public List(String productTitle, String productSku,
String productImageUrl, String productDescription,
String productMrp, String productSellingPrice) {
this.productTitle = productTitle;
this.productSku = productSku;
this.productImageUrl = productImageUrl;
this.productDescription = productDescription;
this.productMrp = productMrp;
this.productSellingPrice = productSellingPrice;
}
#Bindable
public String getProductTitle() {
return productTitle;
}
#Bindable
public String getProductSku() {
return productSku;
}
#Bindable
public String getProductImageUrl() {
return productImageUrl;
}
#Bindable
public String getProductDescription() {
return productDescription;
}
#Bindable
public String getProductMrp() {
return productMrp;
}
#Bindable
public String getProductSellingPrice() {
return productSellingPrice;
}
There are a few ways to do this. One is to make List Parcelable so that you can pass it as an Intent extra. You'll then be able to extract it and populate the Detail page.
public static final LIST = "ListContent";
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
FragmentBinding binding = DataBindingUtil.findBinding(v);
intent.putExtra(LIST, binding.getList());
v.getContext().startActivity(intent);
}
Another is to pass only the ID for the List and read the information again in the detail binding. Add the ID to the List and then you'll be able to extract it when you start the activity:
public static final LIST_ID = "ListID";
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
FragmentBinding binding = DataBindingUtil.findBinding(v);
intent.putExtra(LIST_ID, binding.getList().getId());
v.getContext().startActivity(intent);
}
Either way, you can pull the data from the intent in the onCreate of your details Activity:
public void onCreate(...) {
Intent intent = getIntent();
// Using ID:
int id = intent.getIntExtra(LIST_ID);
List list = loadListFromId(id);
// Using Parcelable:
List list = intent.getParcelableExtra(LIST);
//...
}

Categories

Resources