How can i pass variable from OnCreate to function(View view) - android

i have an activity that get a variable from another activity, and i want to display this variable when user click on button.
the problem is SaveFile(View view) method cannot find "SurveyTilte" variable.
How can i pass this variable?
public class CreateSurvey extends AppCompatActivity {
TextView Textfile;
String SurveyTilte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
Bundle extras = getIntent().getExtras();
SurveyTilte = extras.getString("SurveyTilte");
}
}
i can't, but the code in OnClickListener because there is an #Override method
public void SaveFile(View view) {
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(CreateSurvey.this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CreateSurvey.this, "Permission not granted", Toast.LENGTH_SHORT).show();
finish();
}
}

This is actually more a matter of java than android.
By doing:
protected void onCreate(Bundle savedInstanceState) {
...
String SurveyTilte = extras.getString("SurveyTilte");
}
What you actually do is creating a local variable separated from your class field variable with the same name, and is 'alive' and available for that specific method scope. Meaning you'll loose its reference (and thus its value) when exiting onCreate method.
What you need to do:
All you need to do is not to declare a new variable inside onCreate but to use the same variable you declared in advanced in your class attributes.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SurveyTilte = extras.getString("SurveyTilte");
}
That's how you can use the same reference for your value in the entire class scope.

Remove String keyword from String SurveyTilte = extras.getString("SurveyTilte"); to assign value to the class field and not local variable:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
Bundle extras = getIntent().getExtras();
SurveyTilte = extras.getString("SurveyTilte");
}
and then
public void SaveFile(View view) {
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte); // <-- reference field that contains value from intent data
}

I think this can help you.
public class CreateSurvey extends AppCompatActivity {
TextView Textfile;
String SurveyTilte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
}
}
public void SaveFile(View view) {
Bundle extras = getIntent().getExtras();
if(extras != null) {
SurveyTilte = extras.getString("SurveyTilte");
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte);
}
}

Related

Put EditText in First Activity to TextView on Second Activity

I'm french so sorry for my bad english.
I need to update on my second activity my TextView with a EditText of my first Activity. But I don't how to do.
That is my code on First Activity:
public class MainActivity extends AppCompatActivity {
private TextView mGreetingTextView;
private EditText mLoginEditText,mEmailEditText,mPasswordEditText;
private Button mLoginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGreetingTextView = findViewById(R.id.main_textview_info);
mLoginEditText = findViewById(R.id.main_edittext_login);
mEmailEditText = findViewById(R.id.main_edittext_email);
mPasswordEditText = findViewById(R.id.main_edittext_password);
mLoginButton = findViewById(R.id.main_button_log);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateLogin();
}
String login = mLoginEditText.getText().toString();
});
}
private void validateLogin(){
if (mEmailEditText.getText().toString().equals("admin#admin.com") &&
mPasswordEditText.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Login successful",Toast.LENGTH_SHORT).show();
callHome();
} else {
Toast.makeText(getApplicationContext(), "Wrong login",Toast.LENGTH_SHORT).show();
}
}
public void callHome(){
Intent i = new Intent(getApplicationContext(),HomeActivity.class);
i.putExtra("mLoginText", mLoginEditText.getText());
startActivity(i);
}
But I search a same topic who has the same problem and I don't find.
Apologize for my bad level on Android but I'm student on Android. This is my first topic on StackOverFlow ^^
You are calling mLoginEditText.getText() and that returns Editable. You will need to call mLoginEditText.getText().toString() and that will be a String.
You can update your second activity (HomeActivity) like this
public class HomeActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
textView = findViewById(R.id.textView);
// get the text from main activity
Intent intent = getIntent();
String text = intent.getStringExtra("mLoginText");
textView.setText(text);
}}
I found a result :)
MainActivity:
public class MainActivity extends Activity {
public final static String LOGIN_DATA = "mLoginText";
private EditText mLoginEditText,mEmailEditText,mPasswordEditText;
private Button mLoginButton;
private boolean isValid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoginEditText = findViewById(R.id.main_edittext_login);
mEmailEditText = findViewById(R.id.main_edittext_email);
mPasswordEditText = findViewById(R.id.main_edittext_password);
mLoginButton = findViewById(R.id.main_button_log);
mLoginButton.setOnClickListener(v -> {
isValid = validateLogin();
if (isValid){
callHome();
}
});
}
private boolean validateLogin(){
if (mEmailEditText.getText().toString().equals("admin#admin.com") &&
mPasswordEditText.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Login successful",Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(getApplicationContext(), "Wrong login",Toast.LENGTH_SHORT).show();
return false;
}
}
public void callHome(){
Intent i = new Intent(MainActivity.this,HomeActivity.class);
i.putExtra(LOGIN_DATA, mLoginEditText.getText().toString());
startActivity(i);
}
}
HomeActvity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mHelloText = findViewById(R.id.home_textview_hello);
Intent intent = getIntent();
String login = intent.getStringExtra(MainActivity.LOGIN_DATA);
mHelloText.setText(login);
With that, the login name of the first activity is in the second activity :)

