pass variable from view to activity - java

I have been studying some code trying to learn more, the basic code is very simple. There is a xml layout file, and activity file and view file.
Eg.
simpleprog_layout.xml, SimpleProgView.java and SimpleProgActivity.java
I was looking at how a number of things are done and was trying to work out how a value could be passed from the view file for use in the activity file.
Can some one point me in the right direction?

Value being passed from View to Activity .
If it's to do with attaining reference of the View . It can be done using 2 Approaches
FindviewById()
ViewBinding
And if you'd wish to share a View's value to Another Activity , or to another view of Any other activity it can be achieved majorly in two ways .
Intents
Global Variables
Let's say for example there exists a String "name" and you wish to pass it to the ProfilePage of your application
Intent intent = new Intent(getBaseContext(), ProfileActivity.class);
intent.putExtra("user_name", username); // where Tag is user_name and the variable that holds value is username
startActivity(intent);
and the activity is able to receive the value using :
String userNameFromAnotherActivity= getIntent().getStringExtra("user_name"); // same Tag should be used
And with respect to global variable , any Activity is able to access the value with held in that variable.

Related

Passing Filepath to second activity in andriod studio

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.

Get text of textView from another activity

I am trying to get text from textview which is located in class 2 to use it in class 1 by pressing a button. I do this by sending an Intent, but i got the error of my content. That is what i am trying to send (from class 2 to class 1):
public static void intent_send(){
Intent i = new Intent();
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
class2.startActivity(i);
}
text_view_current_page is a static TextView, otherwise it has an error in this void. I call this void by pressing a button in class 1:
Class2.intent_send();
Intent i = getIntent();
Bundle b = i.getExtras();
PagerNumber = b.getInt("number");
I have an error in the line of the content definition:
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
What should i do with this textView to be able get it's text from another class by pressing a button? Should it be static or should i declare it in that class which receives an intent?
In Android activities are fully separated components and hence those cannot access each other's stuff directly. Those have their own window and view hierarchy which are private only to the owner activity itself.
Nevertheless there are a couple of ways for activities to interact with each other.
Sending data when you are starting second activity via Intent.
Utilizing Application object as a share object among all app's components.
Registering in-activity broadcast receivers by which you can send signals between activities.
My Recommendation for your case:
If in your case, the second activity should have a very close relation with the first one (e.g. accessing its view hierarchy), you could implement the second activity as a dialog or fragment not an activity.

How to Activate Button?

my context menu has two options Silly and Cool. I want to provide one item named activate to list item silly and second item named deactivate to list item cool.
How can i do that.??????
Help
1.If you want to start the second activity(and activate the settings) when Activate button is pressed you can use Intent to send a String or Integer(0 or 1) to know in the second activity that button was pressed.
You can find more information about sending data with Intent here
2.If you don't want to start the second activity when button is pressed but still activate the settings, you can make another class(Utils.java) where you can define all your settings(vibration, volume, ringtone) in methods and call them like that:
Utils mUtils = new Utils();
mUtils.activateVibration();
mUtils.playRingTone();
mUtils.setVolume(volumeLevel);
Hope it helps!
You can use intent.putExtra - put some information there, for example some object, String, whatever you want.
Then in your second activity just get those extras by
Bundle extras = getIntent().getExtras();
And for example if u have some boolean stored then you do:
boolean something = extras.getBoolean("keyToThatBoolean");

using a constructor in an Activity class and trying to get information out from that constructor to display on the associated screen

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?

how to start a new activity in one page on clicking a button in other page

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.

Categories