Cant find a way to delete an item from sharedPreferences - java

I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.
public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return i;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
Map<String, ?> tasks = taskPref.getAll();
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
for(int pos=0 ; pos<myTasks.size() ; pos++){
myTasks.get(pos);
}
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}
And my utlShared class is
public class utlShared {
//context to use later
Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;
public utlShared() {}
public utlShared(Context context)
{
//get context to use it
this.context=context;
//declaretion of shared preferences with file name and file mode (private,public)
userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
//declaration of editor
editor=userPref.edit();
}
//get user and password
public void addUser(String userName, String password)
{
//stores in the phone device under data\data\package name
//put in shared preferences user name and password
editor.putString(userName,password);
//commit (save/apply) the changes.
editor.commit();
}
public boolean checkUser(String userName)
{
//get name by key->userName
String checkString = userPref.getString(userName,"na");
//print to logcat a custom message.....
Log.e("checkUser", "checkUser: "+checkString );
//check if userName equals to responded data, if it's na, we don't have the user...
return !checkString.equals("na");
}
public boolean checkUserPassword(String userName, String userPassword)
{
String checkString = userPref.getString(userName,"na");
return checkString.equals(userPassword);
}
public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
//pointer to user task shared preferences
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
//create editor to change the specific shared preferences
SharedPreferences.Editor taskEditor=taskPref.edit();
//add new task -> if true write 1 else write 0
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
SharedPreferences.Editor tskEditor=taskPref.edit();
tskEditor.clear();
tskEditor.commit();
}
}
This method is called from my Welcome class which is
public class Welcome extends AppCompatActivity {
String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
setPointer();
}
private void setPointer()
{
this.context=this;
userName=getIntent().getStringExtra("userName");
myUtl = new utlShared(context);
taskList=(ListView)findViewById(R.id.taskList);
setListData();
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
Button btnBack = (Button)findViewById(R.id.btnBack);
FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
setListData();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
finish();
}
});
}
private void setListData() {
final TaskAdapter adapter = new TaskAdapter(context, userName);
taskList.setAdapter(adapter);
}
public void addCustomTask(View view)
{
//create builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//set title
builder.setTitle("Add new task!");
//inflate view from layout ->custom layout,null,false as defualt values
View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);
final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
String myTaskCustom = txtCustomTask.getText().toString();
String myTaskLine = txtCustomLine.getText().toString();
myUtl.task(userName, myTaskCustom, myTaskLine, false);
setListData();
}
});
//display our inflated view in screen
builder.setView(viewInflated);
//show the dialog
builder.show();
}
}
Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...
Thanks in advance guys, much appreciated!

taskEditor.remove('item tag');
taskEditor.commit();

Guess my question wasnt clear enough but I have found a way to do that.
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
else
{
taskEditor.remove(taskName);
taskEditor.commit();
adapter.notifyDataSetChanged();
}
Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.
Cheers and thanks a lot guys!

Related

How to make notification OnItemchange when a new item is displayed in the list