Android studio create listener to variable

I have a question what is the best, easiest, shortest way to create custom(personal listener to value, I mean if I had some if statement that's will triggers when some boolean variable will changed.
The problem is the welcomeName initialize as null, so I need few milli seconds before I set a text.
So I want exectue a listener, that will do this when the welcomeName will not be null.
Thanks.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trinee);
findViewById(R.id.trainee_home);
findViewById(R.id.trainee_training);
findViewById(R.id.trainee_cancel);
setFragmentLayout();
String nameLast="";
Bundle bundle = getIntent().getExtras();
welcomeName = (TextView) findViewById(R.id.username_string);
nameLast = bundle.getBundle("personalBundle").getString("name")+
" "+bundle.getBundle("personalBundle").getString("last");
if(welcomeName!=null)
{
welcomeName.setText(nameLast);
}
}
If all should run on the Main/UiThread, then the best way is using LiveData.
LiveData<Integer> mLiveData = new MutableLiveData<>();
void onCreate(Bundle savedInstance) {
mLiveData.observe(this, new Observer<Integer>() {
#Override
public void onChange(Integer value) {
//"value" is the last value of "variable" you want to observe
}
});
}
then from anywhere in the same Activity/Fragment:
mLiveData.postValue(1);
....
mLiveData.postValue(2);
....
button.setOnClickListener(new ... {
void onClick(View v) {
mLiveData.postValue(3);
}
});
Not so working.. I will very thanksful if you can give me some example how do I need implement it
LiveData<String> mLiveData = new MutableLiveData<>();
String nameLast = "";
TextView welcomeName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
welcomeName = (TextView) findViewById(R.id.username_string);
nameLast = bundle.getBundle("personalBundle").getString("name") +
" " + bundle.getBundle("personalBundle").getString("last");
mLiveData.observe(this, new Observer<String>() {
#Override
public void onChanged(String str) {
welcomeName.setText(str);
}
});

I want to Pass the result of the QR Code from ScannerCodeActivity to the TextView in ResultWebService

I want to passe the result of the QR code from the ScanCodeActivity to the TextView in other layout called ResultWebService.
#Override
public void handleResult(Result result) {
ResultWebService.resultTExtViewCode.setText(result.getText());
onBackPressed();
}
this is my ResultWebService :
public class ResultWebService extends AppCompatActivity {
public static TextView resultTExtViewCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_web_service);
resultTExtViewCode = (TextView) findViewById(R.id.textViw_QRcode);
}
}
How can i do this please ?
You can do that, but the better way is to send it in the intent as extras, or have a global variable and assign the text value of the result there.
Intent i=new Intent(context);
i.putExtra("QrText", result.getText());
context.startActivity(i);
and to get it in the other activity
Bundle extras = getIntent().getExtras();
String qrText;
if (extras != null) {
qrText = extras.getString("QrText");
}
// after you do the findViewById
resultTExtViewCode.setText(qrText)

Put And Get Extras From Another Class

