I want to pass my API response to another activity . I am using intent but getting null in the next activity .
My code is MainPage.java
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
}
I am getting the correct response .
Calculation.java
Intent intn = new Intent();
members = intn.getStringExtra("MEMBERS");
System.out.println("dmkmdk"+members);
//no_of_members = Integer.parseInt(members);
I also want to parse it in integer form .
you should get extra like this, don't initiate an intent object
Bundle extras = getIntent().getExtras();
String value1 = extras.getString("MEMBERS");
Try to save data in SharedPreference instead Intent.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
For Storing data:-
editor.putString("MEMBERS",members);
editor.apply();
For retriving data:-
editor.getString("MEMBERS", null); // getting String
Please try this
To Transfer data in next activity
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
startActivity(intn)
}
In New activity where you want to get data try this line
String resFromLast = getIntent().getExtras().getString("MEMBERS");
Log.e("Response From last activity is :" ,resFromLast);
MEMBERS is that key you passed in last activity with intent.
Hope it works.
Related
This is my Activity 1
final Intent ridesameIntent = new Intent(this, Activity2.class);
TextView userText = (TextView) findViewById(R.id.username);
ImageView userImage = (ImageView) findViewById(R.id.profile_pic);
String userNameMessage = userText.getText().toString();
String userPicMessage = userImage.toString();
ridesameIntent.putExtra(EXTRA_MESSAGE_USERNAME,userNameMessage);
ridesameIntent.putExtra(EXTRA_MESSAGE_USERPIC,userPicMessage);
startActivity(ridesameIntent);
This is Activity 2
Intent userDetail = getIntent();
String userPicMessage = userDetail.getStringExtra(Activity1.EXTRA_MESSAGE_USERPIC);
String userNameMessage = userDetail.getStringExtra(Activity1.EXTRA_MESSAGE_USERNAME);
TextView userdetail1 = (TextView) findViewById(R.id.username_scroll);
ImageView userdetail2 = (ImageView) findViewById(R.id.profile_pic_scroll);
userdetail1.setText(userNameMessage);
userdetail2.setImageURI(Uri.parse(userPicMessage));
I have tried passing the uri but getting no results in passing the user pic
also for help here is the code which fetches user profile from Facebook and sets it into the navbar of Activity 1
public void setUserProfile(String jsondata) {
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);
} catch (Exception e) {
e.printStackTrace();
}
}
So please suggest me how can i get the image to activity 2.
Hello this is my code by which i get rid of this problem
In first Activity
Profile profile = Profile.getCurrentProfile();
Bundle mBundle = new Bundle();
mBundle.putParcelable("pic", profile);
Intent loginint = new Intent(MainActivity.this,DashBoard.class);
loginint.putExtra("email",email);
loginint.putExtras(mBundle);
startActivity(loginint);
finish();
And in Second Activity where u want to show that Image
Intent intent = getIntent();
Bundle mBundle =intent.getExtras();
Profile profile;
if (mBundle != null) {
profile = (Profile) mBundle.getParcelable("pic");
} else {
profile = Profile.getCurrentProfile();
}
Picasso.with(DashBoard.this)
.load(profile.getProfilePictureUri(400, 400).toString())
.into(mfbimage);
here mfbimage is object of ImageView where u want to show that Profile Picture.
profile_pic_url.getString("url") extract this value into a variable and pass it as your intent extra and then load it with a Picasso in your second activity like in your setUserProfile method.
EDIT.
So in your setUserProfile(String jsondata) method on this line Picasso.with(this).load(profile_pic_url.getString("url")).into(user_picture); in your load() method you're extracting an url string from a JSONObject by calling profile_pic_url.getString("url"). You can create a field from that statement via Right click -> Refactor -> Extract -> Field... And then call put it as extra to your intent by calling ridesameIntent.putExtra(EXTRA_MESSAGE_USERPIC, fieldNameThatYouExtracted);
Then in your second activity call
Picasso.with(this).load(userPicMessage).into(userPicMessage); instead of userdetail2.setImageURI(Uri.parse(userPicMessage));
After that you can learn how to simplify json deserialization using GSON library Leveraging the Gson Library
You can pass the image Bitmap through the intent to the second activity as it implements the Parcelable interface.
Bitmap profileBitmap = ((BitmapDrawable)user_picture.getDrawable()).getBitmap();
ridesameIntent.putExtra("profilePic", profileBitmap);
And on the other end :
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("profilePic");
I'm using the Gson library to save and retrieve an ArrayList of Players Objects.
My onStop()
#Override
protected void onStop() {
super.onStop();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String guardJSON = gson.toJson(playersNoGuard);
editor.putString(GUARD, guardJSON);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
My onCreate important part
ArrayList<Player> playersNoGuard;
RecyclerView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_players_guard);
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
String guardJSON = prefs.getString(GUARD, null);
Type arrayListPlayers = new TypeToken<ArrayList<Player>>(){}.getType();
Gson gson = new Gson();
if(guardJSON != null) {
playersNoGuard = gson.fromJson(guardJSON, arrayListPlayers);
}
// Get the players and remove the Clairvoyant
Intent intent = this.getIntent();
playersNoGuard = intent.getParcelableArrayListExtra("PLAYERS");
[...] // Code skipped
}
But when this Activity is run, I get the following error log:
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
What's wrong in this code?
You probably write to the same preferences entry somewhere else. Ensure that your key (GUARD) is unique throughout the application.
The problem is with your Response while Gson converting a response it expected Array in response but in your response you have made you are passing Object.
This is already answered here and here
here is reverse situation described.
For storing the serilaizable java object i m using below code
if(sharedpreferences.getString(ComplexObjectXMl,"")!=null) {
Serializer serializer = new Persister();
MyObject example = null;
try {
example = serializer.read(MyObject .class, sharedpreferences.getString(ComplexObjectXMl,""));
} catch (Exception e) {
e.printStackTrace();
}
Intent i1 = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i1);
}
new MyAsyncTask().execute();
In MyAsyncTask i m storing the XmlDataOverHttp in sharedPreferences. Will it get updated everytime if i like do this
you can compare byte array of those object. one coming from shared preference and other which is latest.
byte[] array = new Gson().toJson(latestObject).getBytes(); //your lattest byte array
byte[] secondArray = new Gson().toJson(objectConvertedFromSharedPreferenceOLD).getBytes();
if (Arrays.equals(array, secondArray))
System.out.println("They are same");
else
System.out.println("Nope...");
and as you said you can use service or shared preference to check hourly update in oncreateView() but it only happens when user open your app(between hour it will call api for list items)
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
(Dashboard.this);
long lastUpdateTime = mSettings.getLong("lastUpdateTime", 0);
/* Should Activity Check for Updates Now? */
if ((lastUpdateTime + (3600000)) < System.currentTimeMillis()) {
/* Save current timestamp for next Check*/
SharedPreferences.Editor editor = mSettings.edit();
lastUpdateTime = System.currentTimeMillis();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
/* Start Update for listview your URL to fetch data and then you can check and compare object
also you can use swipeRefreshLayout so user can also refresh data*/
//asyncRequestTime.execute(URL);
}
I have an issues reading from sharedpreferences in android. The data is stored in the preference file, and i ma sure of this because i used logcat to log the data when i read it back IMMEDIATELY as it was stored as well as i used a toast message to display the data after i read it back from preferences. However when i try to read the data again from a new activity it returns the default of an empty sting. When i exist the app and run it again it read the data that was previously stored. Here is my code for when i initially save the data, it also contains the comments i used to verify that the data stored was read back:
public void downloadMatchesAsync() {
brawtaAPIAdapter.runGetMatches(new Callback<JSONKeys>() {
#Override
public void success(JSONKeys jsonKeys, Response response) {
Log.d(ApplicationConstants.TAG, "blarg");
Success = jsonKeys.isSuccess();
message = jsonKeys.getErrorMessage().toString();
if(!message.isEmpty()){
Toast.makeText(MyApplication.getAppContext(), message, Toast.LENGTH_SHORT).show();
}
Gson gson = new Gson();
String jsonObject = gson.toJson(jsonKeys); //converts java object into json string'
Preferences.saveToPreferences(activity, ApplicationConstants.match_data, jsonObject);
//data =Preferences.readFromPreferences(activity, ApplicationConstants.match_data, "no data");
//Toast.makeText(MyApplication.getAppContext(), "In networkOperation" + data, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
}
}); // Call Async API
//return data;
}
In a different activity i try to read the data previously written like so:
jsonString = Preferences.readFromPreferences(MatchSelect.this, ApplicationConstants.match_data, "");
but the code only returns the data stored if i exist the app and run it again.
this is my preference class:
public class Preferences {
private static final String PrefName = "net.brawtasports.brawtasportsgps";
public static void saveToPreferences(Context context, String key, String value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
public static String readFromPreferences(Context context, String key, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultValue);
}
}
What is the issue?
apply() is an asynchronous call, so the data doesn't have to be stored immediately. Try calling .commit() instead.
I want to implement a search in my Android application.
In this page, first I am displaying a user list and then performing a search on the user list. Both are in the same activity. In the following manner, I am getting intent and some values from the previous page. When I display the user list, all the values are coming. But while performing search, spaceId gets lost and becomes null. I need this value.
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
What should I do to get this value?
Edit:
String spaceId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
getMatchingstrings()
ArrayList<Ticket> getMatchingStrings(ArrayList<Ticket> list, String regex1) {
ArrayList <Ticket> listClone = new ArrayList<Ticket>();
for (Ticket string : list) {
if(string.getAssignedTo().equals(regex1)){
listClone.add(string);
}
}
return listClone;
}
Try it
getIntent().getExtras().getString("spaceId");
You said your activity is recreating. So you are not getting the value of spaceID after recreation. Then do this thing as below.
public String PREFS_NAME = "Shared_Pref";
Bundle receiveBundle = this.getIntent().getExtras();
String spaceId_value = receiveBundle.getString("spaceId");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if(spaceId_value == null) {
spaceId_value = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId_value);
}
I hope this will help you out.
edit :
I am editing your code.
Which part i have edited, i have mentioned that part as edited. Carefully see what i have changed and do that thing in your code. Then let me know.
String spaceId;
public String PREFS_NAME = "Shared_Pref"; //edited part
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//editing start
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Bundle receiveBundle = this.getIntent().getExtras();
if(receiveBundle != null) {
spaceId = receiveBundle.getString("spaceId");
if(spaceId == null) {
spaceId = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId);
}
}
//editing end
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
When you are firstly loading your list in activity,you have to save that spaceId in some SharedPreference variable for further use.And while reloading activity with search result,you can find that Id from SharedPreference variable previously saved.
Be sure,you overwrite that variable as and when you firstly load list in your activity to meet your needs cleanly.
Also you have to get spaceId from intent like:
int spaceId=0;
if(getIntent().hasExtra())
spaceId=getIntent().getStringExtra("spaceId");
Doing this wont give you excpetion when you reload the same activity with no extras to your intent.
Or,you will have to pass this spaceId along with intent you are using to reload the same activity for showing search result.
Hope,you get the point!
If u relaunching the same activity while performing search,u will lost that value. If u r doing so,while relaunching also pass that spaceId to the relaunching activity also using intent.putextra() method
as in your question and comments i guess you are getting problem if your activity is recreated
add following code in manifest file under your activity tag
android:configChanges="keyboardHidden|orientation"
your activity will not be created again
and then use the value of spaceID where you need