Strikethrough an item on a Listview - android

I need to put a strikethrough on the text after the item has been checked. I found solutions that use setPaintFlags(descriptionView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);. I don't use a textview but instead use simple_list_item_multiple_choice for my listview so how do I solve this? Here is my entire code:
public class Surv_list extends Fragment {
final String[] OPSys = new String[]{"item1","item2","item3","item4"
};
ListView myList;
Button getChoice, clearAll;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice" ;
ArrayList<String> selectedItems = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listlay, container, false);
myList = (ListView)rootView.findViewById(R.id.list);
ListView list = (ListView) rootView.findViewById(R.id.list);
clearAll = (Button)rootView.findViewById(R.id.clearall);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_multiple_choice, OPSys);
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
list.setAdapter(adapter);
sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if(sharedpreferences.contains(MyPREFERENCES)){
LoadSelections();
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
SaveSelections();
}
});
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClearSelections();
}
});
return rootView;
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the user
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.myList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.myList.getItemAtPosition(i);
} else {
savedItems += this.myList.getItemAtPosition(i);
}
}
}
return savedItems;
}
private void LoadSelections() {
// if the selections were previously saved load them
if (sharedpreferences.contains(MyPREFERENCES.toString())) {
String savedItems = sharedpreferences.getString(MyPREFERENCES.toString(), "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter()
.getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
} else {
myList.setItemChecked(i, false);
}
}
}
}
private void ClearSelections() {
// user has clicked clear button so uncheck all the items
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myList.setItemChecked(i, false);
}
// also clear the saved selections
SaveSelections();
}
}
any help would be very much appreciated.

You can create a custom adapter for your list view and in the getview method of the adpater take the handle of textview . Based on your condition you can combine the already available code to strikeout the text view.

for making your own view attributes in list view, you have to make a custom Adapter other than using default adapter. there is no way you can do this using default adapter. here you can learn how to make custom adapter. also I would suggest you to use RecyclerView instead of ListView

Related

Android - Split String by lines

I'm trying to save the data of 4 variables on the SharedPreferences and load it to a list. My problem is that it shows all the data in the first line of the list. I wanted to split like: Everytime I click the save button I wanted to save the 4 variables and when I click it again and I want to save the new variables and display it a new line.
Showing All on the same index:
TubeDataFragment (save):
public class TubeDataFragment extends Fragment {
List<String> tubeData = new ArrayList<>();
public TubeDataFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tube_data, container, false);
final Spinner spinnerMaterial = (Spinner) view.findViewById(R.id.snipperMaterial);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, getResources().getStringArray(R.array.material));
myAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spinnerMaterial.setAdapter(myAdapter);
//controls
Button btn_saveTube = (Button) view.findViewById(R.id.btn_save_tube);
final EditText et_diameter = (EditText) view.findViewById(R.id.et_diameter);
final EditText et_clr = (EditText) view.findViewById(R.id.et_clr);
final EditText et_thickness = (EditText) view.findViewById(R.id.et_thickness);
//guarda dados do tubo
btn_saveTube.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tubeData.add(" Diameter: " + et_diameter.getText().toString());
tubeData.add(" Thickness: " + et_thickness.getText().toString());
tubeData.add(" CLR: " + et_clr.getText().toString());
tubeData.add(" Material: " + spinnerMaterial.getSelectedItem().toString());
StringBuilder stringBuilder = new StringBuilder();
int i = 1;
for(String data : tubeData)
{
stringBuilder.append(data);
stringBuilder.append(";");
if(i++ == tubeData.size())
{
stringBuilder.append("\n");
}
}
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("tubeData", stringBuilder.toString());
editor.commit();
}
});
return view;
}
}
ArchiveFragment (load)
public class ArchiveFragment extends Fragment {
public ArchiveFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_archive, container, false);
ListView tubeDataList = (ListView) view.findViewById(R.id.tubeData_list);
//load tube data
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
String tubeDataString = settings.getString("tubeData", "");
String[] tubeDataSplit = tubeDataString.split("\n");
List<String> tubeDataItems = new ArrayList<>();
for(int i=0; i<tubeDataSplit.length;i++)
{
tubeDataItems.add(tubeDataSplit[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, tubeDataItems);
// Assign adapter to ListView
tubeDataList.setAdapter(adapter);
return view;
}
}
Your if condition is wrong.
In TubeDataFragment, use below codes in onClick() method:
.............
..................
StringBuilder stringBuilder = new StringBuilder();
int i = 1;
for(String data : tubeData)
{
stringBuilder.append(data);
stringBuilder.append(";");
if(i == 4)
{
stringBuilder.append("\n");
i = 0;
}
i++;
}
...............
.......................

