Android: Intent- FLAG_ACTIVITY_NO_HISTORY not working - android

I have three activities say A B C , from activity A i go to B and and search city and from Activity B iam going to Activity c , in c iam saving something which i put in Async task
and this will be saved in Activit A listview, the problem is after saving in the list when i hit back button i again see the Activity A with not saving the name which i previously saved
private class Savecity extends AsyncTask<city, String, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equals("sucess")){
Intent intent = new Intent(activity, cityActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);}
}
#Override
protected String doInBackground(city... arg0) {
try {
((CityPreferences) activity.getApplication()).createcity(arg0[0]);
return "sucess";
} catch (Exception e) {
Log.e(TAG, "", e);
return "fail";
}
}

You can implement this from your AndroidManifest.xml file, just add android:noHistory="true" attribute in those <activity> you want
hope this helps..

Actually in your activity C when you are trying to re-call activity A, all you need to do is to clear activity-stack. For example:
Intent i = new Intent(getBaseContext(), Activity_A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

Related

How to make a result from function to show in another activity

public void doSomething(View view) {
String url, link_url, pro;
url = textIn.getText().toString();
pro = spin.getSelectedItem().toString();
c1 = new ConnectInternetClass(this);
if (!url.isEmpty()) {
if (url.contains(".") && !(url.contains(" "))) {
if (url.split("\\.").length > 1) {
if (checkConnection()) {
link_url = pro+url;
c1.execute(link_url);
} else {
Toast.makeText(this, "check your internet connection", Toast.LENGTH_SHORT).show();
myText.setText("No Internet Connection");
}
} else {
myText.setText("Unknown domain");
}
} else {
myText.setText("Invalid URL");
}
} else {
myText.setText("URL can\'t empty");
}
}
I have that code to show a web page source. I want to show the result in another activity, but I don't know how. I use the create object from the first activity, but it's not method
public class ShowActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
MainActivity ma = new MainActivity();
}
Passing data from a activity , linkUrl is your variable which data you want to pass :
Intent intent = new Intent (YourActivity.this, ShowActivity.class) ;
intent.putExtra("KEY_LINK" , linkUrl);
startActivity(intent);
Receiving data from ShowActivity , Access the data by the key in onCreate():
String url = getIntent().getStringExtra("KEY_LINK");
Link : How do I pass data between Activities in Android application?
Link : https://developer.android.com/training/basics/firstapp/starting-activity.html
Why you use this kind of things. If you want to load a web page in an activity use webview for it. no need two activities to do that. Another way you can create a class which has your doSomething method (it should be public static) and call it from an activity by using that's class object. When you coding don't create unnecessary activities.

Android: How to maintain set data in the list view

