how to properly use intent? Android beginner - android

I am a beginner in android and I am trying to learn how to use intent.
In my code, I am trying to send 2 integers to a different activity and perform some calculation and return back in the Main activity with the answer.
This is my main activity and with a click of a button it should send 10, 50 to my calculate class and from there I will click operator buttons like add, multiply, divide and send back the answer here in main activity.
So far I am able to received these numbers to my Calculate class and perform operation there but I am not sure how to get back here in main activity with the answers.
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(getIntent() != null){
String msg = getIntent().getStringExtra("MSG");
int result = getIntent().getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivity(i);
}
}
Calculate class
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent i = new Intent(this, MainActivity.class);
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
}
}

you can use startActivityForResult and onActivityResult methods. fist in main activity you call startActivityForResult that means you want to get result from secondActivity (Calculate activity) and then override onActivityResult in main activity to get result.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(getIntent() != null){
String msg = getIntent().getStringExtra("MSG");
int result = getIntent().getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivityForResult(i, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent returnIntent = Intent(this, MainActivity.class);
returnIntent.putExtra("result",calc );
setResult(RESULT_OK,returnIntent);
finish();
}
}

public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent i = new Intent(this, MainActivity.class);
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
startActivity(i);
}
}
You need a startActivity(i); in add() function.

You can do this by
onActivityResult()
method of android intent.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(data.getExtras().containsKey("widthInfo")){
width.setText(data.getStringExtra("widthInfo"));
}
if(data.getExtras().containsKey("heightInfo")){
height.setText(data.getStringExtra("heightInfo"));
}
}
See these links for more info:
http://developer.android.com/training/basics/intents/result.html
http://www.java2s.com/Code/Android/UI/CheckActivityresultandonActivityResult.htm
http://www.mybringback.com/android-sdk/12204/onactivityresult-android-tutorial/

It looks like you should be using startActivityForResult() here.
So, in your MainActivity, your onClick() would be modified to call startActivityForResult():
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivityForResult(i, 100); //modified
}
Then in MainActivity, you would also add onActivityResult to get the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK){
String msg = data.getStringExtra("MSG");
int result = data.getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
Then, in the Calculate Activity, you would calculate the result, and send it back to MainActivity in an Intent, which will send the the MSG and result to onActivityResult() in MainActivity:
public void add(View v){
calc = first + second;
Intent i = new Intent(); //modified
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
setResult(RESULT_OK,i); //added
finish(); //added
}
Note that the reason it would be better for you to use startActivityForResult() here is that it would prevent having to add multiple Activities onto the back stack.
Say for example, you do two calculations (two trips from MainActivity to Calculate and back).
If you just used startActivity(), your back stack would then look like this:
MainActivity->Calculate->MainActivity->Calculate->MainActivity
And, it would just keep growing the more calculations you do.
Using startActivityForResult(), you are always just adding an instance of Calculate to the back stack, and then popping it and returning to the same instance of MainActivity. So, your back stack would always be just:
MainActivity
or...
MainActivity->Calculate
depending on which Activity you are currently in. As you can see, this is a huge improvement over the first option, which just keeps growing as you do more calculations.

Related

On activity finished

I'm developing an notepad app, and i need to reload the notes on the view when the Note Editor is closed (i'm using Finish() to close the Editor), but I am not sure how to wait until the Activity closes and does something.
I'm starting the Editor Activity with this:
public async void noteClicked(object sender, EventArgs e)
{
var obj = (RelativeLayout)sender;
var id = obj.Id;
var note = Util.db.Query<Note>(string.Format("SELECT * FROM Notes WHERE ID={0}", id));
var intent = new Intent(this, typeof(EditorAcitivity));
intent.PutExtra("Note", JsonConvert.SerializeObject(note));
intent.PutExtra("Mode", "Edit");
StartActivity(intent);
}
On the EditorActivity.cs:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.editor_activity);
Util.context = this;
mode = Intent.GetStringExtra("Mode");
txtTitle = FindViewById<EditText>(Resource.Id.editorTitle);
txtText = FindViewById<EditText>(Resource.Id.editorText);
if (mode == "Edit")
{
note = JsonConvert.DeserializeObject<Note>(Intent.GetStringExtra("Note"));
txtTitle.Text = note.title;
txtText.Text = note.text;
}
FindViewById<ImageButton>(Resource.Id.editorDelete).Click += editorDelete_Clicked;
FindViewById<ImageButton>(Resource.Id.editorSave).Click += editorSave_Clicked;
}
private void editorSave_Clicked(object sender, EventArgs e)
{
if (txtText.Text.Length == 0 || string.IsNullOrWhiteSpace(txtText.Text))
{
Util.makeShortText("Null text");
}
else
{
var note = new Note();
note.date = Util.now();
note.text = txtText.Text;
if (string.IsNullOrWhiteSpace(txtTitle.Text))
{
note.title = " ";
}
else {
note.title = txtTitle.Text;
}
Util.db.Insert(note);
this.Finish();
}
}
I want to do something like loadNotes() when the Activity is finished (this.Finish())
Edit: I don't wanna return some data, just wait the activity.
I would suggest you to use StartActivityForResult
var intent = new Intent(this, typeof(EditorAcitivity));
intent.PutExtra("Note", JsonConvert.SerializeObject(note));
intent.PutExtra("Mode", "Edit");
StartActivityForResult(intent,REQUEST_CODE_EDITOR_ACITIVTY);
In that case REQUEST_CODE_EDITOR_ACITIVTY is a integer constant.
And then when your about to finish your activity call to the SetResult method as below
Util.db.Insert(note);
SetResult(Result.Ok);
this.Finish();
And finally override the OnActivityResult method in the same activity you're starting the EditorAcitivity as below
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_EDITOR_ACITIVTY) {
if(resultCode == Result.Ok) {
//Here your activity received the callback and you can call the load notes method
loadNotes();
}
}
}
Take a look at this tutorial if you want to learn more about Activity for result
https://subscription.packtpub.com/book/application_development/9781784398576/8/ch08lvl1sec84/obtaining-data-from-activities

