I cant send Extra for singleTask activity Android - android

I use singleTask activity in my application.
Order activities A->B->C->B
I put extra on A and then get it on B, then I go to C and try putExtra for B, but on B I don't see it.
If I use default android:launchMode, it work ok.

you have to carry extra between intents.
A -step1-> B -step2-> C -step3-> B
step1
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String extraString;
Bundle extras = getIntent().getExtras();
if (extras == null) {
extraString = null;
System.out.println("null extra");
} else {
extraString = extras.getString("extra");
System.out.println("from " + extraString);
}
Intent intent = new Intent(C.this,B.class);
intent.putExtra("extra", extraString);
startActivity(intent);
};
step2
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String extraString,extraString2;
Bundle extras = getIntent().getExtras();
if (extras == null) {
extraString = null;
System.out.println("null extra");
} else {
try
{
extraString = extras.getString("extra");
System.out.println("from " + extraString);
{
catch{}
}
// CATCH EXTRA STRING2
if (extras == null) {
extraString2 = null;
System.out.println("null extra");
} else {
try
{
extraString2 = extras.getString("extra2");
System.out.println("from " + extraString2);
{
catch{}
}
Intent intent = new Intent(C.this,B.class);
intent.putExtra("extra", extraString);
startActivity(intent);
};
step3
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String extraString
Bundle extras = getIntent().getExtras();
if (extras == null) {
extraString = null;
System.out.println("null extra");
} else {
extraString = extras.getString("extra");
System.out.println("from " + extraString);
}
Intent intent = new Intent(C.this,B.class);
intent.putExtra("extra2", extraString);
startActivity(intent);
};

Related

getIntent().getExtra() returns null

I have code that direct users to the profile page from the bottom bar.
private void startNewIntent(Class className, String uid){
Intent intent = new Intent(act, className);
intent.putExtra("uid", uid);
act.startActivity(intent);
act.finish();
}
className = DisplayProfile.class;
if(FirebaseAuth.getInstance().getCurrentUser() != null){
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
startNewIntent(DisplayProfile.class, uid);
} else {
startNewIntent(EmailPasswordActivity.class);
}
in ProfileActivity.java
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String uid = getIntent().getStringExtra("uid");
if(uid != null){
...
}
}
I also tried with Bundle = getIntent().getExtra() with the same results. I have seen similar questions. This seem to be the case: getIntent() Extras always NULL
I tried
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
but getIntent().getExtra != null is still false.
Thank you for your help and advice.
Edit: added context for startNewIntent()
Rather than checking in onCreate() check in onNewIntent():
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String uid = getIntent().getStringExtra("uid");
if(uid != null){
...
}
}
#Override
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
String uid = getIntent().getStringExtra("uid");
if(uid != null){
...
}
}
If it's coming in onNewIntent() this means you are using launchMode for your activity. So this is the behaviour of launch mode.
Avoid ".class" if already present in your class name.
public void startNewIntent(Class className, String uid){
Intent intent = new Intent(act.this, className+".class");
intent.putExtra("uid", uid);
startActivity(intent);
}
Next Phase
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String uid = getIntent().getExtras().getString("uid");
if(uid != null){
...
}
}

How to decide which Activity will start after the next in android