I have Act_01 (where I put value) and Act_02 (where I get value) but have declared these methods in a Extras class, getting value from Act_02 returns null value:
Act_01: (Where I want to pass the value Name to Act_02)
public class Act_01 extends Activity {
Extras cc_Extras;
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
cc_Extras = new Extras();
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cc_Extras.putExtras();
startActivity(intent);
}
});
}
}
Act_02: (Where I want ot receive value Name from Act_01 but the app crashes with null value)
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras();
if(getIntent() != null && getIntent().getExtras() != null)
{
cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras: (Where I define the methods to put and get Extras)
public class Extras extends Activity {
String str_Name;
Intent intent;
public void putExtras() {
// TODO Auto-generated method stub
intent.putExtra("KEY_Name", str_Name);
}
public void getExtras() {
// TODO Auto-generated method stub
str_Name = getIntent().getExtras().getString("KEY_Name");
}
}
EDIT: I do not want to pass and get data directly between activities, I want to use the 3rd class (Extras.java) because I have too many activities having too many values between each other and want to sort of define them globally in Extras so that all my other activities can just call one method instead of getting and putting too many values in my activities.
Your app crashes not with a null value, but a null pointer reference because you created a new Activity manually
cc_Extras = new Extras();
Then called a lifecycle method on it
cc_Extras.getExtras()
Which calls getIntent(), but the Intent was never setup by the Android framework, and cc_Extras.getExtras() wouldn't have any of the data you wanted anyway in the second Activity because it was just created there, not from the first Activity.
Briefly, you should never make a new Activity, and your Extras class does not need to be an Activity in the first place (nor does it provide much benefit).
Just use the Intent object provided by the first Activity to start the second Activity, and get extras like normal. Don't overcomplicate your code. Regarding the title of the question, Intent and Bundle are already "another class" designed by Android for you to transfer data.
On both activities you are creating a new instances of Extras class means they dont hold the same value you can do this to transfer data from A to B
public class Act_01 extends Activity {
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intent = new Intent(Act_01.this, Act_02.class);
intent.putExtra("data", str_Name)
startActivity(intent);
}
});
}
}
And receieve data like this
public class Act_02 extends Activity {
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
// cc_Extras = new Extras();
if(getIntent() != null)
{
if (getIntent().getStringExtra("data") != null) {
Toast.makeText(Act_02.this, "Name: "+getIntent.getStringExtra("data"), Toast.LENGTH_SHORT).show();
}
}
}
}
Also you should consider using Activity Context instead of the application context
Ok! so here are the few things I might wanna suggest you to correct.
Changes needs to be done in the code.
You are not assigning anything to "intent" object , and you have passed a intent without assigning anything to it.
Your instance cc_Extra isn't doing anything in the activity1. You might wanna pass the "intent" object in your constructor of class like cc_Extras= new Extras(intent); and in the Extras class do the following- Intent intent;
Extras(Intent i)
{
this.intent=i;
}
In the activity2 you are creating the new Instance of Extras(). So according to your code it is going to be NULL by default. If you have done the changes from the previous step, you can create new instance by doing cc_Extras(getIntent());
Corrections in the code
1) In Extras class getExtras() method instead of str=getIntent() use str=intent.getExtras.getString().
2) In the activity2 you are not assigning anything to your String str_Name, so you need to return the string you got in getExtras() method. You can do it by changing the return type to String. Below is the sample code.
public String getExtras()
{
str_Name=intent.getExtras().getString("KEY_Name");
//OR
//str_Name=intent.getStringExtra("KEY_Name");
return str_Name;
}
3) By the doing this you need to catch this string in the activity2 by doing `
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}`
4) Another thing is you must create intent like this-
Intent intent=new Intent(currentActivityName.this,anotherActivity2.class);
//then use the intent object
EDIT- Your code must look like this in the end...
Act1
public class Act_01 extends Activity {
Extras cc_Extras=null;
Button btn1;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//changes to do
Intent intent= new Intent(Act01.this,Act02.class);
cc_Extras= new Extras(intent);
cc_Extras.putExtras(str_Name);
//end
startActivity(intent);
}
});
}
}
Act02
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras(getIntent());
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras class
public class Extras { //remove "extends Activity" because it is a class not a activity
String str_Name;
Intent intent;
Extras(Intent i)
{
this.intent=i;
}
public void putExtras(String str) {
// TODO Auto-generated method stub
str_Name=str;
intent.putExtra("KEY_Name", str_Name);
}
public String getExtras() {
// TODO Auto-generated method stub
str_Name = intent.getExtras().getString("KEY_Name");
return str_Name;
}
}
Above code will work just on String. You can extend the functionality if you want.
I hope this must work to get your code working!

android if-statement doesn't work

public class MainActivity extends Activity
{
public static String EXTRA_MESSAGE;
private Intent ceec;
private EditText cc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);}
public void sendMessage(View view)
{
ceec = new Intent(this, ToActivity.class);
cc = (EditText) findViewById(R.id.edit_message);
String message = cc.getText().toString();
ceec.putExtra(EXTRA_MESSAGE, message);
startActivity(ceec);
}}
And
public class ToActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setText(message);
textView.setTextColor(Color.rgb(5,8,100));
if( message == "hi"){
textView.setTextSize(80);
}
// Set the text view as the activity layout
setContentView(textView);
}}
[ if( message == "hi"){
textView.setTextSize(80);
} ]
It didn't work why? And how to fix it and thank you
Instead of
message == "hi"
You should do:
message.equal("hi")
Never compare Strings with ==, check out this question to understand why.
Use .equals() method as,
if(message.equals("hi")){
textView.setTextSize(80);
}
else
{
// do your else stuff
}
this should work.

Categories

Resources