I am new to Android. I have a base Activity class (MainActivity.java) which extends Activity. So I can initialized Intent here.
MainActivity.java
Intent myIntent = new Intent(MainActivity.this, ConnectionClass.class);
myIntent.putExtra("ServerName", ServerName);
startActivityForResult(myIntent, 1);
In connectionClass.java I have a class ConnectionClass which doesn't inherited. But I want to access the values from MainActivity.java. So this class Doesn't inherited Activity & onCreate Method. But I need to access the values from MainActivity.java to ConnectioClass.java
ConnectionClass.Java
public class ConnectionClass {
Bundle bundle = getIntent().getExtras();
String ServerName = bundle.getString("ServerName");
}
How can I do this?
I don't know if the "ServerName" is fixed value, or varies each time, or it has a kind of pool of values. If it's the first or third case, I suggest you to use SharedPreferences. It's a relatively small key-value data storage. You can save data in it and it will be permanent in your app once stored unless deleted. So you can save data in MainActivity, and fetch the value in a class wherever you want.
You can find tutorial here : https://developer.android.com/training/basics/data-storage/shared-preferences.html
you can pass the servername to the class when you are instantiating a new object from ConnectionClass in your activity like below
public class ConnectionClass {
String serverName;
public ConnectionClass(String serverName){
this.serverName=serverName;
}
}
then in your activity you have something like:
Bundle bundle = getIntent().getExtras();
String ServerName = bundle.getString("ServerName");
ConnectionClass connection=new ConnectionClass(ServerName);
Related
Hey I am pretty new to making android apps and I understand that the easiest way to pass data between two activities is through an intent.
In one of my classes (EventOptions.java), I call this line of code:
Intent i = new Intent(EventOptions.this, PhotoFetcher.class);
i.putExtra("imageArray", imageIDs);
startActivity(i);
imageIDs is a string array
In my PhotoFetcher class, I want to set a string array called imageIDs to the imageIDs string array that I am passing through the intent.
I want to set images as a global variable in my class:
public class MainActivity extends Activity implements View.OnClickListener{
Intent it = getIntent();
String[] imageIDs = it.getStringArrayExtra("imageArray");
...
}
This crashes my app however. Is this not allowed? And if so, how can I fix it? Thanks in advance!
Need to call getIntent() in a method instead of at class level. call it inside onCreate :
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// get Intent here
Intent it = getIntent();
String[] imageIDs = it.getStringArrayExtra("imageArray");
}
if I want to use the imageIDs array in another public class defined
in my PhotoFetcher class, do I need to call it again?
To get imageIDsin PhotoFetcher class either declare String[] imageIDs as global variable or pass imageIDs using PhotoFetcher class constructor
You have to use putStringArrayListExtra. You can convert your String[] to an ArrayList first.
Like so
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(imageIDs));
Intent i = new Intent(EventOptions.this, PhotoFetcher.class);
i.putStringArrayListExtra("imageArray", arrayList);
startActivity(i);
And then you can fetch it like you do, preferably in onCreate or after that call.
Intent it = getIntent();
ArrayList<String> imageIDs = it.getStringArrayListExtra("imageArray");
Share data without persisting to disk
It is possible to share data between activities by saving it in memory given that, in most cases, both activities run in the same process.
Note: sometimes, when the user leaves your activity (without quitting it), Android may decide to kill your application. In such scenario, I have experienced cases in which android attempts to launch the last activity using the intent provided before the app was killed. In this cases, data stored in a singleton (either yours or Application) will be gone and bad things could happen. To avoid such cases, you either persist objects to disk or check data before using it to make sure its valid.
Use a singleton class
Have a class to whole the data:
public class DataHolder {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}
private static final DataHolder holder = new DataHolder();
public static DataHolder getInstance() {return holder;}
}
From the launched activity:
String data = DataHolder.getInstance().getData();
Use application singleton (I would recommend this)
The application singleton is an instance of android.app.Application which is created when the app is launched. You can provide a custom one by extending Application:
import android.app.Application;
public class MyApplication extends Application {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}
}
Before launching the activity:
MyApplication app = (MyApplication) getApplicationContext();
app.setData(someData);
Then, from the launched activity:
MyApplication app = (MyApplication) getApplicationContext();
String data = app.getData();
ρяσѕρєя K hit the nail on the head, you're running a method where constructors and fields go. To make the variables (the imageIDs) global, it's quite simple and there are a few ways of doing it. Declare them outside any method, and then assign them in your onCreate or onResume (which will always be called).
Try this:
public class MainActivity extends Activity implements View.OnClickListener {
//global variable
String[] imageIDs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get Intent here
Intent it = getIntent();
imageIDs = it.getStringArrayExtra("imageArray");
}
}
I have a listview in a class that should pass data to another class however it seems I am doing it wrong. Class A contains the listview and through an intent it sends the data back. Class B must receive the data and pass to a field. For that I use a bundle which contain the string and must pass it. However it seems I am doing something wrong. Any hints?
Class A.
public static final String Item = "shop";
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item3 = (String)arrayAdapter.getItem(position).toString();
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
intent.putExtra(Item,item3);
startActivity(intent);
//Toast.makeText(getActivity().getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
}
});
Class B.
Bundle argsss = new Bundle();
argsss = getActivity().getIntent().getExtras();
if(argsss != null){
String shop = argsss.getString(ClassA.Item);
testButton.setText(shop);
}
Stacktrace :
Process: nl.boydroid.loyalty4g.app, PID: 27526
android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.boydroid.loyalty4g.app/nl.boydroid.loyalty4g.app.redeempoints.RedeemItemFragment}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1636)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1430)
at android.app.Activity.startActivityForResult(Activity.java:3532)
at android.app.Activity.startActivityForResult(Activity.java:3493)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.Fragment.startActivity(Fragment.java:880)
at nl.boydroid.loyalty4g.app.redeempoints.SearchableShopList$1.onItemClick(SearchableShopList.java:90)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1524)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3531)
at android.widget.AbsListView$3.run(AbsListView.java:4898)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
This should work:
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
Problem with your code it that you're binding String into Intent object directly and not into Bundle. This is reason why your code is not working. Your Bundle is empty.
you have sent data through the intent not bundle so get the data in other activity as intent
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
note: Im not that knowledgeable in android so i dont know about Bundle class nor Intent class just want to share some thoughts.
Try this.
String shop = argsss.getString("shop");
the value of the Item which is your key (shop) because of this.
public static final String Item = "shop";
look at this ,
//you are putting or passing the value of item3 to Item which is your key named "shop"
intent.putExtra(Item,item3);
so you can only get the value using the key you set.
Update
try this
// first create a bundle for you to be able to use it later.
Bundle sampleBundle = new Bundle();
// then set the values you want. with the Item key.
sampleBundle.putString(Item, item3);
// then create the intent
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
// then put your bundle to intent.
intent.putExtras(sampleBundle);
startActivity(intent);
to get this try this.
Bundle bundle = this.getIntent().getExtras();
if(bundle !=null){
//Obtain Bundle
String strdata = bundle.getString("shop");
//do the process
}
note again: i havent compile it i dont have ide for android its just a hint.
or
if you want to use only intent to pass some value
use your code above then on the other class you can get it by :
Intent intent = getIntent();
//this is how you retrieve the data
String shop = intent.getStringExtra("shop");
Additional ref.
Intent
Fragment to Fragment Try this dude. :)
Fragment to Fragment . Look at the last answer it may help you finding some ways on how fragments work.
Another possible solution
Passing data fragment to fragment
Additional info.
I think you cant pass data from fragment to another fragment directly.
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Based on Fragment Documentation.
Question.
//note: not sure about the flow of the program. just want to ask.
ClassA extends Activity ClassB extends Activity
|| ||
ClassA call the FragmentClassA? FragmentClassB startActivity(ClassB)?
|| ||
FragmentClassA you want to pass data --> ? FragmentClassB
after that, you want to start the ClassB Activity class inside FragmentClassB?
Bundle add the object as serializable and send it to another fragment.
I am trying to pass a String from a class "Play" which extends Activity by using:
Bundle data = new Bundle();
Intent i = new Intent(Play.this, Receive.class);
String category;
data.putString("key", category);
i.putExtras(data);
Then, the "Receive" class which is a non Activity class and does not extend Activity will receive the String from "Play".
But when I try to receive the data using this code:
Bundle receive = new Bundle();
String passed;
receive = getIntent().getExtras();
passed = receive.getString("key");
I get an error on the word "getIntent()" and suggests me to create a method getIntent().
What is the possible solution to this problem?
THANKS!
Intent is not nessesary here. You can just do something like this:
Play.class :
public String getCategory() {
return category;
}
and in Receiver.class :
Play playObject = new Play();
passed = playObject.getCategory();
Or you can use static field as pKs mentioned but it's not always a good pattern.
You should use a public static variable and use it to store data and fetch data from other class.
As intents don't work without extending Activity class in Android.
In your case , it would be like.
public static category="some category";
To access in another class ,
String dataFromActivity=NameOFClassWhereCategoryIsDefined.category;
You cannot getIntent(); from within a class that does not extend Activity. As Sprigg mentioned you would have to use other means of communication between the classes.
When considering the case with android activity, the first method to work is its onCreate method..right?
Suppose i want to pass 2 parameters to android activity class say UserHome . For that am creating the constructor of activity class UserHome and accepting the params.
But when we are calling an activity we are not initializing the Activity class, we are just creating an intent of UserHome class.
Then how can we pass params to that activity from another activity without using intent.putExtra("keyName", "somevalue"); usage.
Experts please clarify how we can cover a situation like this.?
Not sure why you would not want to use the intent params. That is what they are there for. If you need to pass the same parameters from different places in your application, you could consider using a static constructor that builds your intent request for you.
For example:
/**
* Sample activity for passing parameters through a static constructor
* #author Chase Colburn
*/
public class ParameterizedActivity extends Activity {
private static final String INTENT_KEY_PARAM_A = "ParamA";
private static final String INTENT_KEY_PARAM_B = "ParamB";
/**
* Static constructor for starting an activity with supplied parameters
* #param context
* #param paramA
* #param paramB
*/
public static void startActivity(Context context, String paramA, String paramB) {
// Build extras with passed in parameters
Bundle extras = new Bundle();
extras.putString(INTENT_KEY_PARAM_A, paramA);
extras.putString(INTENT_KEY_PARAM_B, paramB);
// Create and start intent for this activity
Intent intent = new Intent(context, ParameterizedActivity.class);
intent.putExtras(extras);
context.startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Extract parameters
Bundle extras = getIntent().getExtras();
String paramA = extras.getString(INTENT_KEY_PARAM_A);
String paramB = extras.getString(INTENT_KEY_PARAM_B);
// Proceed as normal...
}
}
You can then launch your activity by calling:
ParameterizedActivity.startActivity(this, "First Parameter", "Second Parameter");
I can see one situation where you'd be unable to use the standard method of passing the parameters via the Intent: When you're creating an activity that will be launched by another app (say, the edit activity of a Tasker plugin) and, therefore, do not have control over the Intent that will launch your activity.
It's possible to create an Activity that accepts parameters in its constructor. The trick to using it, though, is not to use it directly, but to use a derived class with a default constructor that calls super() with the appropriate arguments, as such:
class BaseActivity extends Activity
{
public BaseActivity(String param1, int param2)
{
// Do something with param1 and param2.
}
// Many more lines of awesomeness.
}
class DerivedActivity extends BaseActivity
{
public DerivedActivity()
{
super("param1", 42);
}
}
Naturally, if you need to generate the parameters to pass to BaseActivity(), you can simply replace the hard-coded values with function calls.
We can pass the value from parent activity to child activity using the bundled collection and shared preference.
1. Shared Preference
2. Bundle Collection
Passing data or parameter to another Activity Android
But you also can create very well a constructor of UserHome.
public class MainActivity extends Activity {
UserHome userHome = new UserHome(param1,param2);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
userHome.yourMethod();
}}
Why do you think that is not possible to initialize a contructor?..MainActivity is a class like any other, just that extends Activity, but also keeps the properties of a class, so that can have, constructors, methods, members.
How do I pass custom objects between activites in android? I'm aware of bundles but I can't seem to see any functionality for this in them. Could anyone show me a nice example of this?
You should implement Parcelable interface.
Link to documentation.
Using Parcelable interface you can pass custom java object into the intent.
1) implement the Parcelable interface to your class like:
class Employee implements Parcelable
{
}
2) Pass the Parcelable object into the intent like:
Employee mEmployee =new Employee();
Intent mIntent = new Intent(mContect,Abc.class);
mIntent.putExtra("employee", mEmployee);
startActivity(mIntent);
3) Get the data into the new [Abc] Activity like:
Intent mIntent = getIntent();
Employee mEmployee = (Employee )mIntent.getParcelableExtra("employee");
a Parcel MIGHT solve your problem.
think of a Parcel as an "array" (metaphorical) of primitive types (long, String, Double, int, etc). if your custom class is composed of primitive types ONLY, then change your class declaration including implements Parcelable.
you can pass a parcelable object thru an intent with no difficulty whatsoever (just like you would send a primitive-typed object). in this case i have a parcelable custom class called FarmData (composed of longs, strings and doubles) which i pass from one activity to another via intent.
FarmData farmData = new FarmData();
// code that populates farmData - etc etc etc
Intent intent00 = new Intent(getApplicationContext(), com.example.yourpackage.yourclass.class);
intent00.putExtra("farmData",farmData);
startActivity(intent00);
but retrieving it may be tricky. the activity that receives the intent will check if a bundle of extras was send along with the intent.
Bundle extras = getIntent().getExtras();
FarmData farmData = new FarmData();
Intent intentIncoming = getIntent();
if(extras != null) {
farmData = (FarmData) intentIncoming.getParcelableExtra("farmData");// OK
}
Given an object PasswordState that implements Serializable throughout the object tree, you can pass this object to anther activity as in:
private void launchManagePassword() {
Intent i= new Intent(this, ManagePassword.class); // no param constructor
PasswordState outState= new PasswordState(lengthKey,timeExpire,isValidKey,timeoutType,"",model.getIsHashPassword());
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outState);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_PASSWORD); // used for callback
}
One simple way to pass an object between activities or make a object common for all applicattion, is create a class extending Application.
Here is a example:
public class DadosComuns extends Application{
private String nomeUsuario="";
public String getNomeUsuario() {
return nomeUsuario;
}
public void setNomeUsuario(String str) {
nomeUsuario = str;
}
}
In all your others activities, you just need instantiate one object "DadosComuns", declarating as a Global Variable.
private DadosComuns dadosComuns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//dados comuns
dadosComuns = ((DadosComuns)getApplicationContext());
dadosComuns.setNomeUsuario("userNameTest"); }
All others activities that you instantiate dadosComuns = ((DadosComuns)getApplicationContext()); you can acess getNomeUsuario() == "userNameTest"
In your AndroidManifest.xml you need to have
<application
android:name=".DadosComuns"