Put And Get Extras From Another Class - android

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!

Related

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)

Multiple Instances and Multiple Activities calling the same Activity

I have three Activities. MainActivity,ActivityB and ActivityC. In activity A and B there are two buttons source and destination in both activities. in Activity C there is a list of data. when button is clicked (either Source or destination) from activity A and B. both Activities are calling Activity C
code for Activity A is following
public class MainActivity extends Activity {
TextView source,destination;
Button sendSource,sendDestination,btnTob;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
source=(TextView)findViewById(R.id.tv_rcvDataA);
destination=(TextView)findViewById(R.id.tv_rcvDataAa);
sendSource=(Button)findViewById(R.id.btn_sendA);
sendDestination=(Button)findViewById(R.id.btn_sendAa);
btnTob=(Button)findViewById(R.id.btn_toB);
sendSource.setText("source");
sendDestination.setText("destination");
src=sendSource.getText().toString();
des=sendDestination.getText().toString();
activity=getClass().getSimpleName();
sendSource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(MainActivity.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});
sendDestination.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(MainActivity.this,ActivityC.class);
senda.putExtra("destination",des);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
btnTob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent movetoB= new Intent(MainActivity.this,ActivityB.class);
startActivity(movetoB);
finish();
}
}); }}
and code for Activity B is
public class ActivityB extends Activity {
TextView sourceB,destinationB;
Button sendSourceB,sendDestinationB;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
sourceB=(TextView)findViewById(R.id.tv_rcvDataB);
destinationB=(TextView)findViewById(R.id.tv_rcvDataBa);
sendSourceB=(Button)findViewById(R.id.btn_sendB);
sendDestinationB=(Button)findViewById(R.id.btn_sendDataBa);
activity=getClass().getSimpleName();
sendDestinationB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra("destination",src);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
sendSourceB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(ActivityB.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});}}
now how to check in activityC which activity is calling this activity and which buttonclicklistener is calling the intent
You need to send the value for determine what value and what activity via Intent.putExtra(). Please be remember that you need to set the key as the first parameter for Intent.putExtra(), like
intent.putExtra(THIS_IS_THE_KEY, THIS_IS_YOUR_VALUE);
You need to create something like this:
// This is the key for your putExtra
// you need to create this as global variable.
public static final String FROM_KEY = "FROM";
public static final String ACTIVITY_KEY = "ACTIVITY";
public static final boolean IS_FROM_SOURCE = true;
// This is a sample to send data to Activity C
// where the activity caller is B and from source
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra(FROM_KEY, IS_FROM_SOURCE);
senda.putExtra(ACTIVITY_KEY,"activity_a");
Then in your Activity C, you need to receive the Intent Extra.
You can get the value in Activity onCreate(), something like this:
Bundle extras = getIntent().getExtras();
boolean from = extras.getBoolean(FROM_KEY);
String act = extras.getString(ACTIVITY_KEY);
// do something here if from activity a
if(act.equals("activity_a")) {
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
} else { // if from activity a
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
}
In onCreate or anytime after that method is called in Activity-C, you should do the following:
Intent intent = getIntent();
if (intent != null) {
String activity = intent.getStringExtra("Activity");
String src = intent.getStringExtra("source");
// Do something with those values
}

how to retrieve Data from Intent ?? [duplicate]

This question already has answers here:
How do I get extra data from intent on Android?
(16 answers)
Closed 8 years ago.
I just want to show an simple Employee record on next layoutPage/Activity !!
this is my EmpLogin Java File
public class EmpLogin extends Activity {
private Button show;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// TODO Auto-generated method stub
show=(Button)findViewById(R.id.show);
show.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText no=(EditText)findViewById(R.id.getno);
EditText name=(EditText)findViewById(R.id.getname);
EditText sal=(EditText)findViewById(R.id.getsalary);
Intent emp = new Intent(getApplicationContext(),EmpShow.class);
emp.putExtra("EmpNO",(no.getText().toString()));
emp.putExtra("EmpName",(name.getText().toString()));
emp.putExtra("Sal",(sal.getText().toString()));
startActivity(emp);
}
});
}
}
How to use Retrieve data from the Intent ??? By using getExtra() method ??? or there is simple way ?? this my EmpShow.class file !!
public class EmpShow extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.empshow);
// TODO Auto-generated method stub
Intent show = getIntent();
}
}
As you passed data insideintent, So try to fetch the intent which has started your activity using the getIntent() method:
Intent intent = getIntent();
If your extra data is represented as strings, then you can use
intent.getStringExtra(String name) method.
As per your OP's class and intent. Here is the snipped which can fetch the values from your intent against respective variable,
public class EmpShow extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.empshow);
Intent intent = getIntent();
String empNo = intent.getStringExtra("EmpNO");
String empNname = intent.getStringExtra("EmpName");
String empSal = intent.getStringExtra("sal");
}
}
First Activity:
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("VAL",value1);
startActivity(i);
Second Activity:
Intent getI=getIntent();
String a =getI.getStringExtra("VAL");

how can i pass my password value into other class of my package