In Activity A, I click a button to go to Activity B. I bring data using Bundle back to the Activity A and I managed to change a String value in the ListView. Then I go to another Activity C to manipulate another data. The problem is, when I get back again to the Activity A, the data from the Activity C is reflected in the ListView, but the previous data from the Activity B is gone.
Here's a code to the Activity B from the Activity A.
private void gotoRepeatWeeklyOptionActivity() {
Intent intent = new Intent(CreateNewAlarmActivity.this, RepeatWeeklyOptionActivity.class);
startActivity(intent);
finish();
}
This one is the method from the Activity A to the Activity C.
private void openAlarmToneOptionDialog() {
Intent intent = new Intent(CreateNewAlarmActivity.this, ChooseAlarmToneActivity.class);
startActivity(intent);
}
And this is a code that leads to the Activity A from the Activity B.
#Override
public void onBackPressed() {
Intent intent = new Intent(this, CreateNewAlarmActivity.class);
ArrayList<Integer> repeatStatusIntList = new ArrayList<>();
intent.putExtra(Keys.OPTION, Keys.OPTION_REPEAT);
if(cbRepeatEveryDay.isChecked()) {
super.onBackPressed();
intent.putExtra(Keys.VALUE, Keys.EVERY_DAY);
Toast.makeText(this, getString(R.string.alarm_will_repeat_every_day), Toast.LENGTH_SHORT).show();
} else if(allUnchecked()) {
super.onBackPressed();
intent.putExtra(Keys.VALUE, Keys.NO_REPEAT);
Toast.makeText(this, getString(R.string.alarm_will_never_repeat), Toast.LENGTH_SHORT).show();
} else {
for(int i=0; i<repeatStatusList.size(); i++) {
super.onBackPressed();
if(repeatStatusList.get(i).isChecked()) {
repeatStatusIntList.add(getRepeatStatusInt(repeatStatusList.get(i)));
intent.putIntegerArrayListExtra(Keys.KEY_REPEAT_STATUS_INTEGERS_LIST, repeatStatusIntList);
}
intent.putExtra(Keys.VALUE, Keys.ON);
}
Toast.makeText(this, getString(R.string.alarm_will_repeat) + getString(R.string.every) +
getAllRepeatDays(repeatStatusList), Toast.LENGTH_SHORT).show();
}
startActivityForResult(intent, RESULT_OK);
finish();
}
Finally, this is a code from the Activity C, which leads back to the Activity A.
btnSelectTone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CreateNewAlarmActivity.class);
intent.putExtra(Keys.OPTION, Keys.OPTION_ALARM_TONE);
intent.putExtra(Keys.VALUE, ringtone);
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
startActivityForResult(intent, RESULT_OK);
finish();
}
});
Here's a sample screen from the Activity A.
what Atif has suggested is one solution which is most desirable in your case.
Else you can use Shared Preferences like below. Get the SP instance and commit the data you want to share in editor
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
And this is how you can retrieve the shared pref data
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
Personally i would suggest you to surf more on developer.android.com or visit below link
https://developer.android.com/guide/topics/data/data-storage.html#pref
In future if you have large amount of data then above solution wont work.
Please follow below link for more options
How to pass the values from one activity to previous activity

How to call an other activity from parent activity by intent setclass?