i made an app using java and retrofit2 to fetch datas from the server.My listview can only display 30 item. when a new item is displayed in the listView the last one is removed automatically and the new one is displayed on that listview.
my Event model :
public class Event {
public int id, user_id, device_id, position_id, alert_id;
// geofence_id
public String message;
public String address;
public float altitude;
// course
public float latitude, longitude;
// power
public float speed;
public String time;
// deleted
public String device_name, geofence_name;
}
my Event Activity:
public class EventsActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.list) ListView list;
#Bind(R.id.clearAllEvents) View clearAllEvents;
#Bind(R.id.content_layout) View content_layout;
#Bind(R.id.loading_layout) View loading_layout;
#Bind(R.id.nodata_layout) View nodata_layout;
#Bind(R.id.search) View search;
String searchtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
ButterKnife.bind(this);
final String api_key = (String) DataSaver.getInstance(EventsActivity.this).load("api_key");
final EventsAdapter adapter = new EventsAdapter(this);
list.setAdapter(adapter);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
#Override
public void success(ApiInterface.GetEventsResult result, Response response)
{
adapter.setArray(result.items.data);
loading_layout.setVisibility(View.GONE);
if(result.items.data.size() != 0)
content_layout.setVisibility(View.VISIBLE);
else
nodata_layout.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(EventsActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
}
my EventAdapter :
public class EventsAdapter extends AwesomeAdapter<Event> {
public EventsAdapter(Context context) {
super(context);
}
ArrayList<Event> original;
#Override
public void setArray(ArrayList<Event> array) {
super.setArray(array);
if(original == null)
original = array;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
Event item = getItem(position);
TextView device_name = (TextView) convertView.findViewById(R.id.device_name);
device_name.setText(item.device_name);
TextView date = (TextView) convertView.findViewById(R.id.date);
date.setText(item.time);
TextView message = (TextView) convertView.findViewById(R.id.message);
message.setText(item.message);
TextView geofence_name = (TextView) convertView.findViewById(R.id.geofence_name);
geofence_name.setText(item.geofence_name);
return convertView;
}
}
The problem is i would like to make a local notification when the new item is added in the server i can get a notification of the displayed item on the listview. i have tried to make something it's working but when starting my activity, the notifications don't stop coming. i don't know why, here is my example :
API.getApiInterface(this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
#SuppressLint("SetTextI18n")
#Override
public void success(ApiInterface.GetEventsResult result, Response response)
{
adapter.setArray(result.items.data);
if(result.items.data.size() != 0) {
layout_evennements.setVisibility(View.VISIBLE);
text_count.setText("Evennements recu:" + listview_evennements.getAdapter().getCount());
//to upload all list one to one together.
for(int i = result.items.data.size(); i <= result.items.data.size(); i++) {
int notificationId = new Random().nextInt(100);
String channelId = "notification_channel_1";
Event item = new Event();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(i > result.items.data.size()){
Intent intent = new Intent(MapActivity.this, EventActivity.class);
intent.putExtra("event", new Gson().toJson(listview_evennements.getItemAtPosition(0)));
startActivity(intent);
getIntent().addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
#SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext(), channelId
);
builder.setSmallIcon(R.drawable.ic_notification_original);
builder.setDefaults(NotificationCompat.DEFAULT_ALL);
builder.setContentTitle("GPSTrackr");
builder.setContentText("Evenement" + item.device_name);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
if(notificationManager != null && notificationManager.getNotificationChannel(channelId) ==null){
NotificationChannel notificationChannel = new NotificationChannel(
channelId, "Notification channel 1", NotificationManager.IMPORTANCE_HIGH
);
notificationChannel.setDescription("Notificatoins evenements");
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
}
Notification notification = builder.build();
if (notificationManager != null) {
notificationManager.notify(notificationId, notification);
}
}else if(i == result.items.data.size()){
MotionToast.Companion.darkColorToast(MapActivity.this, "Aucune Notification",
MotionToast.TOAST_INFO,
MotionToast.GRAVITY_CENTER,
MotionToast.SHORT_DURATION,
ResourcesCompat.getFont(MapActivity.this, R.font.helveticacompressed5871d14b6903a));
}
}
}else {
rien_a_voir.setVisibility(View.VISIBLE);
}
}
#Override
public void failure(RetrofitError retrofitError) {
rien_a_voir.setVisibility(View.VISIBLE);
layout_evennements.setVisibility(View.GONE);
}
});
my APIInterface:
#GET("/get_events")
void getEvents(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, #Query("page") int page, Callback<GetEventsResult> cb);
public static class GetEventsResult
{
public int status;
public GetEventsResultItems items;
public class GetEventsResultItems
{
public int total, per_page, current_page, last_page, from, to;
public ArrayList<Event> data;
}
}
if you have any solution please i need you help. thank you in advance.
I didn't understand the requirement clearly, but I can see that you are creating notifications in for loop which iterates for adapter.getCount times. You might want to move it outside of the for loop.

Radio button returns wrong value in Android

I have a form where a person can enter details about a friend (name, age, gender, address). This friend is displayed in a list view and when a friend from the list is clicked on they have the choice to edit that record.
I can successfully update every detail about a friend except for the gender.
For example:
List view:
1) James Bond, 20, Male, Sydney NSW
Then I click edit and change it to
James smith, 21, Female, Canberra NSW
and then back in my list view it will show:
1) James smith, 21, Male, Canberra NSW
Notice how the gender doesn't change?
I can figure out why this is happening as I use the same logic to change the name and age as i did to change the gender
Here is the relevant code:
ViewFriend.java ( this class displays the list view and has the edit option)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
String text = listView.getItemAtPosition(position).toString();
final int ID = Integer.parseInt(String.valueOf(text.charAt(0)));
AlertDialog.Builder builder = new AlertDialog.Builder(viewFriends.this);
builder.setTitle("Notice");
builder.setMessage("Please select to to edit, delete a friend or cancel");
// add the buttons
builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), editOrDelete.class);
ArrayList<String> result1 = mydb.retrieveRow(ID);
name = result1.get(1);
age = result1.get(2);
gender = result1.get(3);
address = result1.get(4);
code = result1.get(0);
intent.putExtra("code", code);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
startActivity(intent);
}
});
builder.setNeutralButton(" Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mydb.deleteTitle(ID);
finish();
Intent intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
The code above retrieves the details from the database and passes it to the intent. I have printed the contents of each variable (name, age, gender, address) and they print out correctly.
editFriend.java ( this class pre fills the form with the data passed through the intent that displays correctly)
public class editFriend extends AppCompatActivity {
private Intent intent;
private RadioGroup rg;
private Button update;
private RadioButton rb;
private String newName,newAddress,newGender;
private int newAge;
EditText ed, ed1;
public String name,address,gender,age,code;
private int selectedID,ages,codes;
NumberPicker numberPicker;
private databaseManager4 myDataBase;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
intent= getIntent();
myDataBase = new databaseManager4(this);
rg = (RadioGroup)findViewById(R.id.radioGroup_update);
selectedID = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(selectedID);
ed = (EditText)findViewById(R.id.fullName_update);
numberPicker = (NumberPicker)findViewById(R.id.resultAge_update);
numberPicker.setMinValue(6);
numberPicker.setMaxValue(110);
numberPicker.setWrapSelectorWheel(false);
update = (Button)findViewById(R.id.update_button);
ed1 = (EditText)findViewById(R.id.address_update);
name = intent.getStringExtra("name");
age = intent.getStringExtra("age");
gender = intent.getStringExtra("gender");
address = intent.getStringExtra("address");
code = intent.getStringExtra("code");
codes = Integer.parseInt(code);
displayForm();
newName = ed.getText().toString();
newAge = numberPicker.getValue();
newGender = rb.getText().toString();
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(id);
if (myDataBase.updateRow(codes,newName,newAge,newGender,ed1.getText().toString())){
Toast.makeText(getApplicationContext(),"successfully updated the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Could not update the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
}
public void displayForm(){
ed.setText(name);
ed1.setText(address);
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
rb.setChecked(true);
ages= Integer.parseInt(age);
numberPicker.setValue(ages);
}
public void clear(){
ed.setText("");
ed1.setText("");
}
}
This is where the issue lies, even if the user clicks on Male it registers as female and i am unsure why.
Any ideas how i can fix this?
Your problem is that you set value of rb variable to a single radio button, predefined with previous gender value here
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
And you read value of the same button then. To fix that in you click listener for update button you need to read checked radio button id using getCheckedRadioButtonId on radio group (your rg variable).
upd:
this is how your Edit Friend activity code might look like
public class EditFriendActivity extends AppCompatActivity {
private RadioGroup mGenderRadioGroup;
private Button mUpdateButton;
private EditText mNameField;
private EditText mAddressField;
private NumberPicker mAgePicker;
private databaseManager4 mDatabaseManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
initUI();
mDatabaseManager = new databaseManager4(this);
}
private void initUI() {
Intent intent = getIntent();
mNameField = (EditText) findViewById(R.id.fullName_update);
mNameField.setText(intent.getStringExtra("name"));
mAddressField = (EditText) findViewById(R.id.address_update);
mAddressField.setText(intent.getStringExtra("address"));
mAgePicker = (NumberPicker) findViewById(R.id.resultAge_update);
mAgePicker.setMinValue(6);
mAgePicker.setMaxValue(110);
mAgePicker.setWrapSelectorWheel(false);
mAgePicker.setValue(Integer.parseInt(intent.getStringExtra("age")));
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(updateClickListener);
mGenderRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_update);
RadioButton targetRadioButton = null;
switch (Gender.fromString(intent.getStringExtra("gender"))) {
case MALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderMale_update);
break;
case FEMALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderFemale_update);
break;
}
if (targetRadioButton != null) {
targetRadioButton.setChecked(true);
}
}
public void clear() {
mNameField.setText("");
mAddressField.setText("");
}
private Gender getSelectedGender() {
int checkedButtonId = mGenderRadioGroup.getCheckedRadioButtonId();
switch (checkedButtonId) {
case R.id.resultGenderMale_update:
return Gender.MALE;
case R.id.resultGenderFemale_update:
return Gender.FEMALE;
}
return Gender.UNDEFINED;
}
private View.OnClickListener updateClickListener =
new View.OnClickListener() {
#Override
public void onClick(View v) {
Gender newGender = getSelectedGender();
int code = Integer.parseInt(getIntent().getStringExtra("code"));
System.out.println("gender is" + newGender.stringValue);
if (mDatabaseManager.updateRow(
code,
mNameField.getText().toString(),
mAgePicker.getValue(),
newGender.stringValue,
mAddressField.getText().toString())) {
Toast.makeText(
getApplicationContext(),
"successfully updated the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Could not update the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
}
Intent viewFriendsIntent = new Intent(getApplicationContext(), viewFriends.class);
startActivity(viewFriendsIntent);
finish();
}
};
private enum Gender {
UNDEFINED("undefined"),
MALE("Male"),
FEMALE("Female");
private #Nullable String stringValue;
Gender(#Nullable String stringValue) {
this.stringValue = stringValue;
}
public static Gender fromString(#Nullable String value) {
if (value != null) {
for (Gender gender : Gender.values()) {
if (value.equals(gender.stringValue)) {
return gender;
}
}
}
return UNDEFINED;
}
}
}