My first project stuck on OnActivityforResult

I tried to make a simple app which can keep scores on a game with four players. When I press the plus or minus button it opens a new activity (dialog theme) where the user should enter their score. That score should be stored into a text view.
Some part of code looks like this:
Here I opened new activities
buttonPlus1.setOnClickListener(this);
buttonPlus2.setOnClickListener(this);
buttonPlus3.setOnClickListener(this);
buttonPlus4.setOnClickListener(this);
buttonMinus1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttPlusPlayer1:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
break;
case R.id.buttPlusPlayer2:
Intent i2 = new Intent(this, ThirdPlusActivity.class);
startActivityForResult(i2, 2);
break;
case R.id.buttPlusPlayer3:
Intent i3 = new Intent(this, FourthPlusActivity.class);
startActivityForResult(i3, 3);
break;
case R.id.buttPlusPlayer4:
Intent i4 = new Intent(this, FifthPlusActivity.class);
startActivityForResult(i4, 4);
break;
case R.id.buttMinusPlayer1:
Intent i5 = new Intent(this, FirstMinusActivity.class);
startActivityForResult(i5, 1);
}
}
That's an example how activities send data back to main activity
public class SecondActivity extends AppCompatActivity {
private EditText mEditText;
private ImageButton mBackSpace;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
setTitle("ADD POINTS");
mEditText = findViewById(R.id.editTxtActivity);
//implementing backspace button
mBackSpace = findViewById(R.id.backSpaceButton);
mBackSpace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = mEditText.getText().toString();
if (str.length() > 0) {
str = str.substring(0, str.length() - 1);
mEditText.setText(str);
}
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent();
i.putExtra("message", mEditText.getText().toString());
setResult(RESULT_OK, i);
Toast.makeText(this, "You added " + mEditText.getText().toString() + " points", Toast.LENGTH_LONG).show();
finish();
}
}
and "now" I receive the results from activities
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
String a = data.getStringExtra("message");
int i =Integer.parseInt(a);
String b = data.getStringExtra ("message5");
int z = Integer.parseInt(b);
Integer fResult = i - z;
String firstResult = fResult.toString();
mFirstScore.setText(firstResult);
}
if (requestCode == 2 && resultCode == RESULT_OK) {
mSecondscore.setText(data.getStringExtra("message2"));
}
if (requestCode == 3 && resultCode == RESULT_OK) {
mThirdScore.setText(data.getStringExtra("message3"));
}
if (requestCode == 4 && resultCode == RESULT_OK) {
mFourthscore.setText(data.getStringExtra("message4"));
}
the problem is on the last part of the code because I don't know how to receive data from activities and to calculate the result. I want when the user hit the plus button to add numbers and when minusButton is clicked to substract and the result to be stored on a TextView which, for player1, in my case is mFirstScore.
Is this possible or I did everything wrong and it is not possible to manipulate data received from another activity how I image
PS: on case buttMinusPlayer1 and on first if with requestCode 1 I've tried something ;
On SecondActivity put your key message2
#Override
public void onBackPressed() {
Intent i = new Intent();
i.putExtra("message2", mEditText.getText().toString());
setResult(RESULT_OK, i);
finish();
}
and get the data from SecondActivity by the same key message2
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2 && resultCode == RESULT_OK) {
mSecondscore.setText(data.getStringExtra("message2"));
}
}
Hope this helps.

How do i set .equals equal to the result of startActivityForResult

