I was trying to pass a String from an AsyncTask to a new Activity in AsyncTask.onPostExecute:
protected void onPostExecute(String response) {
Intent displayResponse = new Intent(context, DisplayResponse.class);
displayResponse.putExtra("package_name.DisplayResponse.response", response);
displayResponse.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(displayResponse);
}
where context = (Context) this in the MainActivity which starts the AsyncTask and passes context in the constructor.
In DisplayResponse getIntent().getStringExtra("package_name.DisplayResponse.response") is always null
If I use a simple Parcelable with just one String and pass that from
protected void onPostExecute(String response) {
Intent displayResponse = new Intent(context, DisplayResponse.class);
StringParcel sp = new StringParcel(response);
displayResponse.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putParcelable("response", sp);
displayResponse.putExtra("package_name.DisplayResponse.response", bundle);
context.startActivity(displayResponse);
}
I can then use the String in DisplayResponse:
Intent intent = getIntent();
Bundle extras = intent.getBundleExtra("package_name.DisplayResponse.response");
StringParcel sp = extras.getParcelable("response");
textView.setText(sp.parcelString);
So the question is why does the first method using putExtra, getStringExtra fail, whereas the second method using a Parcelable work?
Related
I'm trying to receive JSON from sever and continue to another class, but can't, not working, this how to look my code
class when I click button:
public void onHistoryCheckIn(View view) {
String nCar = numberCar; // to send number car for receive all data json
String type = "historyChckIn";
PreHistoryCheckIn preHistoryCheckIn = new PreHistoryCheckIn(this);
preHistoryCheckIn.execute(type,nCar); // send the data to recieve json
}
Know I go to doInBackground, and I use the onPostExecute
protected void onPostExecute(String s) {
// jsonResult ==> I NEED THE DATA!!!
Intent intent = new Intent(context, HistoryCheckIn.class); // have Damage
context.startActivity(intent);
// alertDialog.setMessage(jsonResult);
// alertDialog.show();
}
I come to class HistoryCheckIn but without JSON, what I can do?
I want to bring jsonResult and I want to come to HistoryCheckIn.class
You have to set the result as an extra to the Intent e.g.
protected void onPostExecute(String s) {
Intent intent = new Intent(context, HistoryCheckIn.class);
intent.putExtra("result", s);
context.startActivity(intent);
}
and retrieve it by calling in HistoryCheckIn
String jsonResult = getIntent().getStringExtra("result");
the fastest way is to add json to your inent
protected void onPostExecute(String s) {
Intent i =new Intent(context, NextActivity.class);
i.putExtra("json", s)
context.startActivity(intent);
}
on other end call
String s= getIntent().getStringExtra("json");
but it is not the best way
The problem i've stuck is
I have 4 activities namely A, B ,C and D . the flow is first A then B then C and so on.
I want to pass data of A to B and then data A+B to C , then data of A+B+C to D and so on..
I've used in Activity A Intent of Hashmap
HashMap<String, String> hashMap = new HashMap<>(); //declared Globally
hashMap.put("key", value);
i.putExtra("map", hashMap); (i is the Intent Object)
startActivity(i); //Starting the Intent
And on receiving side i.e Activity B
HashMap<String, String> hashMap = (HashMap<String, String>)i.getSerializableExtra("map");
Here i'm able to get Successfully the data , but when i try to pass on foward this data to next activity i get null values causing NullPointerException.
In the B activity
Hashmap<String,String> hashMap2 = new HashMap<>;
hashMap2.put("key",hashMap.get("key"));
Log.i("Value:",hashMap.get("key"));
Here i get the values successfully put when same way i pass hashmap2 to C activity i get NullPointerException.
Not understanding what's wrong in here.
I want to pass the values and not store them so i'm preferring Intents over Shared Preferences.
Thanks for your help .I've found out why it was giving me null values
1)In B activity I was doing the wrong way to get the values i.e first getIntent and then sum of A+B values i.e putExtra should be used only when I declare the new intent for the C class. As i was first doing putExtra and then new Intent to C , so in C i used to get Null Values.
This might help you.You can simply send values like this and it will work.
In Activity A:
Intent intent=new Intent(ActivityA.this,ActivityB.class);
intent.putExtra("key1","value1");
startActivity(intent);
In Activity B:
String value1=getIntent.getStringExtra("key1");
Intent intent=new Intent(ActivityB.this,ActivityC.class);
intent.putExtra("key1",value1);
intent.putExtra("key2","value2");
startActivity(intent);
In Activity C:
String value1=getIntent.getStringExtra("key1");
String value2=getIntent.getStringExtra("key2");
Intent intent=new Intent(ActivityC.this,ActivityD.class);
intent.putExtra("key1",value1);
intent.putExtra("key2",value2);
intent.putExtra("key3","value3");
startActivity(intent);
In Activity D,
String value1=getIntent.getStringExtra("key1");
String value2=getIntent.getStringExtra("key2");
String value3=getIntent.getStringExtra("key3");
It is really hectic to send value from one activity to another using Intent same code written in every activity but alternative way is to use cache
public class CacheManager {
public static Map<String, Object> cachedData = new HashMap<>();
public static void clearCache() {
cachedData.clear();
}
public static void putIntoCache(String key, Object value) {
CacheManager.cachedData.put(key, value);
}
public static Object getFromCache(String key) {
if (cachedData.containsKey(key)) {
return CacheManager.cachedData.get(key);
} else {
return null;
}
}
}
One of the advantage of this approch is you can modify data where ever you want and put modified data in cache again
step 1- Create class called cacheManager
Step 2- from anywhere you can put value into Cache HashMap
step 3- from anywhere you can get Value From Cache
Enjoy !
use intent.putExtra in intent like this.
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = null;
i.putExtra("STRING_I_NEED", strName);
startActivity(i);/
and retrieve .
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
First Option
Store data in application context
Declare a class that should extend Application
public class HashTableBundle extends Application {
private Hashtable<String,String> mHashTable = null;
public Hashtable<String, String> getmHashTable() {
return mHashTable;
}
public void setmHashTable(Hashtable<String, String> mHashTable) {
this.mHashTable = mHashTable;
}
}
You can set data into application context by
HashTableBundle mStat = (HashTableBundle) getApplicationContext();
mStat.setmHashTable(mMainHashTable);
You can get it from any activity by using
HashTableBundle mStat = (HashTableBundle) getApplicationContext();
Hashtable<String,String> mHashTable = mStat. getmHashTable();
You need to add HashTableBundle in AndroidManifest otherwise application Throws class cast exception
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:name=".HashTableBundle"> . . . </application>
Second option
MainActivity.java
public class MainActivity extends AppCompatActivity {
Hashtable<String,String> mMainHashTable = new Hashtable<>();
MHashBundle mm = new MHashBundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainHashTable.put("hai","I am From MainActivity");
mm.setmHashTable(mMainHashTable);
Intent mIntent = new Intent(MainActivity.this,ClassB.class);
mIntent.putExtra("myhashtable", mm);
System.out.println("data Main Activity :"+mMainHashTable.get("hai"));
startActivity(mIntent);
this.finish();
}
}
Hashtable container MHashBundle.java
public class MHashBundle implements Serializable {
private Hashtable<String,String> mHashTable = null;
public Hashtable<String, String> getmHashTable() {
return mHashTable;
}
public void setmHashTable(Hashtable<String, String> mHashTable) {
this.mHashTable = mHashTable;
}
}
note MHashBundle.java must implement Serializable
Second Activity ClassB.java
public class ClassB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent mIntent = new Intent(ClassB.this,ClassC.class);
MHashBundle mBundle = (MHashBundle) getIntent().getSerializableExtra("myhashtable");
mIntent.putExtra("myhashtable",mBundle);
System.out.println("data class B :"+mBundle.getmHashTable().get("hai"));
startActivity(mIntent);
this.finish();
}
Thrird Activity
public class ClassC extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MHashBundle mBundle = (MHashBundle) getIntent().getSerializableExtra("myhashtable");
System.out.println("data class C :"+mBundle.getmHashTable().get("hai"));
}
}
I have an ArrayList of CustomInput objects and DataWrapper class with getter and setter for the ArrayList. I want to pass DataWrapper from Non-Activity class to Activity class. I have tried implementing Serializable, but I get Parcelable encountered ioexception writing serializable object cause by NotSerializableException.
DataWrapper.java
public class DataWrapper implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<CustomInput> customInputs;
public void setFields(ArrayList<CustomInput> data) {
this.customInputs = data;
}
public ArrayList<CustomInput> getFields() {
return this.customInputs;
}
}
Non-Activiy class
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("title", title);
DataWrapper dw = new DataWrapper();
dw.setFields(fields);
intent.putExtra("data", dw);
request.startActivity(intent);
}
ActivityKorak.class->onCreate()
Intent intent = getIntent();
String title = intent.getStringExtra("title");
DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
ArrayList<CustomInput> fields = dw.getFields();
No need to create new class DataWrapper.java. Because ArrayList is serializable.
Non-Activiy class
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("title", title);
intent.putExtra("data", fields);
request.startActivity(intent);
}
ActivityKorak.class->onCreate()
Intent intent = getIntent();
String title = intent.getStringExtra("title");
DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
ArrayList<CustomInput> fields = dw.getFields();
hi please check how we can send arraylist in intent
ArrayList<HashMap<String, String>> aldata = new ArrayList<HashMap<String, String>>();
i assumed here data is already added in your arraylist, please check
Send data and start other activity,
Intent intent = new Intent(this,AbcActivity.class);
intent.putExtra("aldata", aldata_TaxiLine);
startActivity(intent);
Get data in your next activity,
ArrayList<HashMap<String, String>> aldata1;
and call this in your oncreate
aldata = (ArrayList<HashMap<String, String>>) getIntent()
.getSerializableExtra("aldata");
hope this will help you.
I want to pass two values to another activity can I do this with putExtra or do I have to do it a more complicated way, which it seems from my reading. E.g.. can something like this work?
public final static String ID_EXTRA="com.fnesse.beachguide._ID";
Intent i = new Intent(this, CoastList.class);
i.putExtra(ID_EXTRA, "1", "111");
startActivity(i);
The above gives an error.
Edit
The first thing I tried was similar to:
i.putExtra(ID_EXTRA1, "1");
i.putExtra(ID_EXTRA2, "111");
but ID_EXTRA2 seems to write over ID_EXTRA1
So,
i.putExtra(ID_EXTRA, new String[] { "1", "111"});
Looks like the go but how do I extract the values from the array in the second activity, I have been using this for a single value.
passedVar = getIntent().getStringExtra(CoastList.ID_EXTRA);
I guess I have to turn ID_EXTRA into an array somehow???
You could pass a 'bundle' of extras rather than individual extras if you like, for example:
Intent intent = new Intent(this, MyActivity.class);
Bundle extras = new Bundle();
extras.putString("EXTRA_USERNAME","my_username");
extras.putString("EXTRA_PASSWORD","my_password");
intent.putExtras(extras);
startActivity(intent);
Then in your Activity that your triggering, you can reference these like so:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String username_string = extras.getString("EXTRA_USERNAME");
String password_string = extras.getString("EXTRA_PASSWORD");
Or (if you prefer):
Bundle extras = getIntent().getExtras();
String username_string = extras.getString("EXTRA_USERNAME");
String password_string = extras.getString("EXTRA_PASSWORD");
You can pass multiple values by using multiple keys. Instead of
i.putExtra(ID_EXTRA, "1", "111");
do
i.putExtra(ID_EXTRA1, "1");
i.putExtra(ID_EXTRA2, "111");
Of course you have to define 2 constants for the keys and have to read both seperately in the new activity.
Or you can pass a string array via
i.putExtra(ID_EXTRA, new String[] { "1", "111"});
Putting extra values in class
public class MainActivity extends Activity {
public final static String USERNAME = "com.example.myfirstapp.MESSAGE";
public final static String EMAIL = "com.example.myfirstapp.EMAIL";
public void registerUser(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText userNameTxt = (EditText) findViewById(R.id.editText1);
EditText emailTxt = (EditText) findViewById(R.id.editText2);
String userName = userNameTxt.getText().toString();
String email = emailTxt.getText().toString();
intent.putExtra(USERNAME, userName);
intent.putExtra(EMAIL,email);
startActivity(intent);
}
Reading extra values from another class
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String user = intent.getStringExtra(MainActivity.USERNAME);
String email = intent.getStringExtra(MainActivity.EMAIL);
Passing bundle of extra for kotlin coders
val intent = Intent(this, MyActivity::class.java)
val extras = Bundle().apply {
putString("EXTRA_USERNAME", "my_username")
putString("EXTRA_PASSWORD", "my_password")
}
intent.putExtras(extras)
startActivity(intent)
Then retrieve your values in the other activity like below:
val extras = getIntent().extras
val username_string = extras?.getString("EXTRA_USERNAME")
val password_string = extras?.getString("EXTRA_PASSWORD")
No you can't but you can pass an array using:
public Intent putExtra (String name, String[] value)
like this for example:
i.putExtra(ID_EXTRA, new String[]{"1", "111"});
Your example won't work, since the Extras are made out of a Key and a Value. You cant put multiple Keys and Values in one Extra
Also, your keys need to be Strings as far as I know (and noticed) but I might be wrong on that one.
Try this:
public final static String ID_EXTRA="com.fnesse.beachguide._ID";
Intent i = new Intent(this, CoastList.class);
i.putExtra("ID_Extra", ID_EXTRA);
i.putExtra("1", 111);
startActivity(i);
For a single small amount of value putExtra is perfect but when you pass multiple values and need to pass custom ArrayList or List then I think it's a bad idea. Solution is you can use Parcelable. You and also use Singleton or Serializable also.
Parcelable:
Parcelable class which you need to share.
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Form your activity where you want to send
MyParcelable example = new MyParcelable();
.....
.....
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
From another activity where you want to receive
MyParcelable example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
i want to send multiple data from activity WelcomeScreen to OpenBook
here is my code
Sending
String a="pg558.sqlite";
String b="pg558";
Intent intent = new Intent(getApplicationContext(), OpenBook.class);
intent.putExtra("db_name",a);
intent.putExtra("book_name",b);
intent.putExtra("chapter_number",3);
intent.putExtra("page_number",1);
startActivity(intent);
Recieving
Bundle b = getIntent().getExtras();
DB_NAME= b.getString("db_name");
BOOK_NAME= b.getString("book_name");
CHAPTER_NUMBER= b.getInt("chapter_number",1);
PAGE_NUMBER= b.getInt("page_number",1);
i'm getting runtime error
03-21 16:29:34.989: ERROR/AndroidRuntime(10651): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mireader/com.mireader.OpenBook}: java.lang.NullPointerException
try Intent intent = new Intent(this, OpenBook.class);
and Bundle b = getIntent();
no need to use bundle, just use this:
Receiving:
Intent i=getintent();
String ab=i.getextra("db_name");
String bc=i.getextra("book_name");
....
you will get your result
in line Intent intent = new Intent(getApplicationContext(), OpenBook.class); use this
Intent intent = new Intent(youractivity.class, OpenBook.class);
instead of using getApplicationContext() use MyActivityClass.this
I have given up on trying to keep track of multiple name/value pairs. You can create an immutable class (or use Parcels) as:
public final class PasswordState implements Serializable {
private static final long serialVersionUID = 1L;
public static final int MIN_PASSWORD_LENGTH= 8;
public final int lengthKey; // in bytes
public final long timeExpire; // in milliseconds as a Calendar object
public final boolean isValidKey;
public final int timeoutType;
public final String password;
public final boolean isHashPassword;
public PasswordState(int lengthKey,
long timeExpire,
boolean isValidKey,
int timeoutType,
String password,
boolean isHashPassword){
this.lengthKey= lengthKey;
this.timeExpire= timeExpire;
this.isValidKey= isValidKey;
this.timeoutType= timeoutType;
this.password= password;
this.isHashPassword= isHashPassword;
}
Then pass this in an intent to the child activity:
private void launchManagePassword() {
Intent i= new Intent(this, ManagePassword.class); // no param constructor
PasswordState outState= new PasswordState(lengthKey,timeExpire,isValidKey,timeoutType,"",model.getIsHashPassword());
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outState);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_PASSWORD); // used for callback
}
Finally, retrieve the stateful object in the child activity:
try {
inPWState= (PasswordState) getIntent().getSerializableExtra("jalcomputing.confusetext.PasswordState");
lengthKey= inPWState.lengthKey;
timeoutType= inPWState.timeoutType;
isValidKey= inPWState.isValidKey;
timeExpire= inPWState.timeExpire;
isHashPassword= inPWState.isHashPassword;
// password= inPWState.password; // not required
} catch(Exception e){
lengthKey= PasswordState.MIN_PASSWORD_LENGTH;
timeoutType= TIMEOUT_NEVER;
isValidKey= true;
timeExpire= LONG_YEAR_MILLIS;
isHashPassword= false;
}
JAL
In your problem, activityclass.class means the class where you actually called the intent and bundle for sending data to the second activity.