Hi there I want to call an Activity an decide which is the next activity to start after the Dialog finished like:
Intent dialog_intent = new Intent(_parent, MyActivityA.class);
dialog_intent.putExtra(MyActivityA.EXTRA_PARENT, MyActivityB.class);
I am getting the extra like this in the Oncreate of MyActivityA:
Type _parent = null; // this is a class variable
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext())
{
String key = it.next();
if(key.equals(EXTRA_PARENT))
_parent = (Type)bundle.get(EXTRA_PARENT);
}
}
in the finishDialog method I do this :
public void finishDialog(View v)
{
try
{
Intent intent = null;
if(_parent != null && _parent instanceof Activity)
{
intent = new Intent(this, _parent.getClass());
}
else
{
intent = new Intent(this, DefaultActivity.class);
}
if(intent != null)
{
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
finish();
}
2 Questions:
Why does _parent instaneof Activity not work. I think MyActivity is a Type which inherits of Activity
Trying to start the activity does not work. But if i put in
new Intent(this,MyActivityB.class);
it works! What am I doing wrong. Is there any other way to do this
You can simply pass integer value and map it to corresponding activity.
Intent dialog_intent = new Intent(_parent, MyActivityA.class);
dialog_intent.putExtra("EXTRA_PARENT", 1);
Now in your activity get this EXTRA_PARENT and call activity
Bundle extras = getIntent().getExtras();
int extraParent = extras.getInt("EXTRA_PARENT");
if(extraParent == 1)
{
Intent dialog_intent = new Intent(_parent, MyActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}

Android OnActivityResult passing data to another form and getting array result from it

I want to send some Data to another activity say SecondActivity and then getting Array data from That SecondActivity to Main activity using OnActivityResult
This is a app like when i press upload button i already have path i want to send that path to another activity and then getting the result in array from another activity to same mainactivity and then want to view that array in textview
CSVUpload
public class CSVUploader extends Activity {
Button btnUpload;
EditText txtName;
EditText txtMessageName;
Bundle extras = getIntent().getExtras();
String FullPath = extras.getString("FullPath");
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
File csvfile = new File(FullPath);
FileInputStream csvStream = new FileInputStream(csvfile);
BufferedReader in = new BufferedReader(new InputStreamReader(csvStream));
String line;
String[] name = null;
String[] number = null;
int iCount=0;
while ((line = in.readLine()) != null){
String[] RowData = line.split(",");
name[iCount] = RowData[0];
number[iCount] = RowData[1];
iCount++;
/* ContentValues values = new ContentValues();
values.put(key, value);
values.put(CsvProvider.NUMBER, number);
values.put("status",status);
getContentResolver().insert(CsvProvider.CONTENT_URI, values);
*/ }
in.close();
Bundle b =new Bundle();
Intent intent = new Intent();
b.putStringArray("name", name);
b.putStringArray("number", number);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
FirstActivity
public void uploadfile(View view){
edittext = (EditText)findViewById(R.id.txtFile);
Toast.makeText(NewMessage.this, FullPath, 2000).show();
if(FullPath != null)
{
Intent intent1 = new Intent(this, CSVUploader.class);
intent1.putExtra("FullPath", FullPath);
startActivityForResult(intent1, 2);
}
else
{
Toast.makeText(NewMessage.this, "No File Selected", 2000).show();
}
}
// Listen for results.
public void onActivityResult(int requestCode, int resultCode, Intent data){
// See which child activity is calling us back.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PATH){
if (resultCode == RESULT_OK) {
curPathName = data.getStringExtra("GetPath");
curFileName = data.getStringExtra("GetFileName");
FullPath = curPathName+"/"+curFileName;
edittext.setText(curFileName);
/* Toast.makeText(NewMessage.this, resId, duration);*/
}
}
if (requestCode==2){
if (resultCode == RESULT_OK) {
Bundle b=this.getIntent().getExtras();
String[] name=b.getStringArray("name");
String[] number=b.getStringArray("number");
String[] status;
}
}
try to use this code. I am not sure this will work properly
MainActivity.java
public void uploadfile(View view){
Intent intent1 = new Intent(this, CSVUploader.class);
intent1.putExtra("FullPath", FullPath);
startActivity(intent1);
}
Replace your code likewise
CSVUploader.java
Bundle b=new Bundle();
Intent i = new Intent(this,MainActivity.class);
b.putStringArray("name",name);
b.putStringArray("number",number)
i.putExtras(b);
startActivity(i);
You can retrive it in MainActivity.java as
Bundle b=this.getIntent().getExtras();
String[] name=b.getStringArray("name");
String[] number=b.getStringArray("number");
You need to put the retrieving code into onCreate instead of where you have it now.
#Override
protected void onCreate(Bundle savedInstanceState) {
String FullPath = getIntent().getStringExtra("FullPath");
By the way why you want to use another activity to do the task. Why dont you do it in the same activity.

Reload same activity but pass bundle

I am trying to reload my activity and pass a bundle, but I'm getting an empty (null) bundle.
Reload activity:
Intent intent = new Intent(MyActivity.this, MyActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", 1);
intent.putExtras(bundle);
MyActivity.this.finish();
startActivity(intent);
onCreate activity and I should get the bundle:
#Override
public void onCreate(Bundle savedInstance)
{
if (savedInstance != null)
{
}
else
{
Log.i("d", "IS NULL !");
}
}
I'm getting null.
In OnCreate() you should do like this :
if(getIntent().getExtras() != null) {
Bundle extras = getIntent().getExtras();
Log.i("Value", extras.getString("key"));
}
Instead of this
if (savedInstance != null){
}
First start the activity and then call finish() as follows:
Intent intent = new Intent(MyActivity.this, MyActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", 1);
intent.putExtras(bundle);
startActivity(intent);
MyActivity.this.finish();
Then receive the bundle extras like this:
Bundle bundle = getIntent().getExtras();
Finally, you can put conditions to check if it's correct like:
if(bundle != null)
{
}
else
{
Log.i("d", "IS NULL !");
}

android: onSaveInstanceState ()

I try to pass a string from one activity to another activity.
This is the coding in Activity A:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("UserName", UserName);
Log.i(Tag, "UserName1: "+ UserName);
super.onSaveInstanceState(savedInstanceState);
}
In Activity B I use this code to get the string:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.i(Tag, "UserName2: "+ UserName);
}
But the logcat shown the first log "UserName1" when I clikc the open to Activity B,
and show the second log "UserName2" as "null".
May I know what wrong with my code?
What I want to do is Activity A pass the String in Activity B when I click the "button" and intent to Activity B. So I can get the String value in Activity B.
Any Idea? Cause I getting error when using intent.putStringExtra() and getintent.getStringExtra(), so I change to use onSaveInstanceState (), but still having problem.
EDIT:
This is my original code, I can get the String in Activity B, but unexpected I can't save my data in Sqlite. If remove the putString Extra then everything go smoothly.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addItem = new Intent(ItemActivity.this, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
addItem.putStringExtra("UserName", UserName);
Log.e(Tag, "UseName: "+ UserName);
startActivity(addItem);
return super.onOptionsItemSelected(item);
}
Code in Activity B:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
UserName = (String) getIntent().getStringExtra("UserName");
Log.e(Tag, "UserName3: "+ UserName);
}
Full code for Activity B:
public class AddEditItem extends Activity implements OnItemSelectedListener {
private static final String Tag = null;
private EditText inputItemName;
private EditText inputItemCondition;
private EditText inputEmail;
private Button btnGal, btnConfirm;
private Bitmap bmp;
private ImageView ivGalImg;
private Spinner spinner;
String[] category = {"Books", "Clothes & Shoes", "Computer", "Electronics", "Entertainment", "Food & Drinks",
"Furnitures", "Mobile Phone", "Other", "UKM"};
String selection;
String filePath, itemName, itemCondition;
String UserName, user;
private int id;
private byte[] blob=null;
byte[] byteImage2 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.e(Tag, "UserName2: "+ UserName);
//UserName = (String) getIntent().getStringExtra("UserName");
//Log.e(Tag, "UserName3: "+ UserName);
}
private void setUpViews() {
inputItemName = (EditText)findViewById(R.id.etItemName);
inputItemCondition = (EditText)findViewById(R.id.etItemCondition);
inputEmail = (EditText)findViewById(R.id.etEmail);
ivGalImg = (ImageView) findViewById(R.id.ivImage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddEditItem.this, android.R.layout.simple_spinner_dropdown_item, category);
spinner = (Spinner)findViewById(R.id.spnCategory);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
user=extras.getString("user");
inputItemName.setText(extras.getString("name"));
inputItemCondition.setText(extras.getString("condition"));
inputEmail.setText(extras.getString("email"));
selection = extras.getString("category");
byteImage2 = extras.getByteArray("blob");
if (byteImage2 != null) {
if (byteImage2.length > 3) {
ivGalImg.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2,0,byteImage2.length));
}
}
}
btnGal = (Button) findViewById(R.id.bGallary);
btnGal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
btnConfirm = (Button) findViewById(R.id.bConfirm);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputItemName.getText().length() != 0 && inputItemCondition.getText().length() != 0
&& inputEmail.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveItemTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveItem();
return null;
}
#Override
protected void onPostExecute(Object result) {
Toast.makeText(getApplicationContext(),
"Item saved", Toast.LENGTH_LONG)
.show();
finish();
}
};
saveItemTask.execute((Object[]) null);
Toast.makeText(getApplicationContext(),
"Item saved reconfirm", Toast.LENGTH_LONG)
.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditItem.this);
alert.setTitle("Error In Save Item");
alert.setMessage("You need to fill in all the item details");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveItem() {
if(bmp!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=byteImage2;}
ItemSQLiteConnector sqlCon = new ItemSQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertItem(UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
else {
sqlCon.updateItem(id, UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
bmp = BitmapFactory.decodeFile(filePath);
ivGalImg.setImageBitmap(bmp);
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view;
selection = tv.getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
onSaveInstanceState is not used in that purpose, its used to save your activity state on for example orientation change, or when you leave an activity and get back to it.
What you need is to use intents.
Other than starting activity, intents can also carry some information throughout app, like this:
This would be activity 1:
Intent = new Intent (getApplicationContext(), Activity2.class);
intent.putExtra("UserName", UserName);
startActivity(intent);
and to recover it in second activity use:
String username = getIntent().getExtras().getString("UserName");
May I know what wrong with my code?
onSaveInstanceState() has nothing to do with passing data between activities. Instead, you need to put your string in an extra on the Intent used with startActivity().
Cause I getting error when using intent.putExtra() and getintent.getExtra()
Since that is the correct approach (albeit using getStringExtra()), please go back to it and fix whatever error you are encountering.

Categories

Resources