Here i want to send the value of "ourpassword" to say in myclass.java so how can i do this??
public class SetPassword extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.set_password);
final EditText ed=(EditText)findViewById(R.id.setpass);
Button submit=(Button)findViewById(R.id.button1);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String ourpassword=ed.getText().toString();
}
});
}
To pass data between activities use intents.
Intent i= new Intent("com.example.myclass");
i.puExtra("mypassword",ourpassword);
startActivtiy(i);
In myclass
Bundle extras = getIntent().getExtras();
if (extras != null) {
String password = extras.getString("mypassword");
}
You can also pass value to another class by passing value to the constructor of the class
myClass mc= new myClass(ourPassword);
mc.doSomething(); //call some method in another class
In your myclass
class myClass{
String pwd;
public myclass(String password)
{
pwd =password;
}
publidc void doSomething()
{
}
}
Say you want pass value to a class like asynctask
//pass value as a parameter to the class constructor
MyAsyncTask my= new MyAycTask(ourpassword).execute();
In My AsyncTask
class MyAsyncTask extends AsyncTask<Void,Void,Void>
{
public M(String password)//receive value here
{
}
other methods....
}
Create object of this class and get the value as
Define string as static
Object.String;
You can also use Use database. thats better way to store and retrieve passwords
If myclass.java is another Activity class, you can just set the password as a parameter in the intent. For example:
Intent intent = new Intent(getApplicationContext(),myclass.class);
intent.putExtra("password", ourpassword);
startActivity(intent);
... and then you can get the value from within the myclass.java in the onCreate() method like this:
String password = "";
if (getIntent().getStringExtra("password") != null) password = getIntent().getStringExtra("password");
EDIT: You place the Intent code in the onClick() method of the submit button.

How to get data from other activity in android?

I have two activities such as Activity A and B and I'm trying to pass two different strings from A to B using Bundle and startActivity(intent).
Like that:
Intent intent = new Intent(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("vidoedetails", filedetails);
//bundle.putString("videoname", filename);
intent.putExtras(bundle);
//intent.putExtra("videofilename", filename);
//intent.putExtra("vidoefiledetails", filedetails);
startActivity(intent);
And in class B I'm using two TextViews to display the strings from class A seperately.
Like that:
Intent i = getIntent();
Bundle extras = i.getExtras();
filedetails = extras.getString("videodetails");
filename = extras.getString("videoname");
The problem is filedetils get printed in class B but not the file name.
Any solution for this?
you have a typo:
bundle.putString("vidoedetails", filedetails);
should be
bundle.putString("videodetails", filedetails);
I know I am 9 days late on this answer, but this is a good example of why I create a constants class. With a constants class, it doesnt matter if it is misspelled ("video" -> "vidoe") because it will be 'misspelled' in both places as you are referencing it through a well known location.
Constants.java
public static String WELL_KNOWN_STRING "org.example.stackoverflow.4792829";
Activity1.java
bundle.putString(Constants.WELL_KNOWN_STRING, filedetails);
Activity2.java
filedetails = extras.getString(Constants.WELL_KNOWN_STRING);
Yes, you spelled wrongly videodetails:
Yours: vid*OE*details
Correct: vid*EO*details
// First activity
actvty_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(v.getContext(),SECONDACTIVITY.class);
startActivityForResult(i, STATIC_INTEGER_VALUE);
}
});
/* This function gets the value from the other activity where we have passed a value on calling this activity */
public void activity_value() {
Intent i = getIntent();
Bundle extras=i.getExtras();
if(extras !=null) {
// This is necessary for the retrv_value
rtrv_value = extras.getString("key");
if(!(rtrv_value.isEmpty())) {
// It displays if the retrieved value is not equal to zero
myselection.setText("Your partner says = " + rtrv_value);
}
}
}
// Second activity
myBtn.setOnClickListener(new View.OnClickListener () {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), FIRSTACTIVITY.class);
Bundle bundle = new Bundle();
bundle.putString("key", txt1.getText().toString());
// Here key is just the "Reference Name" and txt1 is the EditText value
intent.putExtras(bundle);
startActivity(intent);
}
});
Here's another way to pass data between Activities. This is just an example from a tutorial I was following. I have a splash screen that runs for 5 seconds and then it would kill the sound clip from:
#Override
protected void onPause() {
super.onPause();
ourSong.release();
}
I decided I wanted the sound clip to continue playing into the next activity while still being able to kill/release it from there, so I made the sound clip, MediaPlayer object, public and static, similar to how out in System.out is a public static object. Being new to Android dev but not new to Java dev, I did it this way.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
public static MediaPlayer ourSong; // <----- Created the object to be shared
// this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.dubstep);
ourSong.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent(
"expectusafterlun.ch.androidtutorial.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
}
Then from the next activity, or any other activity, I could access that MediaPlayer object.
public class Menu extends ListActivity {
String activities[] = { "Count", "TextPlay", "Email", "Camera", "example4",
"example5", "example6" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this,
android.R.layout.simple_expandable_list_item_1, activities));
}
#Override
protected void onPause() {
super.onPause();
Splash.ourSong.release(); // <----- Accessing data from another Activity
// here
}
}

Categories

Resources