Hi i have trouble in achieving pagination for listview in android. My task is to add Values from editTextto ListView and i need to add pagination to the list. But I tried and i am to insert only one value . While i try to add next values i end up in errors. Please kindly tell me the error on my code. i have added my layout,Activity and Log
MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/agnes2_back"
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.vivek.projectone.MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/border" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:layout_marginTop="15dp"
android:gravity="right"
android:text="#string/welcome"
android:textColor="#58FA58" />
<TextView
android:id="#+id/userView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"
android:text="#string/userLabel"
android:textColor="#FF0000" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearlayout2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_below="#+id/linearLayout1"
android:layout_marginTop="14dp"
android:background="#drawable/border"
android:orientation="horizontal" >
<EditText
android:id="#+id/itemName"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<Button
android:id="#+id/addButton1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/adds"
android:text="" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_alignLeft="#+id/linearlayout2"
android:layout_below="#+id/linearlayout2"
android:layout_marginTop="16dp"
android:background="#drawable/border"
android:orientation="horizontal" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="184dp"
android:layout_weight="2.32"
android:background="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"
tools:listitem="#android:layout/simple_list_item_checked" >
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="#+id/linearLayout3"
android:layout_alignParentBottom="true"
android:layout_below="#+id/linearLayout3"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_Prev"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_marginTop="10dp"
android:background="#drawable/buttonbackground"
android:text="#string/btn_prev" />
<Button
android:id="#+id/btn_Next"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:background="#drawable/buttonbackground"
android:text="#string/btn_next" />
</LinearLayout>
</RelativeLayout>
MainActivity.java
public class MultipleActivity extends Activity implements OnItemClickListener {
Button addToList;
EditText viewListItem1, viewListItem2;
ListView customItemList;
PackageManager packageManager;
ArrayList<String> checkedCustomItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple);
addToList = (Button) findViewById(R.id.adToListBtn);
viewListItem1 = (EditText) findViewById(R.id.viewEditItem1);
viewListItem2 = (EditText) findViewById(R.id.viewEditItem2);
packageManager = getPackageManager();
final List<PackageInfo> packageList = packageManager
public class MainActivity extends Activity {
String userLabel;
EditText itemName;
Button addBut;
Button multipleBtn;
ListView itemList;
private ArrayList<String> itemAList;
ArrayAdapter<String> itemAdapter;
private int pageCount;
private Button buttonPrev;
private Button buttonNext;
private int increment = 0;
public int TOTAL_LIST_ITEMS = 1030;
public int NUM_ITEMS_PAGE = 5;
String item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.userView);
itemName = (EditText) findViewById(R.id.itemName);
addBut = (Button) findViewById(R.id.addButton1);
buttonNext = (Button) findViewById(R.id.btn_Next);
buttonPrev = (Button) findViewById(R.id.btn_Prev);
itemList = (ListView) findViewById(R.id.listView1);
buttonPrev.setEnabled(false);
multipleBtn = (Button) findViewById(R.id.multipleValsBtn);
int val = TOTAL_LIST_ITEMS % NUM_ITEMS_PAGE;
val = val == 0 ? 0 : 1;
pageCount = TOTAL_LIST_ITEMS / NUM_ITEMS_PAGE + val;
Intent intent = getIntent();
userLabel = intent.getExtras().getString("emailID");
textView.setText(userLabel);
itemAList = new ArrayList<>();
itemAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, itemAList);
itemList.setAdapter(itemAdapter);
itemList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
item = itemAList.get(arg2);
Toast.makeText(getApplicationContext(), item, 0).show();
}
});
buttonNext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
increment++;
loadList(increment);
CheckEnable();
}
});
buttonPrev.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
increment--;
loadList(increment);
CheckEnable();
}
});
addBut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
item = itemName.getText().toString();
itemAList.add(0, item);
loadList(0);
itemName.setText("");
}
});
multipleBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
MultipleActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void CheckEnable() {
if (increment + 1 == pageCount) {
buttonNext.setEnabled(false);
} else if (increment == 0) {
buttonPrev.setEnabled(false);
} else {
buttonPrev.setEnabled(true);
buttonNext.setEnabled(true);
}
}
private void loadList(int number) {
ArrayList<String> sort = new ArrayList<String>();
int start = number * NUM_ITEMS_PAGE;
for (int i = start; i < (start) + NUM_ITEMS_PAGE; i++) {
if (i < itemAList.size()) {
sort.add(itemAList.get(i));
} else {
break;
}
}
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
itemList.setAdapter(itemAdapter);
}
}
You need to use setAdapter only once. For changing the list item next time (for loading next 5 items), you just need to use next notifyDataSetChanged
private void loadList(int number) {
ArrayList<String> sort = new ArrayList<String>();
int start = number * NUM_ITEMS_PAGE;
for (int i = start; i < (start) + NUM_ITEMS_PAGE; i++) {
if (i < itemAList.size()) {
sort.add(itemAList.get(i));
} else {
break;
}
}
if(itemAdapter ==null){
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
itemList.setAdapter(itemAdapter);
}
else{
itemAdapter.notifyDataSetChanged();
}
}
Though I didn't get what you are doing, but try to do this change:
Remove this line
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
or Add add one more line below this line
itemList.setAdapter(itemAdapter);
Because you have already called :itemAdapter.notifyDataSetChanged(); it should update the list.
Related
My app that I am creating has two listviews. My second listview does not look the same as my second one. The lines that seperate each item are too close to the text, but I want them to have space on both the top and bottom, like the first list. I have tried to change the padding and the margins but that does not works and I have also tried to change it in one of the Java classes but I get error messages.
Here are two pictures for comparison(The first list is on the left and the second list is on the right)
The second list:
<ListView
android:id="#+id/countryselector"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_above="#+id/checkItem"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="60dp"
android:clickable="false"/>
<TextView
android:id="#+id/checkboxtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/emptyElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="NO ITEM AVAILABLE!"
android:textColor="#525252"
android:textSize="19.0sp"
android:visibility="gone" />
<Button
android:id="#+id/checklist"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentTop="true"
android:gravity="end"
android:layout_alignParentLeft="true"
android:text=""
android:background="#mipmap/arrow2"
My first list:
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="left"
android:text="Favorites"
android:textColor="#222"
android:textSize="15dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="2dp"
android:textStyle="normal" />
<Button
android:id="#+id/tofavorites"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentTop="true"
android:gravity="end"
android:layout_alignParentLeft="true"
android:text=""
android:background="#mipmap/arrow2" />
<ListView
android:layout_marginTop="60dp"
android:id="#+id/countrieselector"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:clickable="false" />
<TextView
android:id="#+id/checkboxtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Here Is my adapter class for the second list:
public class AdapterFavorite extends BaseAdapter {
ArrayList<String> items;
ArrayList<String> items1;
LayoutInflater inflater;
ArrayList selectedItems;
List<Item> dummyItems;
ArrayList<Integer> itemsValue = new ArrayList<>();
Activity activity;
DbUtility dbUtility;
Context context;
AdapterFavorite(Activity activity, ArrayList<String> items, Context context) {
this.items = items;
inflater = activity.getLayoutInflater();
selectedItems = new ArrayList<String>();
this.activity = activity;
this.context = context;
dbUtility = new DbUtility(activity);
}
#Override
public int getCount() {
return items.size();
}
#Override
public String getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
dbUtility.open();
View v = view;
if (v == null) {
v = inflater.inflate(R.layout.checkboxlayoutfavorite, null);
}
TextView textview_countries = (TextView) v.findViewById(R.id.Textview_languages);
Button button = (Button) v.findViewById(R.id.checkbox);
items1 = new ArrayList<>();
textview_countries.setText(items.get(i));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
////Where I tried to add/move items when the checkbox is clicked
dbUtility.delete_byID(items.get(i));
items.remove(i);
notifyDataSetChanged();
}
});
return v;
}
}
Here is my main Java class for the second listL:
ublic class FavoriteActivity extends AppCompatActivity {
DbUtility dbUtility;
List<Item> dummyItems = new ArrayList<>();
Button mainList;
KeyboardPrefManager keyboardPrefManager;
ArrayList<String> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ListView chl = (ListView) findViewById(R.id.languageselector);
mainList = (Button) findViewById(R.id.checklist);
chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
items = new ArrayList<>();
dbUtility = new DbUtility(this);
dbUtility.open();
dummyItems = dbUtility.getAllContacts();
keyboardPrefManager = new KeyboardPrefManager(this);
for (int a = 0; a < dummyItems.size(); a++) {
items.add(dummyItems.get(a).getValue());
}
mainList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FavoriteActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
AdapterFavorite adapter = new AdapterFavorite(this, items, this);
chl.setAdapter(adapter);
chl.setEmptyView(findViewById(R.id.emptyElement));
chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String item = items.get(i); // Getting the dummy item from the List with position i
Toast.makeText(FavoriteActivity.this, "Clicked on " + item, Toast.LENGTH_SHORT).show();
keyboardPrefManager.selectKeyboard(item);
}
});}}
Please check your list item xml for both list same or not.Thanks
I use volley library to get data from database i use this code
public class R_arabic extends AppCompatActivity {
RequestQueue requestQueue;
ListView listView;
ArrayList<listitem_gib> listitems = new ArrayList<listitem_gib>();
String name, img, url, num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_arabic);
listView = (ListView) findViewById(R.id.listView);
TextView textView_Title = (TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
String story_type = intent.getStringExtra("story_type");
switch (story_type) {
case "arabic":
textView_Title.setText("arabic");
break;
case "romance":
textView_Title.setText("romance");
break;
case "motrgm":
textView_Title.setText("motrgm");
break;
case "ro3b":
textView_Title.setText("ro3b");
break;
case "siasa":
textView_Title.setText("siasa");
break;
}
String url = "http://grassyhat.com/android/" + story_type + ".php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
listitems.add(new listitem_gib(id, name, img, url, num));
}
} catch (JSONException e) {
e.printStackTrace();
}
listAllItme();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(R_arabic.this, "no connection", Toast.LENGTH_LONG).show();
} else {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
showad++;
if (showad >= 5) {
showad = 0;
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
i want to add progress bar while data loading to avoid blank page
sorry i'm new in android and i google for that and don't get useful answer
<?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"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kamal.ahmed.rewaya.R_arabic"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#drawable/bg"
tools:showIn="#layout/app_bar_r_arabic">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:id="#+id/textView2" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingRight="#dimen/activity_horizontal_margin"
android:divider="#drawable/div1"
android:dividerHeight="35dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="gone">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
Add progressBar in your activity_r_arabic
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
add ProgessBar progressBar; as global variable in your activity
and initialise it as
progressBar = (ProgessBar) findViewById(R.id.progress_bar);
and then In onResponse(JSONObject response) method add following line
progressBar.setVisibility(View.GONE)
EDIT
Make your linearLayout visible in xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
and inside onResponse(JSONObject response) method add following line
progress_layout.setVisibility(View.GONE)
I am trying to make an activity that provides a list of emergency phone numbers with the ability for the user to add their own custom entries and save them. For some reason, the ListView doesn't appear on the activity. I'm pretty sure I'm doing something wrong in the CustomAdapter class that I made to hold two text boxes in each segment of the ListView.
I'm also trying to set the listView to start a phone activity with the phone number of whatever segment was touched, and I'm unsure if I'm doing this correctly.
PhoneList.java :
public class PhoneList extends AppCompatActivity {
ArrayList<String> customList;
ArrayList<String> numList;
Bundle b;
TinyDB tinydb;
CustomAdapter dataAdapter;
ListView phoneListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);
phoneListView = (ListView)findViewById(R.id.listViewPhone);
Integer num = null;
String label = "";
customList = null;
numList = null;
tinydb = new TinyDB(this);
Button saveContact = (Button)(findViewById(R.id.button4));
b = new Bundle();
customList = tinydb.getListString("label");
ArrayList<Integer> temp = tinydb.getListInt("num");
for(int i = 0; i < temp.size(); i++){
numList.add(temp.get(i).toString());
}
saveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText enteredLabel = (EditText)findViewById(R.id.editText2);
EditText enteredNum = (EditText)findViewById(R.id.editText);
String label = enteredLabel.getText().toString();
Integer num = Integer.parseInt(enteredNum.getText().toString());
b.putString("label",label);
b.putInt("num",num);
addPhoneItem();
}
});
ArrayList<String> phoneList = new ArrayList<>();
phoneList.add("Emergencies");
phoneList.add("Travel Info ");
phoneList.add("Poison Control ");
phoneList.add("AAA: 1(800)836-2582");
if(customList != null && customList.size() > 0) phoneList.addAll(customList);
ArrayList<String> numberList = new ArrayList<>();
numberList.add("911");
numberList.add("511");
numberList.add("18002221222");
numberList.add("18008362582");
if(numList != null && numList.size()>0) {
for (int i = 0; i < numList.size(); i++) {
numberList.add(numList.get(i).toString());
}
}
dataAdapter = new CustomAdapter(this,numberList,phoneList);
phoneListView.setAdapter(dataAdapter);
}
public void addPhoneItem(){
customList.add(b.getString("label"));
numList.add(b.getString("num"));
tinydb.putListString("label",customList);
tinydb.putListString("num",numList);
dataAdapter = new CustomAdapter(this,numList,customList);
phoneListView.setAdapter(dataAdapter);
}
private class CustomAdapter extends ArrayAdapter<String> {
ArrayList<String> labels;
ArrayList<String> nums;
Context context;
public CustomAdapter(Context context, ArrayList<String> n,ArrayList<String> l) {
super(context,R.layout.phone_item);
this.context = context;
labels = new ArrayList<String>();
labels.addAll(l);
nums = new ArrayList<String>();
nums.addAll(n);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.phone_item, null);
holder = new ViewHolder();
holder.viewLabel = (TextView) convertView.findViewById(R.id.editText);
holder.viewNumber = (TextView) convertView.findViewById(R.id.editText2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String label = labels.get(position);
String num = nums.get(position);
holder.viewLabel.setText(label);
holder.viewNumber.setText(num);
holder.viewNumber.setTag(num);
holder.viewNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "tel:" + (EditText) v.getTag();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(str));
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getContext(),"Exception Caught in CustomAdapter",Toast.LENGTH_SHORT).show();
}
}
});
}
catch(Exception e){
Toast.makeText(getContext(),"Exception caught",Toast.LENGTH_SHORT).show();
}
return convertView;
}
}
private class ViewHolder{
TextView viewLabel;
TextView viewNumber;
}
}
activity_phone_list.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: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.rvtripapp.dempsey.rvtripapp.PhoneList">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="#+id/listViewPhone"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:editable="true"
android:hint="Label" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Phone Number" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/button4"
android:textSize="40dp"
android:background="#44fe66"
android:layout_alignBottom="#+id/editText2"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView" />
</RelativeLayout>
phone_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView3" />
</LinearLayout>
Any help is much appreciated, thank you.
Change the super keyword line to
super(context,R.layout.phone_item, n);
Have you tried to override the getCount method of the CustomAdapter class ?
#Override
public int getCount() {
return labels.size();
}
You are setting your custom adapter outside onCreate() try to set it inside the onCreate().
I am new over...
My question is: how to obtain the data from the edittext in fragments? I have really tried everything I have been seeking and no result.
Here is the code:
XML Files
register_user.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include layout="#layout/toolbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/secondary_dark"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
fragment_pdata.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.fundacioncanihua.inutritionist.rnp.Fragments.PersonalDataFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pData"
android:layout_marginTop="10dp"
android:textSize="40dp"
android:textStyle="bold"
android:id="#+id/textView"/>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_lastname"
android:theme="#style/TextLabel"
android:layout_below="#+id/textView"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_lName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/lName"
android:inputType="text"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_user"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_firstname"
android:theme="#style/TextLabel"
android:layout_below="#+id/flayout_lastname"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_fName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/fName"
android:inputType="text|textCapWords"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_user"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<LinearLayout android:layout_width="match_parent"
android:id="#+id/fHorizontal"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/flayout_firstname"
android:layout_marginTop="10dp">
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_birthday"
android:theme="#style/TextLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/birthday"
android:inputType="date"
android:drawableLeft="#drawable/ic_edittext_bd"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_gender"
android:theme="#style/TextLabel"
android:layout_width="150dp"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/gender"
android:inputType="text|textCapSentences"
android:maxLength="1"
android:drawableLeft="#drawable/ic_edittext_gender"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel"
android:layout_below="#id/fHorizontal"
android:layout_marginTop="10dp">
<EditText
android:id="#+id/input_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/location"
android:inputType="text|textCapWords"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_location"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
Java Classes
Register Patient
public class RegisterPatient extends AppCompatActivity implements PersonalDataFragment.getEditText {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_data,
R.drawable.ic_tab_measures,
R.drawable.ic_tab_clinical
};
String s_lname;
private ConnectionSQL dataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_user);
dataBase = new ConnectionSQL(getApplicationContext());
//Setting up the toolbar
Toolbar toolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case R.id.action_settings:
//Code
break;
case R.id.regbutton:
registerPatient();
break;
}
return super.onOptionsItemSelected(item);
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PersonalDataFragment(), getString(R.string.pData));
adapter.addFragment(new AnthropometryFragment(), getString(R.string.anthro));
adapter.addFragment(new NutritionalClinicalFragment(), getString(R.string.nutcli));
viewPager.setAdapter(adapter);
}
private void registerPatient() {
try {
/*final String s_lName = i_lName.getText().toString();
final String s_fName = i_fName.getText().toString();
final String s_bday = i_bday.getText().toString();
final String s_gender = i_gender.getText().toString();
final String s_location = i_location.getText().toString();
dataBase.addPatient(s_lName, s_fName, s_bday, s_gender, s_location);*/
Toast.makeText(RegisterPatient.this, "Patient added successfully!", Toast.LENGTH_SHORT).show();
clearForm((ViewGroup) findViewById(R.id.registerlayout));
} catch (Exception e) {
Toast.makeText(RegisterPatient.this, "Something were wrong! Try it again.", Toast.LENGTH_SHORT).show();
Log.w("WARNING", e.getMessage());
Log.w("WARNING_INFO", e.getCause());
}
}
private void clearForm(ViewGroup group)
{
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
clearForm((ViewGroup)view);
}
}
#Override
public void onFragmentEditTextChanged(String lname) {
}
}
PersonalDataFragment.java
public class PersonalDataFragment extends Fragment{
public EditText editText;
public Calendar myCalendar;
public DatePickerDialog.OnDateSetListener uDate;
private getEditText listener = null;
public PersonalDataFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pdata, null);
//Calendar
editText = (EditText) v.findViewById(R.id.input_birthday);
final EditText i_lname = (EditText) v.findViewById(R.id.input_lName);
editText.setTextIsSelectable(true);
myCalendar = Calendar.getInstance();
uDate = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vi) {
// TODO Auto-generated method stub
new DatePickerDialog(getActivity(), uDate, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
//Getting EditTexts
i_lname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
if (listener != null) {
final String stg = i_lname.getText().toString();
listener.onFragmentEditTextChanged(stg);
Toast.makeText(getActivity(), stg, Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
#Override
public void onAttach(Context context) {
listener = (getEditText) context;
}
private void updateLabel() {
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
editText.setText(sdf.format(myCalendar.getTime()));
}
public interface getEditText {
public void onFragmentEditTextChanged(String lname);
}
}
I don't know what I am doing wrong. I need to get access to those EditText in order to user them and add the user to the SQLite DB but, as the EditText are in the Fragment, I cannot access them directly from the RegisterUser class.
Any ideas on how to solve this? I shall be really and deeply thankful.
Thanks in advance.
Try doing like this,
TextInputLayout FlayoutBirthday= (TextInputLayout) v.findViewById(R.id.flayout_birthday);
EditText i_lname = FlayoutBirthday.getEditText();
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.