I'm trying to make an dynamical move activity process by using baseActivity through process of defined string value.
But I've faced an problem of "activity is not an enclosing class." error in calling "newIntent.setClassName" method of baseActivity.
Could you help some idea?
First, for explaining about the trying code,
This process purpose is for user sign up process.
Here is used activities.
1. AgreeChildActivity (agree a service terms)
2. VerifyingChildActivity (verifying an user)
3. InputChildActivity (input an user info)
4. CompleteChildActivity (show a service join completed)
1~4 These are children of "GateBaseActivity".
It starts the dynamical move process by onClick method of an "MainActivity".
MainActivity {
String sProcessCase1 = "verifying->input->complete";
String sProcessCase2 = "input->verifying->complete";
String sProcessCase3 = "input->complete";
:
:
public void onClick(View v) {
Intent intent = null;
try {
switch (v.getId()) {
case R.id.goDynamicMenu:
// start dynamic process
Intent newIntent = new Intent()
newIntent.setClassName(this, "AgreeChildActivity");
newIntent.putExtra("MOVE_SEQ", sProcessCase1); <== set processCase.
startActivity(newIntent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Following is each activities code.
GateBaseActivity (<= This is a parent of all process activity.)
void onResume() { (so executes this method when each process activity shows.)
String sActivitySeq = getintent("MOVE_SEQ"); <= "verifying->input->complete"
String sNextActivity = <= calculate the nextActivity name on sActivitySeq. For simple, omitted.
// "verifying->input->complete"
// verifying => VerifyingChildActivity
// input => InputChildActivity
// complete => CompleteChildActivity
String sThisChildSimpleName = this.getClass().getSimpleName();
Intent newIntent = new Intent();
// execute here when childActivity is the "AgreeChildActivity".
if ("AgreeChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(AgreeChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
// execute here when childActivity is the "VerifyingChildAcitivty".
else if ("VerifyingChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(VerifyingChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
// execute here when childActivity is the "InputChildAcitivty".
else if ("InputChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(InputChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
// execute here when childActivity is the "CompleteChildActivity".
else if ("CompleteChildActivity".equals(sThisChildSimpleName)) {
newIntent.setClassName(CompleteChildActivity(<=Here occured "not an enclosing class err.", How to solve this error?).this, sNextActivity);
}
newIntent.putExtra("MOVE_SEQ", sActivitySeq);
startActivity(intent);
}
// These are child activities of "GateBaseActivity".
AgreeChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is AgreeChildActivity.");
}
VerifyingChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is VerifyingChildActivity.");
}
InputChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is InputChildActivity.");
}
CompleteChildActivity implement GateBaseActivity
void onResume() {
super.onResume();
Log.d("autoTest", "Here is CompleteChildActivity.");
}
Try-
Context context = getApplicationContext();
Intent intent = new Intent(context, AgreeChildActivity.class);
You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.
not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.

Update data in local SQLite then return to parent Activity solution

I am learning Android. I am creating an application that have 2 activities: List Activity list all records from a local SQLite and Edit activity will create/update record.
On Edit activity, I have a button. When the button clicked, I will process creating/updating the record then returning back to parent activity (List activity).
On Button click. I have 2 solutions to process Create/Update:
1. Process Create/Update in UI thread ( Not using AsyncTask )
This solution is fine but I may have to show 'Processing' dialog.
2. Use AsyncTask -- so creating/updating happens in background Thread. Here is my code in Edit Activity:
---- NOTE that Edit activity use Fragment so getActivity() method will return the instance of EditActivity
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTask<Phrase, Integer, Integer> asyncTask = new AsyncTask<Phrase, Integer, Integer>() {
#Override
protected Integer doInBackground(Phrase... params) {
Phrase phrase = params[0];
if (phrase._id > 0) {
PhraseDao.update(DbManager.openWrite(getActivity()), phrase);
} else {
PhraseDao.insert(DbManager.openWrite(getActivity()), phrase);
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
Intent intent = new Intent();
getActivity().setResult(Activity.RESULT_OK, intent);
// Close Edit Activity then Go back to List activity
getActivity().finish();
// MY QUESTION: What happens if the EditActivity (getActivity) already destroyed?
// How can I handle destroyed activity here
}
};
asyncTask.execute(a_phrase);
}
});
I don't know how to handle 'onPostExecute' method in the case Edit Activity ( accessed by getActivity()) Already destroyed.
Anyone have any ideas? Thank you!
Add a null check to see if activity exists i.e
if(getActivity() != null){
Intent intent = new Intent();
getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();
}

Coming back from intent, do something

I have an android application which is using listView. After clicking on any item on the list it shows you AlertDialog where you can chose either edit or delete. After clicking edit it starts a new intent sending some extra strings to fill up the form for editing. I would like to refresh the list after I click on button save in that EditActivity.
I have read about notifyDataSetChanged() and I think it could work I just would like to know if there is any method which is in MainClass (listView class) and it is executed right after I came back from intent, right after clicking save button in EditActivity.
Or may I just add notifyDataSetChanged() method after I start an activity in the MainActivity?
public class yourClass extends ListActivity {
//define a class variable here.
private ArrayAdapter<Friend> adapter;
#Override
public void onCreate(Bundle savedInstanceState){
//Change this line setListAdapter(new ArrayAdapter<Friend>(this, android.R.layout.simple_list_item_1, db.getAllFriends()));
to
adapter = new ArrayAdapter<Friend>(this, android.R.layout.simple_list_item_1, db.getAllFriends());
setListAdapter(adapter);
}
#Override
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
}
You can add listView.notifyDataSetChanged() in your activity onResume() function.
#Override
public void onResume(){
super.onResume();
yourListView.notifyDataSetChanged();
}
Use the method startActivityForResult() when opening your EditActivity then implement onActivityResult method in your main class. There you will be able to use notifyDataSetChanged
Read this from the doc
use startActivityForResult to call your EditActivity (this isn't simplest way to do what you want but is good way to do), by using this you can find out what is the result of your edit
Intent i = new Intent(this, EditActivity.class);
startActivityForResult(i, 1);
In your EActivity set the data which you want to return back to MainActivity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",YOUR_RESULT); // skip if you do not want to return special result
setResult(RESULT_OK,returnIntent);
finish();
if you want to send cancel action (in your case fail edit) use this
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
Now in your MainActivity class write following code for onActivityResult() method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result"); // result sent from EditActivity
listViewAdapter. notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult

Categories

Resources