Do intent based on which activity includes fragment - android

Hello i have made a fragment which has one button and I am using it in two activities. The problem which arises from this is that the fragment will do the same intent
Onclick(Type variable is which activity it should run and is not implemented into the onclick, this does not work):
runBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (type == 0){
Intent sendToMain = new Intent(getActivity(), MainActivity.class);
sendToMain.putExtra("newStory", story);
}
if (type ==1){
Intent reviewStoryIntent = new Intent(getActivity(),storyReviewActivity.class);
reviewStoryIntent.putExtra("Story", story);
}
}
});
Is there any way to differentiate between which activity the fragment is placed in?

You can check your different activity as below in your fragment:
if(getActivity() instanceof YourFirstActivity) // type == 0
{
// Do your stuff here for First Activity
}else if(getActivity() instanceof YourSecondActivity) // type ==1
{
// Do your stuff here for Second Activity
}

I'm thinking on a different approach. What not to let your activities handle the intents?
So, your activities implements a callback method and your fragment call it so, every activity will know where that Intent should directed.
Hope it helps.

Related

How check if my previous activity exist?

In my app, there are 3 activities and their calling sequence is like this...
Splash activity--->Dashboard Activity--->List Activity
If it goes like this then If I press back button on List activity then it will follow the reverse sequence of above.
There is one requirement where user can navigate to List Activity directly from Splash (Skipping Dashboard Activity) Now when user will hit back button on List Activity then I wan't to show Dashboard Activity which is not there in the Activity Stack.
So please help me with the best approach.
Pass a boolean through the intent for going to List Activity from either of the others. Using onBackPressed check if the boolean is true or false for skipping Dashboard Activity.
Then if true put new intent for loading dashboard activity and finish(); on list activity.
You have to pass class name as intent extra from both Splash and DashboardActiviy.
In List Activity you have to get the class name using getIntent().
When the user click back button, you need to check the class name based on that you can take decision.
if(name.equalIgnorecase(DashboardActivit.class.getSimpleName()){
//Add your intent
}else{
//
}
This may give you definite solution to you.Give a try
you can directly go to splash from list Activity while going to
ListActivity from Dashboard Activity call finish()
Intent i = new Intent(DashboardActivity.this,ListActivity);
startActivtiy(i);
finish();
Start your inner activities with startAcvitiyForResult
Intent i = new Intent(this, Activity_2.class);
startActivityForResult(i, 1);
and in your inner activity
#Override
public void onBackPressed ()
{
finish();
}
You can also do stuff in your outer activity as you like after your inner activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == 1){
Log.i("TEST", "RESULT_OK");
}
else {
return;
}
}
}

Two Intents that start the same class, getExtras() cause IndexOutOfBoundsException

I need to start one Activity (say WriteAtivity), twice, but in different mode.
In MainActivity what happens.
For example:
addNote.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent writeAct = new Intent(MainActivity.this, WriteActivity
// HERE, I DO NOT NEED OF putExtra()
startActivity(writeAct);
}
});
and
editNote.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent visualizza = new Intent(MainActivity.this, WriteActivity.class);
// HERE INSTEAD I HAVE NEED OF putExtra()
visualizza.putExtra("posizione", position);
startActivity(visualizza);
}
});
and in onCreate() of WriteActivity
intent = getIntent().getExtras().getInt("posizione");
rifTitleNote.setText(listNote.get(posizione).getTitle());
As you can see, in one i do not need putExtra() and in second I do.
I do this because I use the WriteActivity, at first, for write a note, and then, for edit the note.
This, in any case causes IndexOutOfBoundsException: Invalid index 0, size is 0
Do you know how I can overcome this problem?
Or give me advice on how to do this?
Thanks! :D
Just use getIntExtra() with a default value, and make sure that the value is not set to the default value before using it.
Intent intent = this.getIntent();
int posizione = intent.getIntExtra("posizione", -1);
if (posizione != -1){
rifTitleNote.setText(listNote.get(posizione).getTitle());
}
Check for the existence of the extra and handle accordingly if it exists or not. See Android's Intent documentation for hasExtra.
if (getIntent().hasExtra("posizione")) {
// Do stuff with extra
}
You could also set an action on the Intent that indicates how the Activity should handle the incoming intent. This is probably the "better" approach but might be overkill depending on your project.

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();
}

