I am a beginner of Android. I want to pass the result from FirstActivity to the SecondActivity as below. How to remove results in intent extra? Or any way to pass the result to SecondActivity and show on the TextView?
(I have make a mistake and replace, my main question is how to delete the result, because i want to set another new result in it.)
FirstActivity.java
public class FirstActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//code...
try {
myDbHelper.createDatabase();
}
catch (IOException ioe) {
Log.d("Error","Error while createing Database");
ioe.printStackTrace();
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
Log.d("Error","Error while Opening Database");
sqle.printStackTrace();
throw sqle;
}
send.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
//...code
//checking for slection
results = queryData(table, type);
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
}
public String queryData(String table, String type){
//...
//do somthing to get result
return result;
}
}
SecondActivity.java
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_item);
TextView tv;
tv = (TextView)findViewById(R.id.tv);
Bundle extras=getIntent().getExtras();
String value1=extras.getString("results");
tv.setText("Result\n" + value1);
}
}
You can do in 2 ways:
1. You can use startActivityForResult(), onActivityResult() from the Activity A, to pass the data on to Activity B, then after some computation, passing the result back to Activity A.
2. Now if you want to just send some data from Activity A to Activity B, and then display it in TextView, then use putExtra() and getExtras()...
Sending from Activity A to B:
Intent i = new Intent(Activity_A.this, Activity_B.class);
i.putExtra("name",Name);
startActivity(i);
Receiving the value on Activity B:
Intent i = getIntent();
String n = i.getExtras().getString("name");
change startActivityForResult(intent, 0) to startActivity(intent);
like this
private void showResult() {
results = queryData(table, type);
Intent intent = new Intent(firstActivity.this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
}
Make new intent and pass
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
You were done your way of method that pass the data to next Activity is right. But, you made a mistake with starting the activity. Starting an Activity in your code should be like below -
private void showResult() {
//...code
//checking for slection
results = queryData(table, type);
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent); // This is the way to start a new Activity which is in seperate class
}
And, just have a look at below -
How do I pass data between Activities in Android application?
Passing data between activities in Android
Related
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!
I'm trying to pass a serialized array of objects from one activity to another. However, I'm unable to reach OnCreate in the second activity if I attach the extra to the intent. Can anyone see what I'm doing wrong?
From the first activity:
public void onDisplayImages(View view){
Intent intent = new Intent(MainActivity.this, ImagesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(IMAGE_LIST,mImagesList);
intent.putExtras(bundle);
MainActivity.this.startActivity(intent);
}
This way doesn't work either:
public void onDisplayImages(View view){
Intent intent = new Intent(MainActivity.this, ImagesActivity.class);
intent.putExtra(IMAGE_LIST,mImagesList);
MainActivity.this.startActivity(intent);
}
mImageList is an ArrayList of ImageData objects where ImageData extends Serializable. When I don't attempt to attach the extra, I make it to the second activity.
ImageData:
public class ImageData implements Serializable {
public Bitmap mImage;
public String mName;
public ImageData(String fileName, Context context){
mName = fileName;
File filePath = context.getFileStreamPath(fileName);
try {
FileInputStream fi = new FileInputStream(filePath);
mImage = BitmapFactory.decodeStream(fi);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I am getting this error
Error:
05-28 16:50:40.540 2731-2731/[myPackageName]/AndroidRuntime﹕ FATAL EXCEPTION: main Process: [myPackageName], PID: 2731 java.lang.IllegalStateException: Could not execute method of the activity –
Im trying to pass data from my TestSearch class to GoogleSearch class. I assigned the values of the tEdit test to a string variable and I want to pass that to GoogleSearch class. But my app get crash when I run it.
Button disp=(Button)findViewById(R.id.btn_Search);
disp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText inputTxt = (EditText) findViewById(R.id.editText1);
String str = inputTxt.getText().toString().toLowerCase().trim();
ArrayList<HashMap<String, String>> userList = controller.searchBook(str);
if (userList.size() != 0) {
//Do something
}
else
{
Intent intent = new Intent("com.example.captchalib.GoogleSearch");
intent.putExtra("message", str);
startActivity(intent);
}
}
});
In my GoogleSearch Class I used Below Code to catch the Intent
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_menu);
Intent intent = getIntent();
String message = intent.getStringExtra("message");
((TextView)findViewById(R.id.Receive)).setText(message);
}
why this is happening and how to solve it ?
Logcat
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.captchalib.GoogleSearch (has extras) }
android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
Change this line:
Intent intent = new Intent("com.example.captchalib.GoogleSearch");
To:
Intent intent = new Intent(TestSearch.this, GoogleSearch.class);
There are many many questions about starting new Intent from another Intent but i'm unable to find solutions of mine. In my main Activity i started an Activity this way
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
and trying to get extra String value this way
public class DownloadManagerSettings extends Activity {
private Button dmOk;
private Bundle extra;
private String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dm_settings);
extra = getIntent().getExtras();
dmOk = (Button) findViewById(R.id.dm_settings_ok);
final Bundle strExtra = extra;
dmOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
try {
Intent intent = new Intent(DownloadManagerSettings.this, Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
But in my LogCat shows following error
08-28 14:19:33.777: E/AndroidRuntime(17837): java.lang.NullPointerException08-28 14:19:33.777: E/AndroidRuntime(17837): at com.downloadmanager.settings.DownloadManagerSettings$1.onClick(DownloadManagerSettings.java:101)
Here 101 Line is
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
UPDATE
new error
08-28 14:55:11.237: E/AndroidRuntime(24623): Caused by: java.lang.NullPointerException 08-28 14:55:11.237: E/AndroidRuntime(24623): at com.downloadmanager.settings.DownloadManagerSettings.onCreate(DownloadManagerSettings.java:66)
66 Line is
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
NEW UPDATE1
Now
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
Another Activity
className = getIntent().getStringExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY");
final String newClass = className;
Log.d("DM_AAAAAAAA", className);
dmOk.setOnClickListener(new View.OnClickListener() {
Find in LogCat
08-28 15:09:14.670: E/AndroidRuntime(27291): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.addon.downloadmanager/com.downloadmanager.settings.DownloadManagerSettings}: java.lang.NullPointerException: println needs a message
Thanks in advance
try this:
public class DownloadManagerSettings extends Activity {
private Button dmOk;
private Bundle extra;
private String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dm_settings);
extra = getIntent().getExtras();
dmOk = (Button) findViewById(R.id.dm_settings_ok);
final Bundle strExtra = extra;
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
dmOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method
try {
Intent intent = new Intent(DownloadManagerSettings.this, Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
Get the String data in onCreate first and then use it in onClick.
Update :
seems you'll have to add your package name as the prefix, see this. After that, use getStringExtra/getCharSequenceExtra to get the string data.(note we don't use Bundle any more). This should work.
update 1:
The following code work on my device.
Intent newIntent = new Intent(getApplicationContext().getPackageName());
newIntent.setClass(this, SecondActivity.class);
newIntent.putExtra(getApplicationContext().getPackageName()+".abc", "test");
startActivity(newIntent);
and in the other activity:
String data = getIntent().getStringExtra(getIntent().getAction()+".abc");
From the javadoc of Intent.putExtra(String,String) :
The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
So try this :
intent.putExtra(getPackageManager().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
and later:
className = strExtra.getString(getPackageManager().getPackageName()+".DM_SETTINGS_ACTIVITY");
Use getStringExtra() instead of getExtra()
or you can also do in from other side during intenet creation
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
Bundle extras = new Bundle();
extras.putString("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
Try this way,hope this will help you to solve your problem.
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
className = className = getIntent().getStringExtra("DM_SETTINGS_ACTIVITY");
OR
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
Bundle bundle = new Bundle();
bundle.putString("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
className = className = getIntent().getBundleExtra().getString("DM_SETTINGS_ACTIVITY");
The problem in your code is here,
intent.putExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
Just replace this line with
intent.putExtra("MainActivity",getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY");
Check this code :
1. **MainActivity.java**
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("MY TEXT", getApplicationContext().getPackageName()+".TestActivity");
startActivity(intent);
2. **MainActivity2.java**
Intent i = getIntent();
final String className = i.getStringExtra("MY TEXT");
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity2.this,Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
This is worked on my device.
I have activity A where it has a ADD button when I click on the button it displays the list of users with check boxes in Second Activity and when I select the users and click the conform button it should display in all the users Activity A.I am using adapter to display the users.
from this button I am getting the list of checked values
private void checkButtonClick()
{
conform = (Button)findViewById(R.id.Confirm);
conform.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Namelist> stateList = contactadapteruser.listexample;
Bundle b=null;
Namelist state;
for(int i=0;i<stateList.size();i++)
{
state = stateList.get(i);
b = new Bundle();
b.putString("selected",state.getName());
if(state.isSelected())
{
responseText.append("\n" + state.getName());
}
}
Intent i= new Intent(Contactselectuser.this,Contactrepresentativedetails.class);
i.putExtras(b);
startActivity(i);
}
});
}
from this button I am getting the I am retrieving the values
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i2 = getIntent();
Bundle b1 = i2.getExtras();
String name1 = b1.getString("selected");
tweet.setText(name1+",\t");
}
});
My problem I am unable to get the users which are checked.
Can any one help me .
use start activity for result to start your second activity.
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, 1);
from second activity before closing you can send
Intent return_intent = new Intent();
return_intent.putExtra("your_user_list",user_list);
setResult(RESULT_CODE,return_intent);
finish();
Now in your FirstActivity override onActivityResult() method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_CODE){
// GET YOUR USER LIST HERE AND USE IT FOR YOUR PURPOSE.
user_list=data.getExtra("your_user_list");
}
}
}
You can use broadcast sender and receiver also for your case. But above method is good for your task.
ArrayList<Namelist> stateList = contactadapteruser.listexample;
// convert your ArrayList to a String[]
String[] arr = new String[stateList.size()];
for (int i = 0; i < arr.length; i++)
{
arr[i] = stateList.get(i).getName();
}
Then using this question as a source, put the String array in your intent:
Bundle b = new Bundle();
b.putStringArray("selected", arr);
Intent i = new Intent(Contactselectuser.this,Contactrepresentativedetails.class);
i.putExtras(b);
startActivity(i);
Then to read the String array from your other activity:
Bundle b = getIntent().getExtras();
String[] array = b.getStringArray("selected");