Can a Shared Preference be applied to custom ListView?

I have a shared preference in my Custom list view. I am using it to keep numbers on the button but I have a condition where the row disappears when the button becomes 0 but when I scroll down it returns to its old form and becomes visible to it's user again. Is it possible to apply the same logic for view in SharedPreference like to keep last situation?
My code is the following:
import static android.view.View.INVISIBLE;
public class MainActivity extends Activity {
public MyAdapter adapter;
Context context;
public ListView list;
public int t[];
public SharedPreferences prefs;
public SharedPreferences.Editor edit;
int [] btnNums={100,150,94,72,206,489,1481,731,131,91,145,137,662,770,196,351,258,131,180,1281};
int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
R.drawable.a10, R.drawable.a11, R.drawable.a12, R.drawable.a13, R.drawable.a14, R.drawable.a15, R.drawable.a16, R.drawable.a17, R.drawable.a18, R.drawable.a19, R.drawable.a20, R.drawable.a21};
String[] exp;
String[] mean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= this.getSharedPreferences("NAME", Context.MODE_APPEND).edit();
prefs = getSharedPreferences("NAME", Context.MODE_APPEND);
Resources res=getResources();
exp= res.getStringArray(R.array.names);
mean=res.getStringArray(R.array.anlam);
list= (ListView) findViewById(R.id.listView);
//
// edit.putInt("Count", btnNums.length);
// int count = 0;
// for (int i: btnNums){
// edit.putInt("IntValue_" + count++, i);
// }
// edit.commit();
//
int[] ret;
int count1 = prefs.getInt("Count", 0);
ret = new int[count1];
for (int i = 0; i < count1; i++){
ret[i] =prefs.getInt("IntValue_"+ i, i);
}
t=ret;
if(t!=null)
{
adapter=new MyAdapter(this,exp,images,mean,t);
}else
{
adapter=new MyAdapter(this,exp,images,mean,btnNums);
}
list.setAdapter(adapter);
context=getApplicationContext();
}
}
class MyAdapter extends ArrayAdapter<String>{
int [] images;
String [] titleArray;
String [] descriptionArray;
int [] btnNums;
MainActivity ma;
public MyAdapter(MainActivity m, String[] titles, int imgs[], String[] descp, int[] btnNum ){
super(m, R.layout.single_row, R.id.textView,titles);
this.images=imgs;
this.titleArray=titles;
this.descriptionArray=descp;
btnNums=btnNum;
this.ma=m;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater) ma.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row=inflater.inflate(R.layout.single_row, parent, false);
final TextView myTitle=(TextView)row.findViewById(R.id.textView);
myTitle.findViewById(R.id.textView);
final TextView descp=(TextView)row.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
final Button button = (Button) row.findViewById(R.id.angry_btn);
final Vibrator a = (Vibrator) ma.getSystemService(Context.VIBRATOR_SERVICE);
if(ma.t!=null)
{
for(int i=0; i<21;i++){
button.setText("" + ma.t[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}else
{
for(int i=0; i<21;i++){
button.setText("" + btnNums[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNums[position]--;
storeIntArray(btnNums);
a.vibrate(30);
if (btnNums[position] == 0) {
button.setEnabled(false);
button.setVisibility(INVISIBLE);
row.setVisibility(INVISIBLE);
}
int temp[]=getFromPrefs();
ma.t=temp;
for (int i = 0; i < 21; i++) {
button.setText("" + temp[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
});
return row;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public void storeIntArray(int[] array){
ma.edit.putInt("Count", array.length);
int count = 0;
for (int i: array){
ma.edit.putInt("IntValue_" + count++, i);
}
ma.edit.commit();
}
public int[] getFromPrefs(){
int[] ret;
int count = ma.prefs.getInt("Count", 0);
ret = new int[count];
for (int i = 0; i < count; i++){
ret[i] =ma.prefs.getInt("IntValue_"+ i, i);
}
return ret;
}
}
First, please format your code, so its more readable.
Question: Can a Shared Preference be applied to custom ListView?
Answer: Yes it possible to use/access shared preferences in a Listview.
Upon reading your code, I believe the problem lies in your implementation of Listview and its adapter. The reason why it gets back to original state when scrolled down. Please note, that GetView is always called when scrolling.
You can refer to this topic: ListView & ViewHolder Pattern.

How to remove SharedPreferences from Array

I have problem with removing items from ArrayList. I tried it maybe 100 times but I can't fix it. Saving to list isn't problem but it's very hard to remove for me.
When I remove SharedPrefs key (position) It's good first time but if I first time remove first position it's deleted from list but its still in preferences so when I try to remove first position second time I cant remove it because there is still saved preference with value "" but I need to remove this preference totally that first position have to contain preferences with value on second position not "".
I tried to make some images for better understanding.
Thats before remove 1st position:
And this is after remove 1st position
There is my CustomListAdapter class
public class CustomListAdapterInterests extends ArrayAdapter < String > {
private final Activity context;
private final ArrayList < String > mItemInterest;
public CustomListAdapterInterests(Activity context, ArrayList < String > itemInterest) {
super(context, R.layout.list_item_interests, itemInterest);
this.context = context;
this.mItemInterest = itemInterest;
}
#Override
public int getCount() {
return mItemInterest.size();
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item_interests, null, true);
TextView itemInterestTV = (TextView) rowView.findViewById(R.id.textInterest);
itemInterestTV.setText(mItemInterest.get(position));
return rowView;
}
}
And here is my fragment
public class InterestsFragment extends BaseFragment {
private ArrayList < String > mInterestList;
private static final int MAX_STORED_LINES_INTERESTS = 50;
private FloatingActionButton plusInterestsBTN;
private CustomListAdapterInterests adapterInterests;
private ListView listInterests;
private EditText interestET;
private Button confirmInterestBTN;
public SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_interests, container, false);
plusInterestsBTN = (FloatingActionButton) v.findViewById(R.id.plusInterests);
sharedPreferences = getActivity().getSharedPreferences(Constants.PREFERENCES_INTERESTS, Context.MODE_PRIVATE);
mInterestList = new ArrayList < String > ();
loadInterestFromPreferences(mInterestList);
adapterInterests = new CustomListAdapterInterests(getActivity(), mInterestList);
listInterests = (ListView) v.findViewById(R.id.listViewInterests);
listInterests.setAdapter(adapterInterests);
listInterests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > arg0, View v, int position, long arg3) {
if (sharedPreferences.contains(Constants.INTEREST + position)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}
}
});
listInterests.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {#Override
public boolean onItemLongClick(AdapterView <? > arg0, View arg1,
final int position, long id) {
onShowDialogSetItem(position);
return true;
}
});
plusInterestsBTN.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
onShowDialogAddItem();
}
});
listInterests.setOnScrollListener(new AbsListView.OnScrollListener() {#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = plusInterestsBTN.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationXBy(350);
} else {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationX(btn_initPosY);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
return v;
}
private void loadInterestFromPreferences(ArrayList < String > mInterestList) {
for (int x = 0; x < 5; x++) {
String interests = sharedPreferences.getString(Constants.INTEREST + x, Constants.DEFAULT);
Toast.makeText(getActivity(), interests, Toast.LENGTH_SHORT).show();
if (interests != "") {
mInterestList.add(interests);
}
}
}
private void onShowDialogSetItem(final int position) {
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
final EditText interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
Button confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
TextView title = (TextView) dialogInterest.findViewById(R.id.textView2);
title.setText("Edit Interest");
interestET.setText(mInterestList.get(position));
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("2", "" + position);
String interest = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
mInterestList.set(position, interestET.getText().toString());
Toast.makeText(getActivity(), "Upravené: " + interests, Toast.LENGTH_SHORT).show();
adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
}
private void onShowDialogAddItem() {
if (mInterestList.size() >= MAX_STORED_LINES_INTERESTS) {
return;
}
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = listInterests.getAdapter().getCount();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
Toast.makeText(getActivity(), "Přidané: " + interests, Toast.LENGTH_SHORT).show();
mInterestList.add(interestET.getText().toString());
//adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
adapterInterests.notifyDataSetChanged();
}
}
Thank you for help. Sorry for my English. If do you will help me I can do any material design app icon for you or google play designs. Thank you. If there is few informations please say me.
I think if you save all of your string list to single property of preferences will make it easy to manage.
see this sample:
//for save
StringBuilder sb = new StringBuilder();
for (String interest : mInterestList) {
sb.append(interest).append(",");
}
prefsEditor.putString("MyInterests", sb.toString());
prefsEditor.commit();
//for read
String [] interests= sharedPreferences.getString("MyInterests");
mInterestList = new ArrayList<String>(Arrays.asList(interests));
in every change to your mInterestList just save it again. no need to remove and adding. change your mInterestList and save again in shared preferences.
Looks to me like your adapter runs off of mInterestList .
I don't see you removing the data item from mInterestsList when your remove the Preference?
Rather than checking whether shared preferences contains, see if it is set to null instead or not, that is do,
if (sharedPreferences.getString(Constants.INTEREST + position)!=null) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}

