sharedpreferences stringset value: How to remove in Android Studio.? - java

I have unchecked the checkbox(per item) to remove it . I am using to sharedpreferences with HashSet concept. I want to pass arraylist value from one page to another page. What i do what is my mistake some one help me.
My code is:
adapterpage.java
public static final String MY_PREFS_NAME = "";
#Override
public void onClick(View view) {
boolean isChecked = mainHolder.chekenitem.isChecked();
// arr=getResources().getStringArray( mainHolder.txtenimgid.getText().toString());
// boolean isChecked = mainHolder.chekenitem.isChecked();
int i;
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
// editor.putString("key_name",itemId );
// editor.apply();
// }
} else {
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
// set.remove(addmembers);
addmembers.remove(k);
edit.remove(addmembers.get(k));
edit.commit();
break;
}
}

You are making mistake here ...
for (j = 0; j < addmembers.size(); j++) {
//set.addAll(addmembers);this will add every time whole data of list into set
set.add(addmembers.get(j));
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
And also here while removing change to this...
edit.remove("yourKey");

Try this code:
public static final String MY_PREFS_NAME = "";
#Override
public void onClick(View view) {
boolean isChecked = mainHolder.chekenitem.isChecked();
// arr=getResources().getStringArray( mainHolder.txtenimgid.getText().toString());
// boolean isChecked = mainHolder.chekenitem.isChecked();
int i;
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
} else {
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
edit.remove("yourKey");
edit.commit();
}
}
what you have to do is that whenever the item is checked you are simply clearing the shared pref value. Hope it helps

thanks to all, i got the solution in my code working fine.
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
restart:
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
} else {
//editor.remove("username").commit();
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
addmembers.remove(k);
edit.remove("yourKey");
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
break restart;
}
}
}
}
catch (Exception ex){
ex.toString();
}
the code is working fine to me.

Related

How to display a different toast message on multiple instances of SpannableString?