How do I persist an attribute in an activity that I'm navigating back up to?

I have some activities basically set up as shown below (clicks on are ListViews).
Parent class method to go to MyChild1
public void onItemClick(int pos){
Intent i = new Intent(this, MyChild1.class);
i.putExtra("KEY1", myAdapter.getItem(pos).getId());
startActivity(i);
}
MyChild1 class method to go to MyChild2
public void onItemClick(int pos){
Intent i = new Intent(this, MyChild2.class);
i.putExtra("KEY2", myAdapter2.getItem(pos).getId());
startActivity(i);
}
So you see that I have a parent, a child, and a grandchild activity. The child inflates based on the id provided by the parent and the grandchild inflates based on the id of the child. This works fine. However, when I use up navigation from the grandchild back to the child, it no longer has the id it needs from the parent to properly inflate. I need to support up navigation because the child can change based on actions in the grandchild.
I could pass the parent's id all the way down to the grandchild activity, but I don't know how to pass it back up. How can I handle this?
Edit: More code for context.
Here is my activity's onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new CourseActivityFragment()).commit();
Intent intent = getIntent();
courseId = intent.getIntExtra(MainFragment.COURSE_ID, 0);
System.out.println("the saved state was null");
// The above prints, so I know it enters this if statement
} else {
courseId = savedInstanceState.getInt(COURSE_ID);
}
}
And here is my onSaveInstanceState
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
// Save current CourseId
savedInstanceState.putInt(COURSE_ID, courseId);
// Call superclass to save view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Instead of startActivity, use startActivityForResult:
Intent intent = new Intent(ParentClass.this, ChildClass.class);
startActivityForResult(intent, RequestCode);
In child class, set some parameter in intent to identify in Parent class.
Intent intent = getIntent();
intent.putExtra(<Key>, <Value>);
In parent class, override the onActivityResult method, and check your Value for that Key
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == RequestCode)
{
//Do something
}
}
I don't quite follow what you need so I hope this will help. Save it in your Activity class as member variable. Activity's object is not destroyed right after user leave this activity. If that still occur and Android will kill your activity, you can use onSaveInstanceState() and restoreInstanceState() methods to restore this id.

Android cant tell intents apart

In my main activity (where everything happens in my application) I call a variety as of now just two other activities which end up calling back to my MainActivity via button press. How do I distinguish between these two Intents back to my MainActivity? I have seperate operations I want to prefrom based on things I did back in the two seperate activites.
Heres what I tried:
Intent intent = getIntent();
String s_message = intent.getStringExtra(AppSettings.EXTRA_MESSAGE);
String f_message = intent.getStringExtra(ViewFavorites.EXTRA_MESSAGE);
if(s_message != null) {
//do something
} else if (f_message != null) {
//do something
}
But when I run my application I find when exiting the two activities that they are prefroming the methods I do not wish them to...am I going about this wrong?
What I do is simply set an Extra in my passing Intent then compare that. Something like this. When creating the Intent add an Extra to compare to
intent.putExtra("source", "appSettings");
then in your Activity check what that value is
Intent intent = getIntent();
String source = intent.getStringExtra("source"); // get that value here
if(s_message != null) {
if ("appSettings".equals(source)){
//do something
} else if (viewFavorites.equals(source)) {
//do something else
}
}
You could use variations of this as far as how you assign the Extra but this is a simple example that works well for me, especially when there are just a few Activites that will be calling this one.
Set a different ACTION on each intent, then use if(getIntent().getAction().equals(ACTION)) to distinguish between intents.
public class MainActivity extends Activity {
public static final String ACTION_ONE = "com.yourpackage.ACTION_ONE";
public static final String ACTION_TWO = "com.yourpackage.ACTION_TWO";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if(intent.getAction() != null){
if(intent.getAction.equals(ACTION_ONE){
//DO SOMETHING
} else if (intent.getAction.equals(ACTION_TWO){
//DO SOMETHING
}
}
}
.....
}
Then when you start your main activity with an intent:
Intent intent = new Intent(MY_CURRENT_CONTEXT, MainActivity.class); //Or MainActivity subclass
add
intent.setAction(ACTION_ONE);
or whichever action is specific to what your intent is trying to accomplish.

Categories

Resources