how to check the toggle button state when list is refreshed or re-opening the app

my app contains a list view which is being populated by a spinner value
this list contains toggle button in each row and for customization purpose i have used baseadapter in list view
i am changing image of toggle button on checked and unchecked
the functionality is going well on toggle button and listview but the problem occurrs when i closes the app and then again opens it it gets refreshed and the toggle state become unchecked and the unchecked image is shown every where
so to solve this i have saved the value of toggle button in shared preferences but now i dont know where to check this in base adapter class plz help me
the necessary code for this
public class DDListAdapter extends BaseAdapter {
ArrayList<DataModelDD> listArray;
int curIndex=1000, pIndex;
public DDListAdapter(String[] str, String[] str1) {
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
}
public void DDListUpdate(String[] str, String[] str1){
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
this.notifyDataSetChanged();
}
#Override
public int getCount() {
return listArray.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return listArray.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
lIndex = index;
pIndex = index;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.lstdd, parent, false);
final DataModelDD dmFl = listArray.get(index);
final TextView lbl1 = (TextView) view.findViewById(R.id.txtDDate);
final TextView lbl2 = (TextView) view.findViewById(R.id.txtDres);
lbl1.setText(dmFl.getDDate());
lbl2.setText(dmFl.getDres());
final ToggleButton btnlock = (ToggleButton) view.findViewById(R.id.btnDAlarm);
if (dmFl.getdSel()) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}
btnlock.setTag(pIndex);
btnlock.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(btnlock.isChecked()){
btnlock.setButtonDrawable(a_icon);
btnlock.setChecked(true);
dmFl.setdSel(true);
Integer position = (Integer) buttonView.getTag();
sp = context.getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("value"+month+"_"+state+"_"+cday, true);
editor.commit();
}
else{
final String alarmTime = dmFl.getDDate();
disableAlarm(buttonView,alarmTime);
btnlock.setButtonDrawable(a_dicon);
btnlock.setChecked(false);
dmFl.setdSel(false);
Integer position = (Integer) buttonView.getTag();
}
}
});
return view;
}
}
and the data model class
package com.example.dd;
public class DataModelDD {
private String DDate;
private String Dres;
private String ShrStr;
private Boolean dSel;
public DataModelDD(String DDate, String Dres, String ShrStr, Boolean dSel){
this.DDate = DDate;
this.Dres = Dres;
this.ShrStr = ShrStr;
this.dSel = dSel;
}
public String getDDate(){
return this.DDate;
}
public void setDDate(String DDate){
this.DDate = DDate;
}
public String getDres(){
return this.Dres;
}
public void setDres(String Dres){
this.Dres = Dres;
}
public String getShrStr(){
return this.ShrStr;
}
public void setShrStr(String ShrStr){
this.ShrStr = ShrStr;
}
public Boolean getdSel(){
return this.dSel;
}
public void setdSel(Boolean dSel){
this.dSel = dSel;
}
}
you need to do
is
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0);
boolean rb0 = prefs.getBoolean("rb0", true);
if (dmFl.getdSel()||rb0) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}

