I am new to Android programming and having a problem in passing a filepath from my main activity to second activity.
Here is my code in Main activity to pass two variables walletDir(contains path) and password.
private File walletDir;
private final String password = "pass";
Intent intent= new Intent(Create_Wallet.this,Wallet_Address.class);
intent.putExtra("EXTRA_WALLET_DIR", walletDir);
intent.putExtra("EXTRA_PASSWORD", password);
startActivity(intent);
Here is my code for second activity
Intent intent = getIntent();
String walletDir = intent.getStringExtra("EXTRA_WALLET_DIR");
String password = intent.getStringExtra("EXTRA_PASSWORD");
Now password is being passed but not walletDir its null and the error i am getting is:
W/Bundle: Key EXTRA_WALLET_DIR expected String but value was a java.io.File. The default value <null> was returned.
private File walletDir;
walletDir is an instance of File.
intent.putExtra("EXTRA_WALLET_DIR", walletDir);
This puts an instance of File into your Intent as an extra. This works because File implements the Serializable interface, and there is a putExtra() method that takes a Serializable.
String walletDir = intent.getStringExtra("EXTRA_WALLET_DIR");
The extra is not a String. Yet, you call getStringExtra() to read it. This is not going to work, because a File is not a String.
Change that line to:
File walletDir = (File)intent.getSerializableExtra("EXTRA_WALLET_DIR");
(it is possible that you do not need the cast — it has been quite some time since I did this in Java)
You might also consider whether you really should be using two activities here. Android is moving very strongly towards having fewer activities, with fragments or composables representing individual screens displayed by those activities.
Related
I created a "Settings Activity" which has a radio button group with three buttons. Each button is coded to pass a different string to sharedPreferences. Each string is the name of an Activity in the project.
1.) DollarActivity
2.) DynamicPercentActivity
3.) StaticPercentActivity
(I used the Device File Explorer to confirm the string are being saved to sharedPreferences successfully)
My idea was to retrieve the string data saved to sharePreferences and replace varActivity which forms part of the Intent below.
Intent intent = new Intent(getApplicationContext().this, varActivity.class);
startActivity(intent);
I tried to create a variable "varActivity" which retieve the relevant string from sharedPreferences, however it did not work. Android Studio prompted me to create class varActivity or innerclass varActivity or interface varActivity. I tried to the create class approach, however this effort created additions problems to be solved (public static void / public void compatibility issues between Activities).
Is there some way retrieve the string from sharePreferences and replace varActivity with the new string data.
There is no way to launch activity by name, but your task still can be implemented, if you put classes with their names in Map.
Map<String, Class> activities = new HashMap<String, Class>() {{
put("DollarActivity", DollarActivity.class);
put("DynamicPercentActivity", DynamicPercentActivity.class);
put("StaticPercentActivity", StaticPercentActivity.class);
}};
...
new Intent(this, activities.get(nameFromPreferences));
Anyway, I definitely recommend you to think again of the task you are trying to solve and find better solution.
My activity class contains a constructor that computes some data:
public IPrintPanelActivity(String title, Object data, byte logoChar,
String keyName, boolean printNCopies, boolean showPrintButton) {
/*
* Configure the panel
*/
super();
panelTitle = title;
this.logoChar = logoChar;
if (data != null) {
setTextArea((String) data);
}
//put the display print panel here
SignOnActivity.startMyActivity(context,(String) data,"CORRECT?");
finish();
}
Then I need this data Object (which is actually a string) to display it in a TextView of the associated layout file. The problem is that I don't know how to get data "out of the constructor" to write something like
myTextView.setText(data);
I found an answer to a question that was asked more than 2 years ago and it seems to be what I need. The problem is that I get a NullPointerException for the context variable.
Here's the definition of the static function startMyActivity:
public static void startMyActivity(Context context, String paramA, String paramB) {
// Build extras with passed in parameters
Bundle extras = new Bundle();
extras.putString("PARAM_A", paramA);
extras.putString("PARAM_B", paramB);
// Create and start intent for this activity
Intent intent = new Intent(context,IPrintPanelActivity.class);
intent.putExtras(extras);
context.startActivity(intent);
}
Do I give you enough information? Please let me know and please help me fix the NullPointerException.
Do not create constructors for your Activity classes. The Android OS is responsible for instantiating Activities and will only try to do so with the default constructor. Keep in mind that an Activity may be destroyed and recreated by the system at various times, usually during configuration changes, such as when the device is rotated between portrait and landscape orientations.
Any "arguments" you pass to an Activity should be done using a Bundle in the Intent that starts the Activity. In one of the lifecycle callback methods (e.g. onCreate()) you can call getIntent() and check its extras for data, then do as you wish.
The link you posted where the user Chase create d static method for starting an activity still follows these guidelines. All his method does is compose the Intent and its extras using the arguments of the static method, then calls startActivity using this Intent. He did not create a constructor for the Activity, nor did he ever call new to instantiate an Activity. He just simplified the process of creating the Intent and its extras to start the Activity with the proper data.
You don't have constructors explicitly for Activties. You don't instantiate a Activity class. You only declare the Activity in manifest file.
Please read the answer by Raghav Sood
And i quote Raghav
By treating an Activity as a normal Java class, you end up with a null
context. As most methods in an Activity are called on its Context, you
will get a null pointer exception, which is why your app crashes.
Can i Create the object of a activity in other class?
I have created an remote controller app in android. In the main page,there are few keys which on pressing sends a signal from the mobile. First of all it asks for a configuration file and parse the file and save the control options in a spinbox. When a particular key is pressed he corresponding control from the spinbox is selected and the signal is sent.
In next screen i would like to have only the keys which on pressed should select the control in the main screen and it should send the signal. In short i should be able to access all the elements in my main_screen.java.
In this you can access your keys in second screen by sending keys from first screen by click on button through this code
Intent in=new Intent(this,yournextActivity.class)
e.g:- my current class is hello.java and next class is Applet.java then through intent
Intent in=new Intent(hello.this,Applet.class)
to pass data to next class use this...
in.putExtras(key,value);
e.g:- my value is String s="Welcome" then i can pass this s to next class like this
in.putExtras("Yours",s);
key should be any text.....
on second class receive this String through this code
Intent in=getIntent();
String m=in.getStringExtras("Yours");
where m is receiving string and "Yours" is the key that you pass from first class...
if you want to pass data from one activity to another, you can do that with the help of intent
to pass data use putExtras()
Intent intent = new Intent(this, yourSecondActivity.class);
intent.putExtra("key", "Value");
startActivity(intent);
and to receive it in second activity use:
getIntent().getExtras().getString("key");
Note i am explaining above as assuming that i am passing data of string type ! so while receiving data, it depends on type of data you are receiving get that accordingly like i used geString("key");
you could pass things by using intents, but have you considered using fragments instead of multiple activities ?
it could even be better if you actually wish the app to work on large screens.
I want to pass strings to all pages in my android app. When the user logs in I save userName and others to strings. I want to send the strings over multiple pages. How can I do that?
I have tried to send it through Intent
Intent myIntent = new Intent(view.getContext(), Help.class);
myIntent.putExtra("userName", userNameString);
startActivityForResult(myIntent, 0);
But when I go to another page I dont want to keep sending the data through Intent every time.
I have tried to get it from the class where I parse and put them in strings
HomeScreen home = new HomeScreen();
String userName= home.userNameString;
But since i am creating a new instance of the HomeScreen then userNameString is null
Any help will be greatly appreciated
Beware of using a static or instance variable to hold this state as the memory state of an Android application can be in flux. Data only stored in memory can be destroyed without your knowledge if your application process is killed while in the background.
The simplest mechanism would be to persist your data into SharedPreferences that you can access from any place in the application. So, first you save the string that you get from login (this is called inside an Activity, FYI):
//Write the username string to preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("userName", userNameString).commit();
Then elsewhere in your application (i.e. other Activity instances) can read that string:
//Read the username string
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("userName", "");
With SharedPreferences, your values are actually persisted, meaning they will live forever on disk and won't go away just because your application's memory is reset (this is usually an advantage, especially for login information). Because of this, you will also need to remove the string when your user "logs out" like so:
//Remove the username string from preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().remove("userName").commit();
There are also methods like contains() to allow you to check if the value is currently saved (is the user logged in?), etc.
The calling Activity is not guaranteed to remain in memory... the Android system may destroy it at any time.
If the child Activity depends on the user name, then the correct means of passing the information is with an Intent.
Declare a static variable and use it from everywhere:
public class SomeClass
{
public static String userNameString;
}
Use it like:
Strign s = SomeClass.userNameString;
Change its value as:
SomeClass.userNameString = "new string";
I am using 2.3.3 version of the Android SDK and I'm trying to pass data between two activities using the following code
Intent myIntent = new Intent(MainAct.this, FriendsActivity.class);
myIntent.putExtra(USER_NAME, ((EditText)findViewById(R.id.username)).getText());
MainAct.this.startActivity(myIntent);
In the FriendsActivity i'm retrieving the value using
Bundle b = getIntent().getExtras();
String user = b.getString(MainAct.USER_NAME);
But the user is null after these lines are executed. Not sure whats wrong here. Read similar questions on SO http://goo.gl/zOJfa but still the problem continue to be seen.
You need to pass (EditText)findViewById(R.id.username)).getText().toString() instead. getText() on an EditText View doesn't return a string, it returns an Editable Object.
just do (EditText)findViewById(R.id.username)).getText().toString() you are able to get string value.