Dynamic ListView With EditTexts Android - java

I have a ListView in my Android application that uses a CustomAdapterClass. The ListView is populated with rows that contain 2 Edit Texts per row. This is fine, the problem I'm having is the ListView is dynamic, i.e. I have added a button that will append on a new row by calling notifyDataSetChanged(); however this clears the whole list.
How can I keep the text that has been entered into the EditTexts when a new row is appended? Code below:
Activity.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:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="afterDescendants"
android:id="#+id/listViewAddPeople">
</ListView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabAddPerson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#mipmap/ic_launcher"
app:backgroundTint="#FFFFFF"
android:elevation="6dp"
/>
</RelativeLayout>
Row.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">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/personNameEditText"
android:hint="Enter Persons Full Name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/personPhoneNoEditText"
android:layout_below="#+id/personNameEditText"
android:hint="Enter Phone No. (Optional)"/>
</RelativeLayout>
Java Class:
public class AddPeopleNewProcedureActivity extends AppCompatActivity {
private ListView addPeopleListView;
private CustomAdapterClass customAdapter;
private FloatingActionButton fab;
private int lineCount;
private EditText personsNameET;
private EditText personsPhoneET;
private List<String> personsName;
private List<String> personsPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addpeoplenew_activity);
setupActivityReferences();
inflateListView();
setupClickListeners();
}
private void setupClickListeners() {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lineCount = lineCount +1;
personsName.clear();
personsPhone.clear();
customAdapter.notifyDataSetChanged();
}
});
}
private void inflateListView() {
customAdapter = new CustomAdapterClass();
addPeopleListView.setAdapter(customAdapter);
}
private void setupActivityReferences() {
addPeopleListView = (ListView) findViewById(R.id.listViewAddPeople);
fab = findViewById(R.id.fabAddPerson);
personsNameET = (EditText) findViewById(R.id.personNameEditText);
personsPhoneET = (EditText) findViewById(R.id.personPhoneNoEditText);
lineCount = 1;
}
public class CustomAdapterClass extends BaseAdapter {
#Override
public int getCount() {
return lineCount;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view =
getLayoutInflater().inflate(R.layout.row_addpersonnew,null);
final int rowClicked = i;
return view;
}
}
}
Any help is appreciated!

I have added a button that will append on a new row by calling
notifyDataSetChanged();
I can't see any append actions when someone clicks that button. I see that you clear both of your lists, personsName and personsPhone and after that you notify your adapter that those lists are empty.
Write what really want to be done inside the onClick().

Related

Adapter's class getView() function not called for Android ListView

I am trying to create a ListView having a list of items, each having three components.
Title (SezonNo)
Description
An Image (SezonThumb)
Following is the code for the layout file "layout_album", how will each item in the list be looked like:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.SeasonsActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imgThumbnail"
android:clickable="true"
/>
<TextView
style="#style/style_textviewsProfile"
android:layout_margin="0dp"
android:textStyle="bold"
android:id="#+id/textViewSeasonNo"
android:text="Season No: " />
<TextView
android:id="#+id/textViewDescription"
style="#style/style_textviewsProfile"
android:text="Description: " />
<View
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#color/Gray"></View>
</LinearLayout>
</ScrollView>
The following is the code for the Activity:
public void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seasons);
listView_seasons=findViewById(R.id.list_seasons);
txtTitle = findViewById(R.id.txtTitle);
String[] seasonNos=new String[]{"1","2","3","4","5"};
String[] seasonDescriptions=new String[]{"a","b","c","d","e"};
int[] seasonThumbs= new int[]{R.drawable.sezon1, R.drawable.sezon2, R.drawable.flag, R.drawable.flag, R.drawable.flag};
adapter=new ListAdapter(this,seasonNos,seasonDescriptions,seasonThumbs);
listView_seasons.setAdapter(adapter);
}
//____________________________Adapter Class________________________//
public class ListAdapter extends ArrayAdapter<String> {
Context context;
String sezonNo[];
String desc[];
int[] imgs;
public ListAdapter(#NonNull Context context, String[] sezonNo, String[] desc, int[] imgs) {
super(context,R.layout.layout_album,R.id.textViewSeasonNo,sezonNo);
this.context=context;
this.sezonNo = sezonNo;
this.desc = desc;
this.imgs = imgs;
Log.d("List","Adapter");
}
#Override
public int getCount() {
return 0;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
Log.d("List","setting bindings...");
view=getLayoutInflater().inflate(R.layout.layout_album,null);
TextView txtSezonNo=view.findViewById(R.id.textViewSeasonNo);
TextView txtDescription=view.findViewById(R.id.textViewDescription);
ImageView imgThumbnail=view.findViewById(R.id.imgThumbnail);
progressDialog.hide();
txtSezonNo.setText(seasonNos[position]);
txtDescription.setText(seasonDescriptions[position]);
imgThumbnail.setImageResource(seasonThumbs[position]);
return view;
}
}
The Constructor of Adapter class is getting called but getView() not called at all.
your getView() is not called because the size you returned in getCount() is 0
please in your getCount() put this :
#Override
public int getCount() {
return sezonNo.length;
}
also getItemId should not be 0 for all, simple solution could be return position of item in the list. return position like
#Override
public long getItemId(int position) {
return position;
}

