Putting arguments to Activitiy.this in Android - android

how can I call MyActivitiy.this, but put arguments to it or to its Bundle?
My Code:
OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(MyActivitiy.this) {
#Override
public void onSwipeLeft() {
//your actions
}
};

The question doesn't seem to be very clear. But, consider declaring a Context ( set it equal to MyActivity.this) and using that as the parameter for your OnSwipeListener.
The way to communicate with an Activity is via Intents. In whatever code you use to start your Activity, go:
Intent intent = new Intent(someContext, MyActivity.class);
intent.putExtra("myKey", "whateverValue");
In your Activity's onCreate() method, use:
Intent intent = getIntent();
String message intent.getStringExtra("myKey", "aDefaultValueJustInCase");
Once that Activity is started, the String message will acquire the value "whateverValue".
As to using its Bundle, you probably only want to do that to recreate your Activity (say you're returning from another Activity, or pressed Back). Documentation for that is here.
Hope that answered your question. If not, please provide us more details and we will probably be able to provide more specific answers.

Related

Pass value through intent or static variable?

I am wondering about the best way to design / program this:
If I have a Boolean value (let's say whether the user has extra power or not) and I need to pass it from Activity A to B to C. Should I add it to an intent from each activity to another OR should I just store it in a static variable and access it every time?
Its is safer to pass it in the intent. sometimes android kills apps without warning when it needs memory and your static values will not be retained on the other hand intent extras are kept. if you want to push it a little further, use shared preference. its designed using Map data struct so speed will not be a problem.
Android Intents have a putExtra method that you can use to pass variables from one activity to another.
public class ActivityA extends Activity {
...
private void startActivityB() {
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("HAS EXTRA POWER", false);
startActivity(intent);
}
}
public class ActivityB exntends Activity {
Bundle bundle;
private void hasExtraPower() {
bundle = getIntent().getExtras();
if(!bundle.getBoolean("HAS EXTRA POWER")
// do something
else
// do something else
}
}
Passing data through Intent
If you use that only in that activity that's fine but
When u need to pass to other layer like viewmodel that will make your operation's speed slower

2 intents on post execute of async task

Had a clarification to make: Can 2 intents be defined to pass the the same data to 2 different activities ? The second class (logout.class) is not getting accessed. The code is:
protected void onPostExecute(String result) {
if(result != null)
{
Intent tokenIntent = new Intent(mContext, tokenActivity.class);
Bundle bundle = new Bundle();
bundle.putString("responsedata",result.substring(result.indexOf("=")+1,result.length()));
tokenIntent.putExtras(bundle);
startActivity(tokenIntent);
Intent tokenIntent2 = new Intent(mContext,logout.class);
Bundle bundle2= new Bundle();
bundle2.putString("responsedata",result.substring(result.indexOf("=")+1,result.length()));
tokenIntent.putExtras(bundle2);
startActivity(tokenIntent2);
}
}
}
Maybe you can use this,
public abstract void startActivities (Intent[] intents, Bundle options)
Added in API level 16
Launch multiple new activities. This is generally the same as calling startActivity(Intent) for the first Intent in the array, that activity during its creation calling startActivity(Intent) for the second entry, etc. Note that unlike that approach, generally none of the activities except the last in the array will be created at this point, but rather will be created when the user first visits them (due to pressing back from the activity on top).
This method throws ActivityNotFoundException if there was no Activity found for any given Intent. In this case the state of the activity stack is undefined (some Intents in the list may be on it, some not), so you probably want to avoid such situations."

Using intent in a public function

I've a method which is making a huge calculation and then calls an intent as follows
public void sampleMethod(final Context cont)
{
.
.
(huge calculation [50-80 lines])
.
.
Intent intent = new Intent(cont, TimesheetMain.class);
finish();
startActivity(intent);
}
This is present in Activity 'SampleActivity'. When I'm trying to access it through on object of Activity 'SampleActivity' from Activity 'B' as follows:
Context context = this;
SampleActivity sa = new SampleActivity();
sa.sampleMethod(context);
I'm getting a NullPointerException at the startActivity line of code while accessing it from Activity 'B'. I can't figure out where am i going wrong in here. Please help me out
EDIT 2
This seem to work when i added context to it like cont.startActivity(intent), but i need to know why shouldn't i use another class or another activity's function in a secondary class? Is the android framework is the reason? I've been doing this (without the intent part) for the past two months or so, i never faced any sudden force close issues in either emulator or in device(Nextbook professional 7 SE); Please explain it with a legit example
You're not supposed to create explicit instances of activities by yourself as you're doing like this:
SampleActivity sa = new SampleActivity();
Please provide a better description for your problem and what you want to achieve with the outcome of this issue.
try the follwng updated code:
public void sampleMethod(final Activity cont)
{
Intent intent = new Intent(cont, TimesheetMain.class);
cont.finish();
cont.startActivity(intent);
}
also move this method to a util class and call it from activity and pass the activity reference as follows
class ActivityB extends Activity
{
.
.
.
Util.sampleMethod(this);
}

Can you Parameterize an intent creation function?

In order to simplify some code, I'm wondering if it is possible to parameterize code that launches activities in an android application, so that instead of having 5
public void showSettings(View view) {
Intent SettingsActivity = new Intent(MainActivity.this, Settings.class);
startActivity(SettingsActivity);
I can do something like the following
public void showActivity(View view, String ActivityName) {
Intent ActivityName = new Intent(MainActivity.this, ActivityName.class);
startActivity(ActivityName);
Then, for each button in the UI, I simply apply the following to the "onclick" event
showActivity(Settings);
or
showActivity(domains);
This would save about 40-50 lines of code in my app. Obviously I know the above code is incorrect, but I'm not sure if it's possible to do what I'm trying to accomplish.
How about something like:
public <T> void showActivity(View view, Class<T> activity) {
Intent activityName = new Intent(MainActivity.this, activity);
startActivity(activityName);
}
You can invoke it with
showActivity(Settings.class);
I'd recommend use ACTIONs (String) instead of specifying exactly context and class. This way you even can share activities among applications, and if you decide to switch to different activity class, you can edit only android manifest, instead of editing all java source code calls this activity.

How to pass value to another tab without starting Activity?

I have 2 Tabs - Tab1 and Tab2, Tab1Activity and Tab2Activity.
I want to pass values from Tab1Actvity to Tab2Activity but dont want to start Tab2Activity.
When i try below code it gives null value:
In Tab1Activity
getParent().getIntent().putExtra("key", "value");
In Tab2Activity
String valueString=getParent().getIntent().getStringExtra("key");
System.out.println("Testing.....: "+valueString);
I really discourage you from using global variables by extending the Application class. If your application goes to the background, (e.g. due a phone call) the android system might decide to kill your application. When the call is finished your application and the activity stack will be restored, but your activity state will be lost.
I'd rather suggest you to use broadcasts to send data to another activity.
In your Tab1Activity:
Intent dataIntent = new Intent();
dataIntent.setAction("com.your.app.DATA_BROADCAST");
dataIntent.putExtra("tag", "your data");
sendBroadcast(dataIntent);
Tab2Activity:
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String yourData = intent.getStringExtra("tag");
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.your.app.DATA_BROADCAST");
registerReceiver(receiver, filter);
You definitely want to reconsider using Activities as the content of your tabs. The more standard approach is to use one Activity that uses Tabs to only show part of the layout when a particular tab is selected.
The Android documentation has an excellent worked example, check out Hello, TabWidget.
Alternative
If for some reason you do need to use Activities, you can pass information between them by either adding values to the extras bundle within the Intent your using to open each Activity, or by extending the Application class.
By extending the Application class (and implementing it as a Singleton) you get an object that will exist whenever any of your application components exist, providing a centralized place to store and transfer complex object data between application components.
Also you can use static classes or SharedPreferences for data transfer between tabs.
the correct way is setting a static field into the activity that creates the tabs
public class greformanews extends TabActivity {
public static String JorgesysTitle;
...
...
...
so in your Activity defined in tab 1
#Override
protected void onPause() {
greformanews.JorgesysTitle = "JORGESYS =)";
super.onPause();
}
in your Activity defined in tab 2
//get value defined in Activity 1 !:)
String Title = greformanews.JorgesysTitle

Categories

Resources