Hi i am new to Android development ,
How to show Custom Listview with check box in Android SDK. I need selected checkbox should be selected before no need to select.
For example i have a favarote view in that i selected some items previously should appear as selected when i have to go that view.
Please any one help me.
Thanks in advance
private void SaveSelections() {
// save the selections in the shared preference in private mode for the
// user
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settingsActivity.edit();
savedNames = getSavedItems();
prefEditor.putString(SETTING_TODOLIST, savedNames);
prefEditor.commit();
}
private String getSavedItems() {
String savedNames = "";
int count = this.listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (FPhoneListCheckboxAES.phonelist.get(i).getChecked() == true) {
if (savedNames.length() > 0) {
savedNames += ","
+ FPhoneListCheckboxAES.phonelist.get(i).getname();
savedPhoneno += ","
+ FPhoneListCheckboxAES.phonelist.get(i).getphoneNo();
} else {
savedNames += FPhoneListCheckboxAES.phonelist.get(i).getname();
savedPhoneno += FPhoneListCheckboxAES.phonelist.get(i)
.getphoneNo();
}
}
}
return savedNames;
}
check the link this will help u a lot
http://appfulcrum.com/2010/09/12/listview-example-3-simple-multiple-selection-checkboxes/
Related
I am working with SharedPrefrences. I have multiple shared preferences in pref. I am changing values 0 to n-1 in a loop while, other value is User Score. Maybe there is some problem with my using of commit(), but the value is not updated. Can you suggest what should I do?
SharedPreferences pref = getApplicationContext().getSharedPreferences("Scorepref", 0);
SharedPreferences.Editor editor = pref.edit();
for (int i = 0; i < mQuestionBank.length; i++) {
editor.putBoolean(Integer.toString(i), false);
editor.commit();
}
mAnswered.setText( "0/" +Integer.toString(mQuestionBank.length));
mScoreval = 0;
mAnswered_count=0;
editor.putInt("User_score", 0);
editor.commit();
mScore.setText("0");
You didn't show us the code how you're trying read the data from prefs but anyway in your case, if you're not able to read the data by prefs.getBoolean then you can iterate over pref.getAll() like:
if (pref.getAll() != null) {
for (int i = 0; i < mQuestionBank.size(); i++) {
if (pref.getAll().get(String.valueOf(i)) instanceof Boolean) {
final Boolean yourSavedBoolean = (Boolean) pref.getAll().get(i);
}
}
}
Or if you need only one value then:
if (pref.getAll() != null) {
Boolean yourSavedBoolean = false;
if (pref.getAll().get("0") != null && pref.getAll().get("0") instanceof Boolean) {
yourSavedBoolean = (Boolean) pref.getAll().get("0");
}
}
I want to know the best way to save and restore checked items, using on adapter the "simple_list_item_checked", I've been trying for a long time using SharedPreferences, but didn't work. Could you give me some examples? Thanks in advance!
Here, found my old code for you. You can use SparseBooleanArray for this.
private SparseBooleanArray sbArray;
//set all of the items checked in the start
if (sbArray == null) {
for (int i = 0; i < listView.getCount(); i++) {
listView.setItemChecked(i, true);
}
}
selectedIdees = new ArrayList<>();
//if we already did some checking in filters, we get our previous selections.
if (sbArray != null) {
Log.i(LOG_TAG, "sbArray size " + sbArray.size());
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key)) {
listView.setItemChecked(key, true);
}
Then somewhere I placed okButton and set onClickListener to it.
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sbArray = listView.getCheckedItemPositions();
Log.i(LOG_TAG, "sbArray created. size= " + sbArray.size());
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key)) {
selectedIdees.add(key + 1);
Log.i(LOG_TAG, "added + " + (key + 1));
}
Then I suggest to save it in shared prefs, creating the parcelable wrapper around it.
Am just wondering if there is a way to save data into a text file without being overwritten.
Currently i am using sharedpreferences and it overwrites the data which is okay but coinciding with this, i want somewhere where i can keep record of the value before being overwritten in a list or column form.
So it goes something like this:
60, 65, 70..etc
The values are stored one after another without being overwritten. I am thinking of doing this locally in a text file which can be read as well.
I am doing this so i can create a stats page or something like that.
I hope someone can help me find a solution.
My code:
public class workout extends Activity {
TextView weightresultText, newweightresultText, difficultyrating;
Boolean male, strength;
double newweight, newweight1;
int weight, age;
Button button, button4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
button = (Button) findViewById(R.id.button);
button4 = (Button) findViewById(R.id.button4);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
weight = Integer.parseInt(sharedPreferences.getString("storedweight", "Your Weight"));
age = Integer.parseInt(sharedPreferences.getString("storedage", "Your Age"));
male = sharedPreferences.getBoolean("is_male", false);
strength = sharedPreferences.getBoolean("is_strength", false);
weightresultText = (TextView) findViewById(R.id.weightresultLabel);
newweightresultText = (TextView) findViewById(R.id.newweightresultLabel);
difficultyrating = (TextView) findViewById(R.id.difficultylevel);
if (sharedPreferences.getBoolean("firstrun", true)) {AgeCalculation();
sharedPreferences.edit().putBoolean("firstrun", false).commit();}
AfterFirstLaunch();
}
public void SaveWeight(){
savePreferences("storednewweight", (Double.toString(newweight)));
}
//Should only happen on first launch.
public void AgeCalculation() {
if (strength == true){
if (male == true && age >= 18) {
newweight = (weight * 0.8);
}
if (male == true && age >= 30) {
newweight = (weight * 0.6);
}
if (male == true && age >= 50) {
newweight = (weight * 0.4);
}
if (male == true && age >= 70) {
newweight = (weight * 0.2);
}
if (male == true && age > 80) {
newweight = (weight * 0.1);
}
if (male == false && age >= 20 ){
newweight = (weight * 0.3 );
}
weightresultText.setText(Double.toString(newweight));
SaveWeight();
}}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
// On every other launch, it is based on button, the newweight is saved and loaded each time.
public void buttonClick1(){
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 5;
//saves value into sharedpreference
savePreferences("storednewweight", (Double.toString(newweight1)));
//save to shared preference, and load value on new launch?
//also store into local database for review later.
difficultyrating.setText("1");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
public void buttonClick4(){
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 10;
//saves value into sharedpreference
//save to text file in array
savePreferences("storednewweight", (Double.toString(newweight1)));
difficultyrating.setText("2");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
//runs on every other launch
public void AfterFirstLaunch(){
buttonClick1();
buttonClick4();
//receive value on other launches and show on field.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
weightresultText.setText(newweight);
}
}
For something like this, where you're storing multiple entries of similar data, you'd really want to use an SQL database with a content provider. You'd just create new rows for each entry.
For writing into a textFile with overwritten use the following code
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/SO/";
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
File logFile = new File(path + "filename.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append("Message");
buf.newLine();
buf.flush();
buf.close();
Make sure you have permission defined in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have a listview with choice mode, and it working. I want to save that checked item to shared preference, then use it in another activity. But, my SharedPreferences doesn'nt save my string correct, and save another file call DATA_Preferences that i never call in my code.
The result is my Next activity get wrong value..
Here is my code that i use to save my string and call it use by another activity:
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<DBLokasi> selectedItems = new ArrayList<DBLokasi>();
// Item position in adapter
SharedPreferences prefs = getSharedPreferences("DATA_COOR", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
// Add slected if truee
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
prefsEditor.putFloat(POINT_LATITUDE_KEY + i, Float.parseFloat(values.get(position).getLat()));
prefsEditor.putFloat(POINT_LONGITUDE_KEY + i, Float.parseFloat(values.get(position).getLng()));
}
prefsEditor.commit();
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = String.valueOf(selectedItems.get(i));
}
Bundle b = new Bundle();
Location location = new Location("POINT_LOCATION");
for (int i = 0; i < checked.size(); i++) {
location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY + i, 0));
location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY + i, 0));
double latitude = prefs.getFloat(POINT_LATITUDE_KEY + i, 0);
double longitude = prefs.getFloat(POINT_LONGITUDE_KEY + i, 0);
prefsEditor.commit();
b.putDouble("Latitude" + i, latitude );
b.putDouble("Longitude" + i, longitude);
}
int banyakPilih = checked.size();
b.putInt("banyakPilih", banyakPilih);
Intent intent = new Intent(getApplicationContext(),
HasilPilihanActivity.class);
// Create a bundle object
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
I save my Prefernces in DATA_COOR.xml file name, it save my string, but i got another file that save my preference with file name DATA_Preferences in my Explorer. Some body can give me solution? Thanks before..
Define private SharedPreferences mediaPrefs = null;
put this on your constructor mediaPrefs = this.getSharedPreferences("Testing", 1);
put below method to the source:
public void storeStateString(String prefsKeys, Float prefsValue) {
SharedPreferences.Editor prefEditor = mediaPrefs.edit();
prefEditor.putFloat(prefsKeys, prefsValue);
prefEditor.commit();
}
Use this method to store the state like:
storeStateString("POINT_LATITUDE_KEY"+i,Float.parseFloat(values.get(position).getLat()));
and now you can get this preference through:
Float finalValue = mediaPrefs.getFloat("POINT_LATITUDE_KEY1","2.0l");
where 2.0l is defalut value if mediaPrefs is null;
Let me know if any issues regarding that.
I have a dynamic listview with one text and one checkbox per line.when i click a button.,i need to get all checked item names & Unchecked item names separately as arraylilst.How could i do that.Examples are much better..
I used..
SparseBooleanArray checked = mainlw.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i) == true) {
Planet tag = (Planet) mainlw.getItemAtPosition(checked.keyAt(i));
String selectedName=tag.getName();
Toast.makeText(getApplicationContext(), selectedName, Toast.LENGTH_SHORT).show();
}
}
Try this out and implement this logic according to your requirement.
int cntChoice = myList.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i) == true)
{
checked += myList.getItemAtPosition(i).toString() + "\n";
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked+= myList.getItemAtPosition(i).toString() + "\n";
}
}
use CHOICE_MODE_MULTIPLE in your ListView and use getCheckedItemPositions() to get the checked ones.
So Onclick of button u can do this,From this you will get the items that are checked:-
#Override
public void onClick(View v)
{
System.out.println("check"+getListView().getCheckItemIds().length);
for (int i = 0; i < getListView().getCheckItemIds().length; i++)
{
System.out.println(getListView().getAdapter().getItem((int)getListView().getCheckItemIds()[i]).toString());
}
}