RecyclerView - I can't add more than 1 line

I'm with a problem to add more than 1 line(item) in my RecyclerView, the item overwrites the previous one when I tap the button, but if I create a List<> with data in hardcoded on onCreate, It works adding more than 1 line in the RecyclerView. Follow the code:
ListChecklistAdapter
public class ListChecklistAdapter extends RecyclerView.Adapter<ListChecklistAdapter.ListChecklistViewHolder> {
private List<Checklist> mChecklist;
private Context mCtx;
public ListChecklistAdapter(Context ctx, List<Checklist> checklists) {
mCtx = ctx;
mChecklist = checklists;
}
#Override
public ListChecklistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_checklist, parent, false);
return new ListChecklistViewHolder(view);
}
#Override
public void onBindViewHolder(ListChecklistViewHolder holder, int position) {
holder.cbItem.setText(mChecklist.get(position).getDescricao());
holder.cbItem.setChecked(mChecklist.get(position).isCheckado());
}
#Override
public int getItemCount() {
return mChecklist.size();
}
public class ListChecklistViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_checkbox)
CheckBox cbItem;
public ListChecklistViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public void refreshData(List<Checklist> item) {
this.mChecklist.clear();
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
}
item_checklist
<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">
<CheckBox
android:id="#+id/item_checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:paddingLeft="6dp"
android:text=" "
tools:text="Exemplo de item de lista" />
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.rcv_lista)
RecyclerView rvLista;
int valor;
private List<Checklist> lista;
private ListChecklistAdapter listChecklistAdapter;
#BindView(R.id.btn_add_item)
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
private int cont() {
return valor++;
}
public void novoItem(View view) {
lista = new ArrayList<>();
lista.add(new Checklist("Item " + (cont() + 1), true));
loadRecycler(lista);
}
private void loadRecycler(List<Checklist> lista) {
if (listChecklistAdapter == null) {
Log.i("LOG", "IF");
listChecklistAdapter = new ListChecklistAdapter(this, lista);
rvLista.setAdapter(listChecklistAdapter);
rvLista.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvLista.addItemDecoration(new DividerItemDecoration(this, 1));
return;
} else {
Log.i("LOG", "ELSE");
listChecklistAdapter.refreshData(lista);
listChecklistAdapter.onAttachedToRecyclerView(rvLista);
}
}
}
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="teste.com.br.recyclercomcheckbox.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv_lista"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_add_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:onClick="novoItem"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="+ novo item"
android:textColor="#009688" />
</LinearLayout>
Just remove this line this.mChecklist.clear(); from your refreshData() method.
public void refreshData(List<Checklist> item) {
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
#Nilesh Rathod solved the problem! I just deleted this.mChecklist.clear(); from the ListCheckAdapter.java > refreshData()
Thanks for everyone to help too!

RecyclerView's height 'match_parent' not working as expected whereas fixed height (1000dp,2000dp) is working

I'm working to make a cool layout like this:
For this I'm using Android Parallax library from Github.
This library is creating all the views (as shown in picture) from xml itself.
But I want to create my own recyclerview, create adpaters, model classes and show them with cardview.
I tried using cardview and recyclerview.
Problem:
When I put RecyclerView's height as match_parent (android:layout_height="match_parent"), it gives UI like this:
Only first cardview is display with half part only. Other cardviews are overlapped somehow.
But when I give its height with fixed height like (1000dp, 2000dp), it shows the UI as expected (as shown in first figure). I think it is not a good solution to give its height fixed since data items may differ.
I don't understand what is wrong with my code. Please do suggest some solutions on this.
Following is my different views with my code.
activity_main.xml
<com.github.florent37.parallax.ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:src="#drawable/background"
android:tag="parallax=0.3" />
<TextView
style="#style/MyTitle"
android:layout_width="match_parent"
android:layout_height="160dp"
android:gravity="center"
android:tag="parallax=0.5"
android:text="My awesome title" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
</FrameLayout>
</com.github.florent37.parallax.ScrollView>
card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_margin="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Hello"
android:textStyle="bold" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_marginTop="10dp"
android:text="world" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
My Adapter class is like this:
public class MyRecyclerViewAdapter extends RecyclerView
.Adapter<MyRecyclerViewAdapter
.DataObjectHolder> {
private ArrayList<ContactsModel> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView label;
TextView dateTime;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
dateTime = (TextView) itemView.findViewById(R.id.textView2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<ContactsModel> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
holder.dateTime.setText(mDataset.get(position).getmText2());
}
public void addItem(ContactsModel dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
In MainActivity, I have written code like this:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
Fabric.with(this, new Crashlytics());
}
private ArrayList<ContactsModel> getDataSet() {
ArrayList results = new ArrayList<ContactsModel>();
for (int index = 0; index < 20; index++) {
ContactsModel obj = new ContactsModel("Some Primary Text " + index,
"Secondary " + index);
results.add(index, obj);
}
return results;
}
}
Model class is like:
public class ContactsModel {
private String mText1;
private String mText2;
ContactsModel (String text1, String text2){
mText1 = text1;
mText2 = text2;
}
public String getmText1() {
return mText1;
}
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) {
this.mText2 = mText2;
}
}
Apologies for the very long bulk of code.
Thanks!
You have a RecyclerView (which is scrollable) within a Scrollable Layout.
Replace your ScrollView tag with "android.support.v4.widget.NestedScrollView". This will allow the RecyclerView to properly expand.
<android.support.v4.widget.NestedScrollView
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:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</android.support.v4.widget.NestedScrollView>
After Replaceing your ScrollView with NestedScrollView you can just add this line into the NestedScrollView
android:fillViewport="true"
I was having a same problem in my NestedScrollView.
Just added one line inside NestedScrollView and my problem solved.
android:fillViewport="true"