I am getting data from a json file and I want to have a different toast (on click) for each spannable string on the textview.
It works but it only shows the same toast message for each spannablestring on the textview; specifically its only showing the very last currentLocation on the json file.
for(int k = 0; k < 8;k++) {
spannableString1 = new SpannableString("Destination: " + canningTownArrivals1.get(k).destinationName); //spannable string is in the scope of the for loop,
ClickableSpan clickableSpan1 = new ClickableSpan() {
#Override
public void onClick(View view1) {
for(int c = 0; c < 8; c++){
Toast.makeText(CanningTownActivity.this,canningTownArrivals1.get(c).currentLocation,Toast.LENGTH_LONG)
.show();
}
}
};
spannableString1.setSpan(clickableSpan1,0,canningTownArrivals1.get(k).length() + 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textViewResult1.append(spannableString1);
textViewResult1.append(
"\nTime: " + canningTownArrivals1.get(k).timeToStation + " mins\n");
textViewResult1.setMovementMethod(LinkMovementMethod.getInstance());
}
I want it to show a different currentLocation on each spannableString.
for(int k = 0; k < 8;k++) {
spannableString1 = new SpannableString("Destination: " + canningTownArrivals1.get(k).destinationName); //spannable string is in the scope of the for loop,
spannableString1.setSpan(createClickableSpan(canningTownArrivals1.get(k).currentLocation),0,canningTownArrivals1.get(k).length() + 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textViewResult1.append(spannableString1);
textViewResult1.append(
"\nTime: " + canningTownArrivals1.get(k).timeToStation + " mins\n");
textViewResult1.setMovementMethod(LinkMovementMethod.getInstance());
}
private ClickableSpan createClickableSpan(final String location) {
return new ClickableSpan() {
#Override
public void onClick(#NonNull View widget) {
Toast.makeText(CanningTownActivity.this,location,Toast.LENGTH_LONG)
.show();
}
};
}

How to get the index of the clicked ItemizedIconOverlay in OSM

How do i get the index position of the ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay when the user taps the icon? For example, when a user taps/clicks the first icon it should get the integer 0
List<GeoPoint> nodes = nodeCoordinates();
ArrayList<OverlayItem> anotherOverlayItemArray = new ArrayList<>();
Drawable newMarker = getResources().getDrawable(R.drawable.marker_node);
for(int i = 0; i < nodes.size(); i++) {
anotherOverlayItemArray.add(new OverlayItem("Road", "Nodes", nodes.get(i)));
anotherOverlayItemArray.get(i).setMarker(newMarker);
}
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<>(
this, anotherOverlayItemArray, null);
map.getOverlays().add(anotherItemizedIconOverlay);
There's an example here
https://github.com/osmdroid/osmdroid/blob/master/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/SampleMilitaryIconsItemizedIcons.java
ack, formatting issues....
`
itemOverlay = new ItemizedOverlayWithFocus<>(new ArrayList(),
new ItemizedIconOverlay.OnItemGestureListener() {
#Override
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
Toast.makeText(
context,
"Item '" + item.getTitle() + "' (index=" + index
+ ") got single tapped up", Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onItemLongPress(final int index, final OverlayItem item) {
Toast.makeText(
context,
"Item '" + item.getTitle() + "' (index=" + index
+ ") got long pressed", Toast.LENGTH_LONG).show();
return false;
}
}, context);
`

Compare String with Bubble Sort Algorithm

I have a program that will fetch several String from database (announcementId, and announcementTitle),
then for every string fetched from the database, I want to compare each of them (Compare all the fetched announcementId),
if the string (announcementId) has different value then it will create a new Button using the announcementTitle as it's(the button) value fetch from database.
I tried to learn how, and found out that bubble sort algorithm can be used in this case, but there is some error in the program.. Index out of bound exception..
Then I tried some code and tried to change the array, but it still didnt work.
Could you please take a look at my code and tell me where is the error and the best way to fix the error
This is my code :
myDb = new Database(ViewAllAnnouncement.this);
myDb.open();
totalAnnouncement = myDb.countHowManyAnnouncement(username);
String temp = Integer.toString(totalAnnouncement);
//Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show();
String[] announcementTitle = myDb.fetchMyAnnouncement(username);
String[] announcementId = myDb.fetchAnnouncementId(username);
for (int i = 0; i < totalAnnouncement; i++) {
for (int j = 0; j < totalAnnouncement - i; j++) {
if (j > 0 || j < totalAnnouncement-i) {
if (!announcementId[j].equals(announcementId[i])) {
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
}
}
}
}
myDb.close();
And this is my method to return the announcementId
public String[] fetchAnnouncementId(String Username) {
// TODO Auto-generated method stub
int i = 0;
String Query = "SELECT b." + ANNOUNCEMENT_ID + " FROM "
+ MS_GROUP_DETAIL + " a, " + MS_ANNOUNCEMENT_DETAIL + " b, "
+ MS_ANNOUNCEMENT + " c WHERE a." + GROUP_ID + " = b."
+ GROUP_ID + " AND b. " + ANNOUNCEMENT_ID + " = c."
+ ANNOUNCEMENT_ID + " AND a." + MEMBER_USERNAME + " =? ORDER BY b." +ANNOUNCEMENT_ID;
Cursor c = ourDatabase.rawQuery(Query, new String[] { Username });
String temp[] = new String[c.getCount()];
int iArray = c.getColumnIndex(ANNOUNCEMENT_ID);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
temp[i] = c.getString(iArray);
i++;
}
c.close();
return temp;
}
If bubble sort is the answer you must have misunderstood the question. I strongly recommend you just add
ORDER BY announcementId
to the end of your query. That way the database will sort by your column for you.
Edit
You could use
ORDER BY 1
to sort by the first column (and omit the name). And, then your code should look something like
for (int i = 0; i < totalAnnouncement - 1;) {
int j = i + 1;
for (; j < totalAnnouncement; j++) {
if (!announcementId[j].equals(announcementId[i])) {
break;
}
}
// j is the first value where the announcementId changes
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
i = j; // <-- assign j to i.
}

Create Preference dynamically

I am using this code to get a list of permission required by a specific application. I would like to create a Preference for each permission requested. How can I do this? The code is:
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(myPackageName, PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = packageInfo.requestedPermissions;
if ( requestedPermissions != null ) {
for (int i = 0; i < requestedPermissions.length; i++) {
permission.setSummary(requestedPermissions[i] + "\n");
}
}
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}
Mario i ´d like to know for what are you going to create preferences with the name of App´s permissions, but here you got a solution.
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(myPackageName, PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = packageInfo.requestedPermissions;
if ( requestedPermissions != null ) {
for (int i = 0; i < requestedPermissions.length; i++) {
//permission.setSummary(requestedPermissions[i] + "\n");
//method to create a preference with the name of your permission.
setPreference(this, requestedPermissions[i]);
}
}
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}
Method to create a preference .
public static void setPreference(Context context, String preferenceName)
{
SharedPreferences settings = context.getSharedPreferences(preferenceName, 0);
SharedPreferences.Editor editor = settings.edit();
//Add a key to this preference and his value.
editor.putString(preferenceName+"_value", "Value stored in preference called: " + preferenceName);
editor.commit();
}
create a method to read the value stored in your preferences
public static String getPreference(Context context, String preferenceName){
SharedPreferences settings = context.getSharedPreferences(preferenceName, 0);
return settings.getString(preferenceName+"_value", "");
}
then you can read values stored in your preferences, for example, read a value stored in a preference called
"android.permission.INTERNET"
:
Log.i("Preferences", getPreference(this,"android.permission.INTERNET"));
example Displayin data in Toast:
Toast.makeText(this, "the value stored in \"android.permission.INTERNET\" preference is: " + getPreference(this,"android.permission.INTERNET"), Toast.LENGTH_LONG).show();

Adding a item from another activity to ExpandableListView

I want to add a item to the child Today from another activity to the ExpandableListView. The activity where I want to add it is named LocHistory, here is a the code to add something to the list:
static void addListData(final Context context) {
List<NewsItem> list = listDataChild.get("Today");
NewsItem newsData = new NewsItem();
newsData = new NewsItem();
newsData.setHeadline("11.11111, 1.1111");
newsData.setSpeed("1.11KM/H");
newsData.setDirection("111");
newsData.setDate("11-1-1111 11:11:11");
list.add(0, newsData);
listDataChild.put("Today", list);
}
This is working when I have call the function in the same class (LocHistory). But when I call it in MainActivity like this:
public class MainActivity extends Activity {
Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button2 = (Button) this.findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LocHistory.addListData(getBaseContext());
}
});
}
}
Then there is nothing added to the list. Is it possible to add a item from another activity to ExpandableListView? I want if there's something added that the class LocHistory is not going to open, so I think startActivity with a intent is not a option here (but i'm not sure).
(The java sources can be found here:
MainActivity.java,
LocHistory.java,
NewsItem.java and
ExpandableListAdapter.java)
Edit:
As some guys on a other forum pointed out, I'm now using SharedPreferences. I'm using this code:
static void addListData (int TimeStamp, final String lat, final String lng, final String speed,
final String direction, final Context context){
int todaystamp = startOf("today");
int yesterdaystamp = startOf("yesterday");
String Datetime = DateFormat.format("dd-MM-yyyy kk:mm:ss", new Date(TimeStamp * 1000L)).toString();
SharedPreferences pref = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
if (TimeStamp >= todaystamp) {
editor.putString("Today", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp >= yesterdaystamp) {
editor.putString("Yesterday", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp < yesterdaystamp) {
editor.putString("Older", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
}
editor.commit();
}
But now I'm stuck with one problem, when I add a item to the SharedPreferences on the same key it will overwrite the previous data. How can I add data to the same key without overwriting the previous data? Is it maybe possible to first get the data and then join the item to the data after that add the data to the SharedPreferences?
For you last edit you can try this:
static void addListData(int TimeStamp, final String lat, final String lng,
final String speed, final String direction, final Context context) {
int todaystamp = startOf("today");
int yesterdaystamp = startOf("yesterday");
String Datetime = DateFormat.format("dd-MM-yyyy kk:mm:ss", new Date(TimeStamp * 1000L)).toString();
String location = "*headline=" + lat + ", " + lng + ";speed=" + speed
+ ";direction=" + direction + ";date=" + Datetime + ";";
SharedPreferences pref = context.getSharedPreferences("myPrefs",
MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
if (TimeStamp >= todaystamp) {
String today = pref.getString("Today",null);
if (today != null) {
StringBuilder str = new StringBuilder(today);
str.insert(0, location + ", ");
editor.putString("Today", str.toString());
} else {
editor.putString("Today", location);
}
} else if (TimeStamp >= yesterdaystamp) {
String yesterday = pref.getString("Yesterday",null);
if (yesterday != null) {
StringBuilder str = new StringBuilder(yesterday);
str.insert(0, location + ", ");
editor.putString("Yesterday", str.toString());
} else {
editor.putString("Yesterday", location);
}
} else if (TimeStamp < yesterdaystamp) {
String older = pref.getString("Older",null);
if (older != null) {
StringBuilder str = new StringBuilder(older);
str.insert(0, location + ", ");
editor.putString("Older", str.toString());
} else {
editor.putString("Older", location);
}
}
editor.commit();
}
This will ensure that it not overrides the key but append if it exists. (This is done by checking whether the SharedPreferences is not null for a specific key).
I use StringBuilder with the insert method in this case.

Categories