Update the Value of the ListView Item In Android

I have a Listview that is showing a list .So on the click of the listview i have a customDialog.In that i am taking some values from the user.So want once the user enters the details and click on the ok button ,then i have to update the value of that item from the listview and when all the item of the listview has been updated then compare it with the previous value to check whether all the item are updated or not .Help me on this how could i do this
Activity Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_iween_booking_page);
intent = getIntent();
isReturn = (Boolean) intent.getExtras().get("isReturn");
searchParam = (HashMap<String,String>) intent.getExtras().get("searchParam");
listView = (ListView) findViewById(R.id.passengerList);
emailId = (TextView)findViewById(R.id.emailid);
continuebooking = (ImageView)findViewById(R.id.continuebooking);
firstName= (EditText)findViewById(R.id.firstName);
lastName =(EditText)findViewById(R.id.LastName);
mobileNumber =(EditText)findViewById(R.id.mobileNumber);
setTittle();
if(searchParam.get("NoOfChild").equals("0") && searchParam.get("NoOfInfant").equals("0")&& searchParam.get("NoOfAdult").equals("1")){
} else {
passengerList = getPassengerList(passengerInfo);
showPassengerListView(passengerList);
}
continuebooking.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(searchParam.get("NoOfChild").equals("0") && searchParam.get("NoOfInfant").equals("0") && searchParam.get("NoOfAdult").equals("1")){
if(firstName.getText().toString().trim().equalsIgnoreCase("")){
firstName.setError("Enter FirstName");
}
if(lastName.getText().toString().trim().equalsIgnoreCase("")){
lastName.setError("Enter LastName");
}
if(mobileNumber.getText().toString().trim().equalsIgnoreCase("")){
mobileNumber.setError("Enter Mobile No.");
}
}else{
int count = listView.getAdapter().getCount();
listData = new String[count];
for (int i = 0; i < count; i++) {
listData[i] = listView.getAdapter().getItem(i).toString();
}
for(int i=0;i<listView.getAdapter().getCount();i++){
for(int j=0;j<count;j++){
if(listData[j]==listView.getAdapter().getItem(i).toString()){
Log.d("listData data", listView.getAdapter().getItem(i).toString());
// View v=listView.getChildAt(i);
// TextView tv=(TextView) v.findViewById(android.R.id.text1);
// tv.setError("Please change the data");
}
}
}
}
}
});
}
private void showPassengerListView(final String[] passengerList) {
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, passengerList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// int itemPosition = position;
// String itemValue = (String) listView.getItemAtPosition(position);
View v=listView.getChildAt(position);
TextView tv=(TextView) v.findViewById(android.R.id.text1);
tv.setError(null);
passengerInformationPopup(passengerList,position);
}
});
}
public void passengerInformationPopup(final String[] passengerList, final int position) {
final Dialog dialog= new Dialog(Test.this,R.style.Dialog_Fullscreen);
dialog.setContentView(R.layout.passenger_details_dialog);
final EditText firstNameDialog;
final EditText lastNameDialog;
ImageView continueBooking;
dateofBirth = (TextView)dialog.findViewById(R.id.dateofBirth);
firstNameDialog = (EditText)dialog.findViewById(R.id.firstName);
lastNameDialog =(EditText)dialog.findViewById(R.id.LastName);
continueBooking =(ImageView)dialog.findViewById(R.id.continuebooking);
if((passengerList[position].contains("Child"))|| (passengerList[position].contains("Infant"))){
dateofBirth.setVisibility(View.VISIBLE);
}else{
dateofBirth.setVisibility(View.GONE);
}
dateofBirth.setClickable(true);
dialog.show();
continueBooking.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
isSuccess= true;
if(firstNameDialog.getText().toString().trim().equalsIgnoreCase("")){
firstNameDialog.setError("Enter FirstName");
isSuccess= false;
}
if(lastNameDialog.getText().toString().trim().equalsIgnoreCase("")){
lastNameDialog.setError("Enter LastName");
isSuccess= false;
}
if((passengerList[position].contains("Child"))|| (passengerList[position].contains("Infant"))){
if(dateofBirth.getText().toString().trim().equalsIgnoreCase("")){
dateofBirth.setError("Date of Birth Can't be blank");
isSuccess= false;
}
}
if(isSuccess){
dialog.cancel();
View v=listView.getChildAt(position);
TextView tv= (TextView) v.findViewById(android.R.id.text1);
tv.setText(firstNameDialog.getText().toString().trim().toString()+" "+lastNameDialog.getText().toString().trim().toString());
}
}
});
}
passengerInformationPopup function i have to update the items values of the ListView .In on create continueBooking i have to check whether all the items are updated or not
Before Updation
After Updation
Never update ListView items directly. Update data in your storage and call notifyDataSetChanged on your adapter.
You will need an ArrayAdapter with the data for your list. Then when you manipulate the data in that array you can call .notifyDataSetChanged(); on the adabter to refresh your view.
Be aware that it have to be the same arraylist! so you cant call arraylist = new ArrayList(); that will destroy the reference. Instead use arraylist.clear(); and then arraylist.addAll(data);
Here is an example:
public class GroupsListAdapter extends ArrayAdapter<Object> {
/**
* Constructor
*
* #param context
* Context
* #param objects
* Array of objects to show in the list.
*/
public GroupsListAdapter(Context context, ArrayList<Object> objects) {
super(context, R.layout.row, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Object = getItem(position);
/* Initialize strings */
String nameText = group.getName();
boolean upToDate = group.isUpToDate();
/* Get the layout for the list rows */
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row, parent, false);
}
rowView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//do stuff here
}
});
return rowView;
}
}

Categories

Resources