MultiListView displays only one TextView

I am writing a ListView with 2 TextViews per row, but when I execute I get only one TextView.
Here is my adapter extending Base adapter
public class GlossaryListViewAdapter extends BaseAdapter {
List<Glossary_Entry> glossary_entryList;
Context context;
public GlossaryListViewAdapter(Context context,List<Glossary_Entry> glossary_entryList){
this.glossary_entryList = glossary_entryList;
this.context = context;
}
#Override
public int getCount() {
return glossary_entryList.size();
}
#Override
public Object getItem(int postion) {
return glossary_entryList.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = LayoutInflater.from(context).inflate(R.layout.glossary_single_row,viewGroup,false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)view.getTag();
}
viewHolder.titleTextView.setText(glossary_entryList.get(position).getTitle());
viewHolder.definitionTextView.setText(glossary_entryList.get(position).getDefinition());
return view;
}
private static class ViewHolder{
TextView titleTextView;
TextView definitionTextView;
public ViewHolder(View view){
titleTextView = (TextView)view.findViewById(R.id.glossary_title_textview);
definitionTextView = (TextView)view.findViewById(R.id.glossary_word_definition_textview);
}
}
}
Here is my Activity code
public class GlossaryAcvtivity extends AppCompatActivity {
ListView glossaryListView;
ListAdapter listAdapter;
List<Glossary_Entry> glossary_entryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glossary);
/**
* Sample data
*/
glossary_entryList = new ArrayList<>();
glossary_entryList.add( new Glossary_Entry("Force","This is a push or push on an object.They can be duew to a phenomenon such as gravity, magnetism, or anything that might cause a mass to accelerate."));
glossary_entryList.add( new Glossary_Entry("Motion","Change in position of an object over time, described in terms of displacement,distance,velocity,acceleration,time and speed"));
glossary_entryList.add( new Glossary_Entry("Quantum Leap","An Abrupt transition of an electron,atom, or molecule from one quantum state to another,with the absorption or emission of a quantum"));
glossary_entryList.add( new Glossary_Entry("Force","This is a push or push on an object.They can be duew to a phenomenon such as gravity, magnetism, or anything that might cause a mass to accelerate."));
glossaryListView = (ListView)findViewById(R.id.glossary_list_view);
listAdapter = new GlossaryListViewAdapter(getApplicationContext(),glossary_entryList);
glossaryListView.setAdapter(listAdapter);
}
}
The source of my data is an Entry class
public class Glossary_Entry {
public String title;
public String definition;
public String getTitle() {
return title;
}
public String getDefinition() {
return definition;
}
public Glossary_Entry(String title,String definition){
this.title = title;
this.definition = definition;
}
}
Here is my glossary_single_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="16sp"
android:layout_margin="4dp"
android:id="#+id/glossary_title_textview"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_description"
android:layout_margin="4dp"
android:textSize="12sp"
android:id="#+id/glossary_word_definition_textview"/>
</LinearLayout>
Here is my glossary_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#color/white"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:id="#+id/glossary_toolbar"
android:background="#color/colorPrimary"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:id="#+id/glossary_list_view"
android:layout_margin="8dp"
android:layout_below="#+id/glossary_toolbar"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
Please help when I execute I get only one TextView per row...
Apparently, I needed to change the text color to black in the second TextView. The text was there just not visible.
<LinearLayout xmlns:android="http:// schemas.android.com/apk/res/android" 
android:orientation="vertical"
android:layout_marginTop="10dp" 
android:layout_marginLeft="10dp"
  android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:text="#string/app_name"
