I made a listview with adapter and each listview item contains four RadioButtons.
What I want to do is to have a button on the listview containing activity.And when I click on that button it will retrieve all checkstate of radiobuttons of each item and send them to other activities.
But I don't know how to retrieve that data although I searched a lot . this is the Activity.java file
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.width;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
import static android.util.TypedValue.applyDimension;
/**
* Created by jack on 30/08/17.
*/
public class TempActivity extends AppCompatActivity {
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.s7_1);
ArrayList<String> titlesArray = new ArrayList<>();
titlesArray.add("إيه رأيك في البني آدم اللي شرح الدورة");
titlesArray.add("ايه رأيك في المكان اللي تمت فيه الدورة");
titlesArray.add("الجهة المنظمة اللي عملت الدورة");
titlesArray.add("محتوى الدورة");
titlesArray.add("تقييم عام");
//Initialization of Adapter and ListView and hooking them together
RateAdapter rateAdapter = new RateAdapter(this , titlesArray);
listView = (ListView)findViewById(R.id.rate_listview);
listView.setAdapter(rateAdapter);
Toast.makeText(getBaseContext() , listView.getCount()+"" , Toast.LENGTH_SHORT).show();
}
}
This is my adapter
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
public class RateAdapter extends ArrayAdapter {
View listItemView;
String currentTitle;
TextView titleTV ;
Context context;
public String a ="test";
public RateAdapter(Context context, ArrayList<String> arrayList) {
super(context, 0, arrayList);
this.context = context;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.n, parent, false);
}
//Declaration for the current title
currentTitle = (String) getItem(position);
//Initializations //Note if radiobuttons are declared as global variables the items are missed up :D
final RadioButton radioVa = (RadioButton) listItemView.findViewById(R.id.rateitems_va);
final RadioButton radioVb = (RadioButton) listItemView.findViewById(R.id.rateitems_vb);
final RadioButton radioVc = (RadioButton) listItemView.findViewById(R.id.rateitems_vc);
final RadioButton radioVd = (RadioButton) listItemView.findViewById(R.id.rateitems_vd);
titleTV = (TextView)listItemView.findViewById(R.id.rateitems_title);
//Setting the title to the TextView
titleTV.setText(currentTitle);
//Setting oncheck listener to permit only one check
//for Va
radioVa.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVc.setChecked(false);
}
}
});
//
radioVb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVa.setChecked(false);
radioVc.setChecked(false);
radioVd.setChecked(false);
}
}
});
radioVc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVa.setChecked(false);
radioVb.setChecked(false);
radioVd.setChecked(false);
}
}
});
radioVd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
radioVb.setChecked(false);
radioVc.setChecked(false);
radioVa.setChecked(false);
}
}
});
return listItemView;
}
}
This is the listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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="160dp"
android:orientation="vertical"
android:layoutDirection="rtl"
android:background="#fff"
android:paddingBottom="10dp">
<TextView
android:id="#+id/rateitems_title"
android:gravity="center_vertical"
android:paddingRight="15dp"
tools:text="ًWhat do you think about me "
android:textColor="#fff"
android:textSize="13sp"
android:textStyle="bold"
android:background="#277db3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="30dp"/>
<LinearLayout
android:orientation="vertical"
android:padding="30dp"
android:layout_below="#id/rateitems_title"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:background="#drawable/course_items_border_trans"
android:id="#+id/rateitems_va"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="ممتاز"
android:textSize="15sp"
android:paddingRight="5dp"/>
<RadioButton
android:id="#+id/rateitems_vb"
android:background="#drawable/course_items_border_trans"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="جيد جدا"
android:textSize="15sp"
android:paddingRight="5dp"/>
</RadioGroup>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/rateitems_vc"
android:background="#drawable/course_items_border_trans"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="جيد"
android:textSize="15sp"
android:paddingRight="5dp"/>
<RadioButton
android:id="#+id/rateitems_vd"
android:background="#drawable/course_items_border_trans"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="ضعيف"
android:textSize="15sp"
android:paddingRight="5dp"/>
</RadioGroup>
</LinearLayout>
</android.widget.RelativeLayout>
and this is the activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layoutDirection="rtl"
android:background="#fff"
android:paddingBottom="10dp">
<TextView
android:gravity="center_vertical"
android:paddingLeft="15dp"
tools:text="List test"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"
android:background="#277db3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="30dp"/>
<ListView
android:id="#+id/rate_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/the_btn"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.widget.LinearLayout>
Use a model something like
Class Rate{
String title;
int rate;
Rates(String title){
this.title = title;
}
public void setRate(int rate){
this.rate = rate;
}
public String getTitle(){
return this.title;
}
}
Now, inside activity do something like:
List<Rates> rates = new ArrayList<>();
rates.add(new Rates("إيه رأيك في البني آدم اللي شرح الدورة"));
rates.add(new Rates("ايه رأيك في المكان اللي تمت فيه الدورة");
rates.add(new Rates("الجهة المنظمة اللي عملت الدورة"));
rates.add(new Rates("محتوى الدورة"));
rates.add(new Rates("تقييم عام"));
List<String> strings = new ArrayList<>(rates.size());
for (Rate rate : rates) {
strings.add(rate != null ? rate.getTitle() : null);
}
//Initialization of Adapter and ListView and hooking them together
RateAdapter rateAdapter = new RateAdapter(this , titlesArray);
Now, inside adapter class, Handle the Event for radio buttons. To pass data back to Activity, created an interface to update respective index.
interface RadioClickListener{
void radioClicked(int position, int rate);
}
...
RadioClickListener radioClickListener;
...
public RateAdapter(Context context, ArrayList<String> arrayList) {
super(context, 0, arrayList);
this.context = context;
radioClicked = (RadioClickListener) context;
}
So, when you click the ratioButton, item at respective index is updated by calling
//pass the position and rate for that item
radioClickListener.radioClicked(position, "1");
And finally implement the interface to the Activity to update the List.
public class TempActivity extends AppCompatActivity implements RateAdapter.RadioClickListener {
...
#Override
public void radioClicked(int position, int rate){
rates.get(position).setRate(rate);
}
Now, you have the updated rates List, So to pass it to another activity parcel is with the intent and send it.
Related
i'm just setup my RecyclerView but there's not appear in my emulator & there is error "E/RecyclerView: No adapter attached; skipping layout" Could you guys help me to find my failure?
This is my application layout :
Click here to see my application layout view
StockContent.Java (Fragment) :
package com.example.psmandroidapps;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.Toolbar;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class StockContent extends Fragment {
RecyclerView StockRecyclerView;
List<ModalClass> mList;
CustomAdapter customAdapter;
public StockContent() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View stockview = inflater.inflate(R.layout.stock_content, container, false);
StockRecyclerView = stockview.findViewById(R.id.StockRecyclerView);
customAdapter = new CustomAdapter(mList,getContext());
StockRecyclerView.setAdapter(customAdapter);
StockRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return stockview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//just for sample only
mList = new ArrayList<>();
mList.add(new ModalClass(R.drawable.profilepicture,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logodetail,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logo,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.profilepicture,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logodetail,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logo,"Mitsubishi S-N50"));
}
}
StockContent.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3FFFC">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/StockRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
Stock_CardView.XML (for recyclerview content) :
<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="15dp"
android:layout_margin="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
android:layout_width="100dp"
android:layout_height="100dp"
app:cardCornerRadius="30dp"
android:layout_margin="15dp"
android:layout_weight="0.1">
<ImageView
android:id="#+id/img_goodspicture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/profilepicture"
android:scaleType="centerCrop"/>
</androidx.cardview.widget.CardView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:layout_marginRight="15dp"
>
<TextView
android:id="#+id/txt_goodsname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mitsubishi S-N10 (220V)"
android:textColor="#000000"
android:fontFamily="#font/sarabun_bold"
android:textSize="21dp"
android:layout_marginBottom="0dp"/>
<TextView
android:id="#+id/txt_goodstype"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Jenis : Contactor"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp" />
<TextView
android:id="#+id/txt_goodsstock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stok : 105 pcs"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp"/>
<TextView
android:id="#+id/txt_dateofgoodsentry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tanggal masuk : 29/07/2020"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
ModalClass.Java :
package com.example.psmandroidapps;
public class ModalClass {
int image;
String text;
public ModalClass(int image, String text) {
this.image = image;
this.text = text;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
CustomAdapter.Java :
package com.example.psmandroidapps;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
List<ModalClass> mList;
Context context;
public CustomAdapter(List<ModalClass> mList, Context context) {
this.mList = mList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.stock_cardview,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.imageView.setImageResource(mList.get(position).getImage());
holder.textView.setText(mList.get(position).getText());
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.img_goodspicture);
textView=itemView.findViewById(R.id.txt_goodsname);
}
}
}
Thats the code of mine.. the result is nothing, nothing showing in my emulator.. Thank you for read this question, hope you guys can help me to solve my problem here. Thank you guys! have a nice day
If i complete those edit text with what i want,it will show the info to my fire data base but in the recycler view never show the third holder(holder.textViewZ.setText(model.getWhy). Do you have any idea why is this happening?
This is my main activity
package com.example.incercarefirebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.graphics.ColorSpace;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.SuccessContinuation;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.net.IDN;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private Button btnSaveRecycler;
private EditText etNAME, etSurrname, etZ;
private FirebaseRecyclerOptions<Model> options;
private DatabaseReference rootDatabaseref;
private FirebaseRecyclerAdapter<Model, MyViewHolder> adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNAME = findViewById(R.id.etNAME);
etSurrname = findViewById(R.id.etSurrname);
etZ = findViewById(R.id.etZ);
btnSaveRecycler = findViewById(R.id.btnSaveRecycler);
recyclerView = findViewById(R.id.recyclerviewID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
rootDatabaseref = FirebaseDatabase.getInstance().getReference().child("Users");
btnSaveRecycler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = Integer.parseInt(etNAME.getText().toString());
String name = etSurrname.getText().toString();
String why = etZ.getText().toString();
String key = rootDatabaseref.push().getKey();
rootDatabaseref.child(key).child("ID").setValue(id);
rootDatabaseref.child(key).child("Name").setValue(name);
rootDatabaseref.child(key).child("Why").setValue(why);
}
});
options = new FirebaseRecyclerOptions.Builder<Model>().setQuery(rootDatabaseref, Model.class).build();
adapter = new FirebaseRecyclerAdapter<Model, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull Model model) {
holder.textviewName.setText(model.getName());
holder.textviewID.setText(model.getID());
holder.textViewZ.setText(model.getWhy());
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_layout, parent, false);
return new MyViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
}
This is my viewHolder
package com.example.incercarefirebase;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textviewID, textviewName, textViewZ;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
textviewID = itemView.findViewById(R.id.textViewID);
textviewName = itemView.findViewById(R.id.textViewName);
textViewZ = itemView.findViewById(R.id.textViewZ);
}
}
This is my model
package com.example.incercarefirebase;
public class Model {
private int ID;
private String Name;
private String Why;
public Model() {
}
public Model(int ID, String name, String why) {
this.ID = ID;
Name = name;
Why = why;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getWhy() {
return Why;
}
public void setWhy(String why) {
Why = why;
}
}
This is the single_view_layout
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="123"
android:textSize="30dp" />
<TextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name..."
android:textSize="30dp" />
<TextView
android:id="#+id/textViewZ"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="aaaaa"
android:textSize="30dp" />
</LinearLayout>
This is the main 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="#+id/etNAME"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="ID"
android:inputType="textPersonName" />
<EditText
android:id="#+id/etSurrname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Name"
android:inputType="textPassword" />
<EditText
android:id="#+id/etZ"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="#+id/btnSaveRecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewID"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
I have an app with a bottom navigation view that changes between 4 fragments and I'm trying to make it so that those fragments are displayed with data from firebase using FirebaseRecyclerView Adapter.
I have everything set up but the layout that the FirebaseRecyclerView Adapter inflates is not appearing.
My MainAcitivity.java
package com.pap.diogo.pilltrack;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class MainActivity extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new HomeFragment();
break;
case R.id.navigation_pills:
selectedFragment = new PillsFragment();
break;
case R.id.navigation_appointment:
selectedFragment = new AppointsFragment();
break;
case R.id.navigation_account:
selectedFragment = new AccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
Intent VerifyLogin = new Intent(MainActivity.this, Launcher.class);
VerifyLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(VerifyLogin);
}
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
};
My AccountFragment.java
package com.pap.diogo.pilltrack;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class AccountFragment extends Fragment {
private RecyclerView AccountUsers;
private View mMainView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_account, container, false);
AccountUsers = mMainView.findViewById(R.id.accountlist);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
AccountUsers.setLayoutManager(linearLayoutManager);
AccountUsers.setHasFixedSize(true);
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String userid = user.getUid();
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
FirebaseRecyclerOptions<Account> AccountQ = new FirebaseRecyclerOptions.Builder<Account>().setQuery(ref, Account.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<Account, AccountInfo> AccountAdapter = new FirebaseRecyclerAdapter<Account, AccountInfo>(AccountQ){
#NonNull
#Override
public AccountInfo onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new AccountInfo(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.account, viewGroup, false));
}
#Override
protected void onBindViewHolder(#NonNull final AccountInfo holder, int position, #NonNull final Account model) {
ref.child(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String name = dataSnapshot.child("name").getValue().toString();
final String age = dataSnapshot.child("idade").getValue().toString();
holder.setName(name);
holder.setAge(age);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
};
AccountUsers.setAdapter(AccountAdapter);
}
public static class AccountInfo extends RecyclerView.ViewHolder{
View AccountL;
public AccountInfo(#NonNull View itemView) {
super(itemView);
AccountL = itemView;
}
public void setName(String name){
TextView AccountName = AccountL.findViewById(R.id.AccountName0);
AccountName.setText(name);
}
public void setAge(String age){
TextView AccountAge = AccountL.findViewById(R.id.AccountAge0);
AccountAge.setText(age);
}
}
}
My account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/AccountUser"
android:layout_width="match_parent"
android:layout_height="163dp"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="15dp"
android:background="#drawable/edit_bg"
android:padding="15dp">
<RelativeLayout
android:id="#+id/AccountImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/AccountInfos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/AccountImage"
android:layout_toEndOf="#id/AccountImage"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp">
<TextView
android:id="#+id/AccountName0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Nome1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/AccountAge0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountName0"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Idade1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="#+id/AccountChangePass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountAge0"
android:text="Mudar Palavra-Passe"
android:textColor="#color/colorWhite"
android:textSize="18sp"
android:textStyle="bold"
android:textAllCaps="false"
android:padding="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/custom_button"/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountUser">
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:src="#drawable/ic_add"
android:padding="5dp"
android:background="#drawable/add_button"/>
</RelativeLayout>
</RelativeLayout>
My fragment_account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/accountlist">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
GitHub of my APP
I fixed it.
All I had to do was to remove this line of code:
AccountUsers.setHasFixedSize(true);
I am using a custom adapter for my ListView which I already don't understand as much as I would like to. I can find information online on how to add a row to ListView but it doesn't integrate nicely into my code, I'm guessing because I'm using a custom adapter. I have my setOnClickListener() method for my button in my Main Activity and have been experimenting there but just cant figure it out I'm also not sure if my method is in the right place?
this is the mainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import static java.util.logging.Logger.global;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] Chores = {""};
ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
// this is where I am trying to have button click add another row to my listView
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//this is where I am stuck
}
});
}
}
here is my CustomAdapter class
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
class CustomAdapter extends ArrayAdapter{
public CustomAdapter(Context context, String[] choreText) {
super(context, R.layout.custon_listview_row, choreText);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myInflater = LayoutInflater.from(getContext());
View customView = myInflater.inflate(R.layout.custon_listview_row, parent, false);
String singleListItem = (String) getItem(position);
EditText choreText = (EditText) customView.findViewById(R.id.editText_ID);
ImageButton imageButton = (ImageButton) customView.findViewById(R.id.imageButton_ID);
choreText.setText(singleListItem, TextView.BufferType.EDITABLE);
imageButton.setImageResource(R.drawable.clock);
return customView;
}
}
activity_main.xml
<?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:id="#+id/activity_main"
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.emilythacker.chorelist.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/customListView_ID"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp" />
<Button
android:text="Add Chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/button_ID" />
</RelativeLayout>
and custom_listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp">
<ImageButton
android:layout_width="60dp"
android:scaleType="fitCenter"
app:srcCompat="#drawable/clock"
android:id="#+id/imageButton_ID"
android:layout_height="60dp"
android:background="#null"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/editText_ID"
android:layout_alignParentLeft="true"
android:alpha = ".5"
android:hint="Enter chore"
android:maxLines="1"
android:inputType="text"
/>
</RelativeLayout>
First make your list into an ArrayList instead of String array.
private ArrayList<String> arrayList;
In the buttons onClick
arrayList.add("New Item");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
public void onClick(View v) {
String stringToAdd = ... //
MyAdapter.add(stringToAdd);
}
You will need to add final to the adapter declaration for this to work:
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
EDIT
To add more than one row at a time:
public void onClick(View v) {
String[] rowsToAdd = ... //
MyAdapter.addAll(rowsToAdd);
}
I have code for creating adapter for ListView:
ListView films=(ListView)findViewById(R.id.listViewCurrentFilms);
ArrayList<HashMap<String, String>> list=getList();
String[] fields=new String[]{"title", "director", "cast"};
int[] resources=new int[]{R.id.textViewFilmName, R.id.textViewDirector, R.id.textViewStart};
SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.film_item, fields, resources);
films.setAdapter(adapter);
But I have an ImageView in film_item, and I also need to bind different images from drawable for each item in ListView. How can I do it? Thank you.
this is a working example
import java.io.ByteArrayInputStream;
import java.util.List;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class StockQuoteAdapter extends ArrayAdapter {
private final Activity activity;
private final List stocks;
public StockQuoteAdapter(Activity activity, List objects) {
super(activity, R.layout.movie , objects);
this.activity = activity;
this.stocks = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
StockQuoteView sqView = null;
if(rowView == null)
{
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.stock, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sqView = new StockQuoteView();
sqView.ticker = (TextView) rowView.findViewById(R.id.ticker_symbol);
sqView.quote = (TextView) rowView.findViewById(R.id.ticker_price);
sqView.time = (TextView) rowView.findViewById(R.id.showtimelist);
sqView.img = (ImageView) rowView.findViewById(R.id.Image);
sqView.btn = (Button) rowView.findViewById(R.id.lmbtn);
sqView.ll = (LinearLayout) rowView.findViewById(R.id.LinearLayout02);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sqView);
} else {
sqView = (StockQuoteView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
final StockQuote currentStock = (StockQuote) stocks.get(position);
sqView.ticker.setText(currentStock.getTickerSymbol());
sqView.quote.setText(currentStock.getT_name());
sqView.time.setText(currentStock.getTime());
try{
byte[] bb = currentStock.getBb();
ByteArrayInputStream imageStream = new ByteArrayInputStream(
bb);
Bitmap theImage = BitmapFactory
.decodeStream(imageStream);
Drawable d = new BitmapDrawable(theImage);
sqView.img.setBackgroundDrawable(d);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
sqView.ll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return rowView;
}
protected static class StockQuoteView {
protected TextView ticker;
protected TextView quote;
protected TextView time;
protected ImageView img;
protected Button btn;
protected LinearLayout ll;
}
}
add to activity
StockQuoteAdapter aa = new StockQuoteAdapter(this, stocks);
the stock.xml is
<?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:padding="6dip" android:layout_height="match_parent" android:orientation="horizontal">
- <LinearLayout android:id="#+id/LinearLayout02" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<ImageView android:id="#+id/Image" android:layout_height="80px" android:layout_width="60px" android:layout_margin="15px" />
- <LinearLayout android:id="#+id/LinearLayout01" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="#+id/ticker_symbol" android:textColor="#000000" android:textStyle="bold" />
<TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="#+id/ticker_price" android:textColor="#000000" />
<TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="#+id/showtimelist" android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
</LinearLayout>