List is returning item after deleting all the items [duplicate]

My List is returning an item after clearing all the items by deleting ,On app fresh install its returing null which is good but after adding item and then by deleting all, this happens when go back from that activity and come again, list.size() is returning 1 and an item is remaing ,i don't know if it is loading from cache object instance here is my code of adapter class
[please look to the image attached ,list is empty but still counter 1 counter = cartModelList.size()]i have a list of cart itemsprivate List<CartModel> cartModelList;
It's returning null on app fresh install which is good but when i add item to the cart and then remove all the items then its returning 1.
I mean cartmodelList.size() is returning as far I know it's returning some items from cached objects or some thing like that.
The question is how to remove that List object cached or any alternative?
I tried on delete button but still cached coming
public static double p = 0;
private List<CartModel> cartModelList;
Database db;
Context context;
public CartAdapter(Context context, List<CartModel> cartModelList) {
this.cartModelList = cartModelList;
this.context = context;
db = new Database(context);
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_layout_item, parent, false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final Viewholder holder, final int position) {
String namee = cartModelList.get(position).getName();
String manufacturere = cartModelList.get(position).getManufacturer();
String availabilitye = cartModelList.get(position).getAvailability();
String e_parte = cartModelList.get(position).getE_part();
String m_parte = cartModelList.get(position).getM_part();
String floatprice = cartModelList.get(position).getUnit_();
String int_quantity = cartModelList.get(position).getQuantity();
String float_line_total = cartModelList.get(position).getLine_total();
holder.setItemDetails(namee, manufacturere, availabilitye, e_parte, m_parte, floatprice, int_quantity, float_line_total);
int checker = SharedPrefManager.getInstance(context).cartcount().getCounter();
if (checker <= 0){
cartModelList.clear();
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position);
notifyDataSetChanged();
Toast.makeText(context, "Product deleted from cart", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();
}
CartList user111 = new CartList(--COUNTER_BADGE);
// Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
SharedPrefManager.getInstance(context).cartList(user111);
((Activity)context).invalidateOptionsMenu();
((Activity)context).finish();
Intent intent = new Intent(context, CartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
#Override
public int getItemCount() {
return cartModelList.size();
}
class Viewholder extends RecyclerView.ViewHolder {
private TextView name;
private TextView manufacturer;
private TextView availability;
private TextView e_part;
private TextView m_part;
private TextView price;
private EditText quantity;
private TextView linetotal;
private Button btn_delete;
private Button btn_update;
private Button adapter_livestock;
public SpinKitView progressbar;
public Viewholder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
manufacturer = itemView.findViewById(R.id.manufacturer);
availability = itemView.findViewById(R.id.availability);
e_part = itemView.findViewById(R.id.e_part);
m_part = itemView.findViewById(R.id.m_part);
price = itemView.findViewById(R.id.price);
quantity = itemView.findViewById(R.id.quantity);
linetotal = itemView.findViewById(R.id.linetotal);
btn_delete = itemView.findViewById(R.id.btn_delete);
btn_update = itemView.findViewById(R.id.btn_update);
adapter_livestock = itemView.findViewById(R.id.adapter_livestock);
progressbar = itemView.findViewById(R.id.adapterrprogresslivestockprogress);
}
private void setItemDetails(String namee, String manufacturere, String availabilitye, String e_parte, String m_parte, String floatprice, String int_quantity, String float_line_total) {
name.setText(namee);
manufacturer.setText(manufacturere);
availability.setText(availabilitye);
e_part.setText(e_parte);
m_part.setText(m_parte);
price.setText("£"+floatprice);
quantity.setText(int_quantity);
linetotal.setText("£"+float_line_total);
}
}
[https://i.stack.imgur.com/PxDTZ.jpg]
Okay... The first.
if (db.deleteProduct(cartModelList.get(position).getID()))
will not delete your item from cartModelList, you need to do it manually. Like this:
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position)
And the second. You have to call notifyDataSetChanged() or itemChanged or itemRemoved etc. only in the end of your deletion method. Please, tell me, if it worked.
P.S. Your items do not cached. The problem is in your code order.
Edit 1. Also, you need to check your db.deleteProduct method. Is it worked? Is your if statement worked?
Edit 2. Try this.
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (db.deleteProduct(cartModelList.get(position).getID())) {
cartModelList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Product deleted from cart", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();
}
CartList user111 = new CartList(cartModelList.size());
// Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
SharedPrefManager.getInstance(context).cartList(user111);
((Activity)context).invalidateOptionsMenu();
((Activity)context).finish();
Intent intent = new Intent(context, CartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
my problem is solved by putting cartModelList.clear on delete button when cartModelList.size() == 1 , so after deleting the last item it will clear the list.

Message chat doesn't work well

With my app I send a message and a notification from my smartphone (called PHONE1) to another (called PHONE2). The message is received by PHONE2. PHONE2 send a reply message to PHONE1. PHONE1 receive a notification and read the message. PHONE1 send a reply message to PHONE2 and app crashes.
Messages.java:
public class Messages extends AppCompatActivity {
private static final String TAG = "ChatActivity";
Context context;
private ChatArrayAdapter chatArrayAdapter;
private ListView listView;
private EditText chatText;
private Button buttonSend;
private boolean side = false;
String from, to, mess;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
buttonSend = (Button) findViewById(R.id.send);
listView = (ListView) findViewById(R.id.chatMessage);
chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), R.layout.row_messages_right);
listView.setAdapter(chatArrayAdapter);
chatText = (EditText) findViewById(R.id.msg);
chatText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
return sendChatMessage();
}
return false;
}
});
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
sendChatMessage();
}
});
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setAdapter(chatArrayAdapter);
//to scroll the list view to bottom on data change
chatArrayAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
listView.setSelection(chatArrayAdapter.getCount() - 1);
}
});
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
receiveChatMessage();
}
}, 0, 1000);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private boolean receiveChatMessage(){
InternalDatabaseOperations DB = new InternalDatabaseOperations(this);
Cursor CR = DB.getInformation(DB);
CR.moveToLast();
from = CR.getString(0);
to = CR.getString(1);
if(!Objects.equals(mess, CR.getString(2))){
mess = CR.getString(2);
chatArrayAdapter.add(new ChatMessage(!side, mess));
return true;
}
return false;
}
//Send chat message
private boolean sendChatMessage() {
mess = chatText.getText().toString();
chatArrayAdapter.add(new ChatMessage(side,mess));
chatText.setText("");
InternalDatabaseOperations DB = new InternalDatabaseOperations(this);
Cursor CR = DB.getInformation(DB);
CR.moveToLast();
from = CR.getString(1);
to = CR.getString(0);
BackgroundTaskSendingMessage sendingMessage = new BackgroundTaskSendingMessage(this);
sendingMessage.execute(to, from, mess);
return true;
} }
chatArrayAdapter.java:
class ChatArrayAdapter extends ArrayAdapter<ChatMessage> {
private TextView chatText;
private List<ChatMessage> chatMessageList = new ArrayList<>();
private Context context;
#Override
public void add(ChatMessage object) {
chatMessageList.add(object);
super.add(object);
}
public ChatArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.context = context;
}
public int getCount() {
return this.chatMessageList.size();
}
//Retrieve message position
public ChatMessage getItem(int index) {
return this.chatMessageList.get(index);
}
//Change layout inflater if necessary
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage chatMessageObj = getItem(position);
View row = convertView;
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (chatMessageObj.left) {
row = inflater.inflate(R.layout.row_messages_right, parent, false);
}else{
row = inflater.inflate(R.layout.row_messages_left, parent, false);
}
chatText = (TextView) row.findViewById(R.id.msgr);
chatText.setText(chatMessageObj.message);
return row;
}
}
MessagingServiceNotification:
public class MyFirebaseMessagingService extends FirebaseMessagingService{
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String message = remoteMessage.getData().get("message");
String from = remoteMessage.getData().get("From");
String to = remoteMessage.getData().get("to");
InternalDatabaseOperations DB = new InternalDatabaseOperations(this);
DB.putInformation(DB, from, to, message);
showNotification(message);
}
private void showNotification(String message) {
Intent i = new Intent(this, Messages.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("BookStore")
.setContentText(message)
.setSmallIcon(R.drawable.book)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
logcat:
14007-14681/gamingproject.sellmybooks E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: gamingproject.sellmybooks, PID: 14007
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6353)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:875)
at android.view.View.requestLayout(View.java:17524)
at android.view.View.requestLayout(View.java:17524)
at android.view.View.requestLayout(View.java:17524)
at android.view.View.requestLayout(View.java:17524)
at android.view.View.requestLayout(View.java:17524)
at android.view.View.requestLayout(View.java:17524)
at android.view.View.requestLayout(View.java:17524)
at android.widget.AbsListView.requestLayout(AbsListView.java:2027)
at android.widget.AbsListView.setSelectionFromTop(AbsListView.java:7045)
at android.widget.ListView.setSelection(ListView.java:2018)
at gamingproject.sellmybooks.Messages$3.onChanged(Messages.java:74)
at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
at android.widget.BaseAdapter.notifyDataSetChanged(BaseAdapter.java:50)
at android.widget.ArrayAdapter.notifyDataSetChanged(ArrayAdapter.java:286)
at android.widget.ArrayAdapter.add(ArrayAdapter.java:182)
at gamingproject.sellmybooks.ChatArrayAdapter.add(ChatArrayAdapter.java:22)
at gamingproject.sellmybooks.Messages.receiveChatMessage(Messages.java:104)
at gamingproject.sellmybooks.Messages.access$300(Messages.java:23)
at gamingproject.sellmybooks.Messages$4.run(Messages.java:83)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Thank you in advance for the help.
The problem is that your Timer is using a background thread, and you're trying to update your ChatArrayAdapter from that background thread.
From the documentation:
Corresponding to each Timer object is a single background thread that
is used to execute all of the timer's tasks, sequentially.
If you keep your code as is for the Timer:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
receiveChatMessage();
}
}, 0, 1000);
It looks like you just need to put the code that adds an item to the adapter on the UI Thread:
private boolean receiveChatMessage() {
InternalDatabaseOperations DB = new InternalDatabaseOperations(this);
Cursor CR = DB.getInformation(DB);
CR.moveToLast();
from = CR.getString(0);
to = CR.getString(1);
if(!Objects.equals(mess, CR.getString(2))){
mess = CR.getString(2);
//modified:
runOnUiThread(new Runnable() {
#Override
public void run() {
chatArrayAdapter.add(new ChatMessage(!side, mess));
}
});
CR.close(); //close your cursor to avoid memory leaks!
return true;
}
CR.close(); //close your cursor to avoid memory leaks!
return false;
}