android:textColor="#color/blue" 
android:textStyle="bold" 
android:textSize="16sp" android:layout_margin="4dp"
android:id="#+id/glossary_title_textview"/>
<TextView 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:text="#string/app_description"
android:layout_margin="4dp" 
android:textSize="12sp" 
android:textColor="#color/black"
android:id="#+id/glossary_word_definition_textview"/>
</LinearLayout

Set text inside fragment not working after revisiting fragment

I am developing an bus time table android app. I have three fragments.
Inside first fragment I have two radio buttons i.e. From Malegaon & To Malegaon. (Malegaon is name of place).
If I select From Malegaon radio button then I am setting text to sourceEditText as Malegaon. and If I select To Malegaon radio button then I am setting text to destinationEditText as Malegaon.
This condition is working fine, when I visit fragment first time, but if I revisit fragment then From Malegaon radio Button is already selected, sourceEditText is blank and destinationEditText has text as Malegaon.
Here is my snapshot and code for first fragment.
after selecting to Malegaon radio button.
I am just changing visibility of layout. (source edittext,destination edittext,search button is one layout)
OldStandFragment.java
public class OldStandFragment extends Fragment {
public static OldStandFragment fragment ;
private static final String ARG_POSITIONS = "position";
private int positions;
private View myFragmentViewOld;
private LinearLayout fromOldMalegoanView, toOldMalegoanView;
Button selectRouteButton;
public static final String required_dest = "Please Enter Destination";
public static final String required_source = "Please Enter Source";
String language = "";
DbHelper helper;
private String sourceId = "", destinationId = "";
private ArrayList<Route> myArrayList;
private RouteAdapter routeAdapter;
private ListView routeListView;
private EditText sourceEditTextFromMalegoanOld;
private EditText destinationEditTextFromMalegoanOld;
private ImageButton searchFromMalegoanButtonOld;
private EditText sourceEditTextToMalegoanOld;
private EditText destinationEditTextToMalegoanOld;
private ImageButton searchToMalegoanButtonOld;
private RadioButton fromOldMalegoanRadioButton, toOldMalegoanRadioButton;
public OldStandFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
positions = getArguments().getInt(ARG_POSITIONS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentViewOld = inflater.inflate(R.layout.fragment_old_stand, container, false);
selectRouteButton = (Button) myFragmentViewOld.findViewById(R.id.selectRouteButton);
fromOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.fromOldMalegoanRadioButton);
toOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.toOldMalegoanRadioButton);
fromOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.fromOldMalegoanView);
toOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.toOldMalegoanView);
sourceEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.destinationEditText);
searchFromMalegoanButtonOld = (ImageButton) fromOldMalegoanView.findViewById(R.id.searchResultButton);
sourceEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.destinationEditText);
searchToMalegoanButtonOld = (ImageButton) toOldMalegoanView.findViewById(R.id.searchResultButton);
SharedPreferences prefs = getContext().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
int a = prefs.getInt("LangValue", 0);
if (a == 0) {
language = "English";
} else {
language = "मराठी";
}
helper = new DbHelper(getContext());
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
String stopValue = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue);
fromOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (fromOldMalegoanRadioButton.isChecked()) {
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
helper = new DbHelper(getContext());
String stopValue1 = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue1);
destinationEditTextFromMalegoanOld.setText("");
}
}
});
toOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toOldMalegoanRadioButton.isChecked()) {
fromOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.GONE);
toOldMalegoanView.setVisibility(View.VISIBLE);
helper = new DbHelper(getContext());
String stopValue2 = helper.getStopName("1", language);
destinationEditTextToMalegoanOld.setText(stopValue2);
sourceEditTextToMalegoanOld.setText("");
}
}
});
searchFromMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
searchToMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
return myFragmentViewOld;
}
public static OldStandFragment newInstance(int position) {
if(fragment == null) {
fragment = new OldStandFragment();
}
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITIONS, position);
fragment.setArguments(bundle);
return fragment;
}
}
fragment_old_stand.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:scrollbars="vertical"
tools:context="com.ashishkudale.malegoanagar.Fragments.OldStandFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Direction or Route"
android:gravity="center"
android:textColor="#FFFFFF"
android:id="#+id/Note"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_margin="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_ContainerOld"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="From Malegaon"
android:id="#+id/fromOldMalegoanRadioButton"
android:layout_marginLeft="5dp"
android:checked="false" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/fromOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To Malegaon"
android:id="#+id/toOldMalegoanRadioButton"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/toOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Select Route "
android:id="#+id/selectRouteButton"
android:background="#drawable/button_effect"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
this is Adapter to call fragment.
MyPagerAdapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Old Stand","New Stand", "Fare"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment fragment = null;
if(position ==0) {
fragment = OldStandFragment.newInstance(position);
}else if(position ==1 ){
fragment = NewStandFragment.newInstance(position);
} else if (position == 2) {
fragment = MapFragment.newInstance(position);
}
return fragment;
}
}
after revisiting OldStandFragment it look like this.
I checked with adding logs everywhere possible. And I found that after revisiting OldStandFragment, toOldMalegoanRadioButton.setOnClickListner() method is getting called.
Now I want to refresh fragment when I re-visit or any other way to solve this issue.
You have to use SharedPreferences to save state of checkbox, try this code
public class StackOne extends AppCompatActivity {
SharedPreferences prefs;
private RadioButton rButton1, rButton2;
private RadioGroup rg_ContainerOld;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_one);
prefs = PreferenceManager.getDefaultSharedPreferences(StackOne.this);
rButton1 = (RadioButton) findViewById(R.id.fromOldMalegoanRadioButton);
rButton2 = (RadioButton) findViewById(R.id.toOldMalegoanRadioButton);
rg_ContainerOld = (RadioGroup) findViewById(R.id.rg_ContainerOld);
GetSelectedRadioButton();
int k = prefs.getInt("rb1", 0);
if (k == 1) {
rButton1.setChecked(true);
sourceEditTextFromMalegoanOld.setText("");
} else if (k == 2) {
rButton2.setChecked(true);
sourceEditTextToMalegoanOld.setText("");
}
}
private void GetSelectedRadioButton() {
rg_ContainerOld.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.fromOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 1).commit();
break;
case R.id.toOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 2).commit();
break;
}
}
});
}
}
In your code you are dynamically setting checked state of radiobutton
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
thats why your radiobutton's oncheckedchanged method will get call. And thats why code in it.

Categories