im kinda new to programming and would like to make some sort of like a login and register page. so from my login page i click register and it would go to the register page and i want the username/password i get from the register page to be used in the previous login page to login into the app. But i cant seem to set the username/password using the result. Only able to set the textview. pls help heres the code
public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText Password;
private TextView Info;
private Button Login;
private int counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = (EditText)findViewById(R.id.etName);
Password = (EditText)findViewById(R.id.etPass);
Info = (TextView) findViewById(R.id.tvInfo);
Login = (Button)findViewById(R.id.btnLogin);
Info.setText("No Of Attempts Remaining: 5");
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validate(Name.getText().toString(),Password.getText().toString());
}
});
}
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
else{
counter--;
Info.setText("No Of Attempts Remaining: " + String.valueOf(counter));
if(counter == 0){
Login.setEnabled(false);
}
}
}
public void facebooklogin(View myview){
Intent intent = new Intent(this, MenuActivity.class);
startActivity(intent);
}
public void register(View myview) {
Intent i = new Intent(this, RegisterActivity .class);
startActivityForResult(i, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String reginame = data.getStringExtra("NAME");
String regipass = data.getStringExtra("PASS");
Name.setText("" + reginame);
Password.setText("" + regipass);
}
}
}
How do i set the
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
to be equal to the onActivityResult reginame and regipass
your condition is wrong it should be like this:-
private void validate(String userName, String userPassword){
if(!userName.equals("") && !userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
First Activity.
Send information
Intent send = new Intent(MainActivity.this, Main2Activity.class);
send.putExtra("login",editText.getText());
send.putExtra("password",editText1.getText());
startActivity(send);
Second Activity.
Get Information
if(getIntent()!=null){
Intent intent = getIntent();
editText.setText(intent.getStringExtra("login")) ;
editText1.setText(intent.getStringExtra("password")) ;
}

Passing data from second activity to first activity

I am trying to pass Bundle from second activity to the first(launch) activity. In order not to get NPE on launch, I am checking if bundle != null, however, it looks, like even after returning from second activity with Bundle, it still doesn't run the "if" body.
Here is my part of code of first activity
Bundle bundle = getIntent().getExtras();
if (bundle!=null) {
Player player = new Player();
player.setStatus(bundle.getInt("Status"));
player.setName(bundle.getString("Name"));
addPlayerToList(player);
Log.e("Player with a name " + player.getName(), "Has been created");
}
And code of second activity
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(getApplicationContext(),StartActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("Status",status);
bundle.putString("Name", name);
Log.d("Object " + name, "Status: " + status);
startActivity(i);
}
});
Thanks for any help/advice
Use startActivityForResult() for this situation.
1) You open second activity from the first using this method, not startActivity()
2) Do whatever you want in the second activity
3) Set result bundle
4) Finish activity
5) Open bundle in the first activity
In your case it will look like:
1) Call second activity like this:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, REQUEST_SECOND_ACTIVITY); // request code const
2-4)
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
final Intent returnIntent = new Intent();
returnIntent.putExtra("Status", status); // set values
returnIntent.putExtra("Name", name);
setResult(Activity.RESULT_OK, returnIntent); // set result code
finish(); // finish this activity and go back to the previous one
}
});
5) Override this method in the first activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_SECOND_ACTIVITY: // same request code const
if(resultCode == Activity.RESULT_OK){
Player player = new Player();
player.setStatus(data.getIntExtra("Status"));
player.setName(data.getStringExtra("Name"));
addPlayerToList(player);
}
break;
}
}
try Intent.putExtra() instead of putting data into a bundle, and use Intent.getStringExtra() to get a String data;
In your code, there is no code to put your bundle into intent. actually you never pass the bundle to first activity. you can use this answer to solve your problem.
good luck!

Trying to read barcodes with Zxing, but it seems the onActivityResult is not beeing called

as the title says, I'm trying to scan 1D barcodes, so far I have thet following code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void test(View view){
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "1D_CODE_MODE");
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
IntentResult intentResult =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null) {
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
TextView uno = (TextView) findViewById(R.id.textView1);
uno.setText(contents);
Toast.makeText(this, "Numero: " + contents, Toast.LENGTH_LONG).show();
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
}
And of course, I have both IntentResult and IntentIntegrator added to the project.
So, the scanner is beeing called correctly when a button is pressed and it seems to scan the code perfectly (it says "Text found" after it scans it), but it seems that the onActivityResult is not called, since the TextView is not beeing updated and the Toast is not appearing.
Any idea on what the mistake could be?
Thanks in advance!
Your first mistake is not using IntentIntegrator.initiateScan(), replacing it with your own hand-rolled call to startActivityForResult().
Your second mistake is in assuming that IntentIntegrator.REQUEST_CODE is 0. It is not.
Hence, with your current code, you are sending out a request with request code of 0, which is coming back to onActivityResult() with request code of 0, which you are ignoring, because you are only looking for IntentIntegrator.REQUEST_CODE.
Simply replace the body of your test() method with a call to initiateScan(), and you should be in better shape. Here is a sample project that demonstrates the use of IntentIntegrator.
I resolve your same problem so.
public class MainActivity extends Activity {
private TextView tvStatus, tvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.tvStatus = (TextView) findViewById(R.id.tvStatus);
this.tvResult = (TextView) findViewById(R.id.tvResult);
Button scanBtn = (Button) findViewById(R.id.btnScan);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_FORMATS", "QR_CODE_MODE");
startActivityForResult(intent,
IntentIntegrator.REQUEST_CODE);
} catch (Exception e) {
Log.e("BARCODE_ERROR", e.getMessage());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
if (scanResult != null) {
this.tvStatus.setText(scanResult.getContents());
this.tvResult.setText(scanResult.getFormatName());
}
}
}
The onActivityResault function must be overridden. just add an #Override before the function declaration and it will be solved.

Categories

Resources