Application always calls onCreate() when the phone is locked and unlocked

Is there any way to save the state of the application because the application calls onCreate() everytime the android phone is locked. When I unlocked it, the app calls the onCreate() method and start again.. BTW my app is like text twist. When I unlock the screen a new word is shown, instead of the current one.. The score is also reset as well as the time.. How can I work on this? Please help.. It's still unanswered..
This is the whole code of my activity..
public class friend extends Activity {
//score
ScoreHandler scHandler;
Score sc;
int totalScore;
//words
//DatabaseHelper dbHelp;
DBHelper dbHelp;
public String randomWord;
//speech
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
//shake
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
//timer
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private TextView timeText;
private final long startTime = 180 * 1000;
private final long interval = 1 * 1000;
private long timeLeft;
private int gameScore;
private TextView shuffleView;
TextView scoreView;
//Animation
Animation myFadeInAnimation;
Animation myFadeOutAnimation;
Animation leftToRight;
//sliding
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
Context context;
static final String STATE_SCORE = "currentScore";
static final String STATE_WORD = "currentWord";
static final String STATE_TIME = "currentTime";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
} else {
// Probably initialize members with default values for a new instance
}
setContentView(R.layout.friend);
leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);
ImageButton next = (ImageButton) findViewById(R.id.nextround_game);
next.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, friend1.class);
startActivity(intent);
}
});
ImageButton giveUp = (ImageButton) findViewById(R.id.surrender_game);
giveUp.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, GameOverActivity.class);
startActivity(intent);
}
});
//score
//timer
timeText = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
timeText.setText(timeText.getText() + String.valueOf(startTime/1000));
countDownTimer.start();
timerHasStarted = true;
this.removeAll();
dbHelp = new DBHelper(this);
randomWord = dbHelp.random();
System.out.println(randomWord);
String wordCaps = randomWord.toUpperCase();
final String finalWord = shuffle(wordCaps);
shuffleView = (TextView) findViewById(R.id.jumble);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/American Captain.ttf");
shuffleView.setTypeface(type);
shuffleView.setText(finalWord);
//shake
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
//String str = (String) stringList.remove(selectedWord);
String wordOutput = shuffle(finalWord);
TextView tv = (TextView) findViewById(R.id.jumble);
tv.setText(wordOutput);
}
});
//speech
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timeText.setText("0:00");
playSound(R.raw.clock_whistle);
ImageView timeIsUp = (ImageView) findViewById(R.id.time_is_up);
timeIsUp.startAnimation(leftToRight);
}
#Override
public void onTick(long millisUntilFinished) {
long minutes = (millisUntilFinished / (1000*60)) % 60;
long seconds = (millisUntilFinished / 1000) % 60 ;
timeLeft = millisUntilFinished/1000;
timeText.setText("" + minutes + ":" + seconds );
if (timeLeft <= 10) {
playSound(R.raw.clock_beep);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
System.out.println(""+text.get(0));
String spoken = text.get(0);
if(dbHelp.exists(spoken)){
if(dbHelp.isLongest(spoken)){
Toast.makeText(getApplicationContext(), "You have guessed the longest word! ", Toast.LENGTH_SHORT).show();
}
gameScore = text.get(0).length()*10;
scoreView = (TextView) findViewById(R.id.scoreView);
scoreView.setText(""+gameScore);
scHandler = new ScoreHandler(this);
scHandler.addScore(new Score(1,gameScore));
int cumulativeScore = scHandler.accumulateScores();
scoreView.setText(""+cumulativeScore);
playSound(R.raw.correct);
WordGuessedHandler guessedWord = new WordGuessedHandler(this);
guessedWord.addGuessedWord(new Words(1,spoken));
ImageView img = (ImageView) findViewById(R.id.awesome);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
img.startAnimation(myFadeInAnimation);
img.startAnimation(myFadeOutAnimation);
}else{
playSound(R.raw.poweng);
ImageView image = (ImageView) findViewById(R.id.wrong);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
image.startAnimation(myFadeInAnimation);
image.startAnimation(myFadeOutAnimation);
}
}
}
}
}
public String shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
return output.toString();
}
#Override
public void onBackPressed()
{
Intent inMain=new Intent(friend.this, MainActivity.class);
inMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inMain);
countDownTimer.cancel();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE,gameScore);
savedInstanceState.putLong(STATE_TIME,timeLeft);
savedInstanceState.putString(STATE_TIME,randomWord);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
}
//sliding menu onChange
#Override
public void onContentChanged()
{
super.onContentChanged();
mOpenButton = (Button) findViewById( R.id.button_open );
mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer);
/* GridView gridView;
ArrayList ArrayofName = new ArrayList();
WordHandler db = new WordHandler(this);*/
TextView txt = (TextView) findViewById(R.id.text);
txt.setText("Hello There!");
GridView gridview = (GridView) findViewById(R.id.gridView1);
WordGuessedHandler guessed = new WordGuessedHandler(this);
List <WordGuessed> guessedList = guessed.getAllWordGuessed();
List<String> wordsList = new ArrayList<String>();
for(WordGuessed wg:guessedList){
wordsList.add(wg.getWord());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, wordsList);
gridview.setAdapter(adapter);
}
public void playSound(int sound) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.setLooping(false);
mp.setVolume(1,1);
mp.start();
}
public void removeAll()
{
ScoreHandler scHandler = new ScoreHandler(this);
// db.delete(String tableName, String whereClause, String[] whereArgs);
// If whereClause is null, it will delete all rows.
SQLiteDatabase db = scHandler.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
db.delete("scores_table", null, null);
db.close();
}
}
This question answers your question.
https://developer.android.com/training/basics/activity-lifecycle/index.html
Please use the onPause() and onResume() methods in your main Activity to solve this problem. If both method aren't defined, your app will go to the next methods in the lifecycle, which will be onCreate() and other methods. Read more here.
It is also possible to save your current instance by using onSaveInstance(Bundle b) and onRestoreInstance(Bundle b)
PS: someone has asked it earlier, and wrote a small example to use the onSaveInstance and onRestoreInstance (if you want to use it) here.

Categories