Currently I try to learn about creating an android app and work through a Tutorial on it using android studio.
So far, I've created two activites.
The Main activity features a Plain Text Field and a Button. The other activity displays the input of the Plain Text Field when pressing the Button.
The Tutorial ends here.
For fun purpose, I want to change it to the second activity displaying certain text on one special input. Now the line to determine if input is equal to certain String looks like this:
String result = message.equals("foo?") ? "bar" : "wrong";
As long as I leave the Questionmark at the end of "foo?", it sets result to "wrong", although I intend it to be bar.
(With message being the content of the Plain Text Field from the Main Activity)
MCVE Attempt
Main Activity
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Go Button */
public void sendMessage(View view)
{
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString(); //User puts in "foo?"
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}}
Second Activity (Showing the result)
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = findViewById(R.id.textView3);
String result = message.equals("foo?") ? "Bar" : "wrong"; //result is set to "wrong"
textView.setText(result);
//But "Bar" expected
}}
Changing userinput to foo instead of foo? and removing the questionmark in .equals("foo?") (to .equals("foo")) produces correct output. Hope thats enough
Related
Multiple Activity App...Activity1 (SiteData) collects data and sends to Activity10 (DataReview)...but before going straight to Activity10 user must go through Activities2-9 (SanDiegoArea, etc...) collecting data and also passing EXTRA_TEXT to the other activity until Activity10...
This way:
(Activity1 -> Activity2 -> ... -> Activity10)
Activity10 will be able to review Activity1-9 EXTRA_TEXT for verification...Code is as follows but I'm getting no EXTRA_TEXT at Activity10 to display in it's TextViews for review? How can I solve the problem?
Activity1 - SITEDATA - data info input
public class SiteData extends AppCompatActivity {
public static final String EXTRA_TEXT = "MultipleActivities.EXTRA_TEXT";
public static final String EXTRA_NUMBER = "MultipleActivities.EXTRA_NUMBER";
public void clickFunction(View view) {
Intent intent = new Intent(getApplicationContext(), SanDiegoArea.class);
startActivity(intent);
Log.i("Info", "Login Details Entered");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sitedata);
//Possible coding needed for Autocomplete...see more
Button button = (Button) findViewById(R.id.buttonSend);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openSanDiegoArea();
}
});
}
public void openSanDiegoArea() {
EditText editText1 = (EditText) findViewById(R.id.editTextName);
String text = editText1.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.editTextPhone);
int number = Integer.parseInt(editText2.getText().toString());
Intent intent = new Intent(this, DataReview.class);
intent.putExtra(EXTRA_TEXT, text);
intent.putExtra(EXTRA_NUMBER, number);
startActivity(intent);
}
}
ACTIVITY10 - DATAREVIEW Section getting info
public class DataReview extends AppCompatActivity {
public void clickFunction(View view) {
Intent intent = new Intent(getApplicationContext(), ThankYou.class);
startActivity(intent);
Log.i("Info", "Sample Data Sent to BWTF");
}
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datareview);
Intent intent = getIntent();
String text = intent.getStringExtra(SiteData.EXTRA_TEXT);
int number = intent.getIntExtra(SiteData.EXTRA_NUMBER, 0);
TextView textView1 = (TextView) findViewById(R.id.editTextName);
TextView textView2 = (TextView) findViewById(R.id.editTextPhone);
TextView textView3 = (TextView) findViewById(R.id.editTextEmail);
TextView textView4 = (TextView) findViewById(R.id.editTextDate);
TextView textView5 = (TextView) findViewById(R.id.editTextTime);
textView1.setText(text);
textView2.setText("" + number);
}
};
If Activity1 calls Activity2, it will have to pass data to it the way you are doing. ( I'm guessing here that your Activity2 is DataReview.class)
But Activity2 will call Activity3 and, in order for it not to loose the data received from activity 2 you will have to send it too. In other words, Activity1 sends Activity1's data to Activity2, Activity2 sends Activity1's and Activity2's data to Activity3 and so on.
In this way, Activity9 will receive (1, 2, 3, 4, 5, 6, 7, 8) data from it's caller Activity8 and will have to pass all this accumulated data to Activity10.
Considering that Activity3 is called by Activity2 it can't see the data sent from Activity1 because it don't know it unless Activity2 pass it too. Am I been clear?
If you are just learning Android it is ok to do it this way in order to learn but it is not the better way to solve this problem. I would use a same ViewModel on all activities in order to represent this data in order to always have just one place for holding it as it would make my code more clear. In reality I wouldn't even use all those Activities, I would use only one activity and work with 10 fragments, one for each page (it is just to provide navigation between then). So those are Ideas for you to improve your app if you feel It would be good.
So I have made a simple app that currently has an EditText input with a button that, onClick, takes user to a specified website + the user input at the end.
However, my EditText input doesn't seem to "connect" with my declared String and therefore no input value gets detected, taking the user straight to the default website as the button is pressed.
I have tried this code:
rns = et.getText().toString();
Where "et" is the declared name of the EditText input, and "rns" is the declared name of the String to read the input.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText et;
String rns; /* Declarations here */
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.regNum); /* regNum is android id */
rns = EditText.getText().toString(); /* This is the line in question,
with a red underscore on "getText() due to being referenced from a static context */
b = (Button) findViewById(R.id.regBut); /* regBut is android id */
b.setOnClickListener(MainActivity.this);
}
public void onClick(View v){
if (v == b){
Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse
("https://www.vegvesen.no/kjoretoy/Kjop+og+salg/Kjøretøyopplysninger?
registreringsnummer=" + rns));
startActivity(browserIntent);
}
}
I expected the EditText input field "et" (id = regNum) to detect the user input, but it doesn't at all. One thing I hadn't considered was it not detecting numbers, but I checked and it didn't detect letters alone either.
(Test results were all with the aforementioned code:
rns = et.getText().toString();
)
Your code should have been:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText et;
String rns; /* Declarations here */
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.regNum); /* regNum is android id */
b = (Button) findViewById(R.id.regBut); /* regBut is android id */
b.setOnClickListener(MainActivity.this);
}
public void onClick(View v){
if (v == b){
/* Get the string from the edittext on button press */
rns = et.getText().toString();
Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse
("https://www.vegvesen.no/kjoretoy/Kjop+og+salg/Kjøretøyopplysninger?registreringsnummer=" + rns));
startActivity(browserIntent);
}
}
You retrieve your EditText via et = (EditText) findViewById(R.id.regNum);, so you should retrieve it using the et variable you just declared:
et.getText().toString()
You are accessing the method directly from class name, (not on the instance of your object) and calling getText() from it, to which in my recollection is not a static method.
Also have you tried checking against the view id on your onClick callback? v == b is not always true in this case.
Try
public void onClick(View v){
if (v.getId() == R.id.regBut){
...
}
}
You can also check out JakeWharton's ButterKnife for injecting views from xml to your code. So you won't have to do findViewById() and you can annotate #OnClick to your respective methods.
I am using AsyncTask to perform Background task, After completing my task, I want to set the resultant string from onPostExecute method to another activity's constructor and from there I want to set that string to TextView. when I print log inside the constructor it's printing the string, but when i set the same string on textview, it gives empty string.(the string set on textview is empty, so it simply prints nothing.)
My AsyncTask Code :
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("Answer1",s);
new Answer(s);
}
My Answer Activity, in which I am setting the string via constructor and setting value of this string on textview, but this string is empty.
public class Answer extends AppCompatActivity {
TextView textView;
String str;
// Dont Delete this
Answer(){
}
// Here, Log will print right string, but not on textview
Answer(String str){
this.str = str;
Log.d("Answer2",this.str);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
textView = findViewById(R.id.SetSteps);
// The String set here is empty, can you please elaborate???
textView.setText(str);
}
}
You should never instantiate an Activity youself. The correct way is to pass the desired data througn an intent to the new activity:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Intent intent = new Intent(CurrentActivity.this, Answer.class);
intent.putExtra("MY_DATA", s);
startActivity(intent);
}
Then in your Answer activity you can receive the value:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
textView = findViewById(R.id.SetSteps);
String result = getIntent().getExtras().getString("MY_DATA","");
textView.setText(result);
}
1 - Add a Context variable to your AsyncTask
Context context = getApplicationContext();
2 - in onPostExecute, create a new intent, add your string to the intent and start the activity :
Intent intent = new Intent(context, Answer.class);
intent.putExtra("Answer1",s);
context.startActivity(intent);
3- in your Answer activity, you can get the string from the intent like below:
Intent intent = getIntent();
String answer = intent.getStringExtra("Answer1");
if(answer !=null){
// do what you want
}
PS: Please please, remove constructors from your Activity, it is not recommended
I am working on a code and the part of converting the string into and integer as shown above is causing the application to stop working before it starts when I upload it to the mobile.
I have reduced the code as minimum as possible. the following code is giving the exact same problem. What would the solution be?
String no=edttxt.getText().toString(); //this will get a string
int no2=Integer.parseInt(no); //this will get a no from the
This is my code:
public class MainActivity extends Activity {
TextView txtview;
EditText edttxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtview=(TextView)findViewById(R.id.textView);
edttxt=(EditText)findViewById(R.id.edittxt);
String no=edttxt.getText().toString(); //this will get a string
int no2=Integer.parseInt(no); //this will get a no from the string
Button btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtview.setText(edttxt.getText());
}
});
}
}
You should be getting a java.lang.NumberFormatException because as soon as the app starts you are getting the string from edittext in onCreate(). This would return "" which would cause the exception in the line Integer.parseInt(). Depending on your use case for no2, you need to move it accordingly.
So basically my question is just explained in the title. How can I send data between activities without having to start that activity which receive the data. Here's my code: This is the main activity sending the data :
public class MainActivity extends Activity {
private EditText mainedit1;
private TextView maintext1;
private Button mainadd1;
private Button maindone1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
maindone1=(Button) findViewById(R.id.maindone);
mainedit1=(EditText)findViewById(R.id.mainedit1);
maintext1=(TextView)findViewById(R.id.maintext1);
mainadd1=(Button)findViewById(R.id.mainadd);
mainadd1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test1= mainedit1.getText().toString();
Intent intent = new Intent(MainActivity.this,test.class);
intent.putExtra("word",test1);
startActivity(intent);
}
});
And this is the activity receiving the data :
public class test extends Activity {
TextView testtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fortest);
testtext=(TextView)findViewById(R.id.testtext);
Intent intent = getIntent();
String Word = intent.getStringExtra("word");
testtext.setText(Word);
}
So what I did in here is to send the data but also starting the activity, and this is not what I want to share. Please show me how do I fix my code?
It seems you're just looking to save a string for later use. In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);
You can use sharedprefrence of android following code you can implement
In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);
OR
Sending data without having to start a new Acitivity, by create static variable
ex.
public class First_Activity extends Activity {
public static String USER_FORMATED_NUMBER = null;
USER_FORMATED_NUMBER="Data you want to pass";
}
public class Second_Activity extends Activity {
String data=First_Activity.USER_FORMATED_NUMBER;
}