I use httpclient along with cookiestore to keep my session, now I want to use the same session on the next activity, I'm using api 8 so I can't use cookiemanager. Is it possible? If only I could somehow send the cookie list through, eg:
Intent i = new Intent(this, Login.class);
i.putExtra("domain", domain);
//need to get the following list across
List<Cookie> cookies = cookieStore.getCookies();
//i.putMyDamnCookies("cookies",cookies);
startActivity(i);
Any idea how I could achieve this?
Yes you can send a List to another activity, but first you'll need to convert it to an instance of ArrayList, or String[] array.
Take a look over this threads:
Passing a List to another Activity in Android
How to put a List in intent
store your List as an array of strings and pass it to in an intent to next activity like this:
String[] cookieArray = new String[cookies.size()];
//copy your List of Strings into the Array
int i=0;
for(Cookie c : cookies ){
cookieArray[i]=c.toString();
i++;
}
//then pass it in your intent
Intent intent = new Intent(this, Login.class);
intent.putExtra("cookieArray", cookieArray);
startActivity(i);
Then in your next actvity, retrieve the array of cookies from the intent and convert the cookies back like so:
List<Cookie> cookies = new List<Cookies>();
for(int i=0;i<cookieArray.size;i++)
{
cookies.add(new HttpCookie(cookieArray[i]));
}
Sure - just read the cookie from the HTTP header, and store it however is convenient for you.
I think this is probably overkill, but here's an example that uses the Apache HTTP Client that ships with Android 2.2:
How do I make an http request using cookies on Android?
Also look here (available since level 1):
http://developer.android.com/reference/org/apache/http/cookie/package-summary.html
Related
I'm trying to transfer ArrayList between activities, but nothing I've tried works as well.
This was my best shot, but this didn't work either.
I'm calling the external action here:
getComics getComicInfo = new getComics(charName, pageNum);
getComicInfo.execute();
getIntentData()
and here i'm trying to put data, but the problem is due the fact that this is an external action, so I can't shift through activits.
if(counter == comicInfoObject.length()){
Log.v("check arr length =>" , Integer.toString(comicList.size()));
Intent i = new Intent();
i.putExtra("comicArrayList", (ArrayList<Comics>)comicList);
}
and here i'm tring to retrive the data, but it doesn't get inside the "if"
public void getIntentData(){
Intent i = getIntent();
if(i != null && i.hasExtra("comicArrayList")){
comicList2 = i.getParcelableExtra("comicArrayList");
int size = comicList2.size();
}
}
first code is where I call an external class that using api and in the bottom line creates the arrayList
second code is inside the external class, where I'm trying to pass the arrayList with putExtra
third code is where i'm tring to retrive the data after getIntentData().
Pack at the sender Activity
intent.putParcelableArrayListExtra(<KEY>, ArrayList<Comics extends Parcelable> list);
startActivity(intent);
Extract at the receiver Activity
getIntent().getParcelableArrayListExtra(<KEY>);
You need make a Comics class that implements Parcelable, then use put ParcelableArrayListExtrato pass arraylist.
Here is a sample link for Pass data between activities implements Parcelable
However be careful if your array list too big, you could get intent exception, for this case you could think about a static reference to store your array list.
I'm developing an Android app and I'm kind of new to this. What I'm currently trying to do is to maintain a user logged in. To login I have to make a request to an API and send the user email and password, that returns a JSONObject which I manage just fine. I have a CookieStore variable to get the cookies and store them into my SharedPreferences.
I just realised my cookies get lost if I close the application and I need to keep making requests to the API even if the app gets resumed, because the user has already logged in. I tried to "restore" the cookies in the onResume() method of one of my activities but that doesn't work the way I want it to. If I try to get the cookies using CookieStore.getCookies() after I resume my app that list is null.
I've been told I can use loopj's AsynHttpClient and manage my cookies with PersistentCookieStore but wouldn't that get me to the same problem? I'd be losing the value of the PersistentCookieStore instance every time I resume my app, right?
so my question is:
How can I restore the cookies in order to keep them persistent and make me able to keep making requests to the API?
Hope anyone can help me with this.
Thanks in advance.
You have two options:
Option 1 - If using SharedPreferences and HttpUrlConnection: you need to manually retrieve the cookie from the SharedPreferences and add the cookie to each request when using HttpUrlConnection.
Option 2 - If using loopj AsyncHttpClient: According to the loopj documentation, you must create an instance of PersistentCookieStore and add it to your AsyncHttpClient every time your app is restarted, like so
AsyncHttpClient myClient = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
where 'this' is a Context.
How do you store/restore your cookies to/from the SharedPreferences? Can you share some code?
Also can you try debugging it and tell us what's wrong with it? Does it not get stored to the SharedPreferences? Does it fail to restore them?
Before storing/restoring the CookieStore to the SharedPreferences, you would need to create a Serializable object with it first, such as an ArrayList<HashMap<String, String>
Something like:
public static void storeCookies(Context context, CookieStore cookieStore) {
ArrayList<HashMap<String, String> cookies = new ArrayList<HashMap<String, String>();
for (Cookie cookie : cookieStore.getCookies()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", cookie.getName());
map.put("path", cookie.getPath());
map.put("domain", cookie.getDomain());
map.put("expiry_date", cookie.getExpiryDate());
map.put("ports", cookie.getPorts());
map.put("value", cookie.getValue());
map.put("version", cookie.getVersion());
...
// Add all the fields you want to save
cookies.add(map);
}
SharedPreferences.Editor editor = context.getSharedPreferences().edit();
editor.putSerializable("cookies", cookies).apply();
}
public static void addCookiesToStore(Context context, CookieStore cookieStore) {
List<Map<String, String>> cookies = (ArrayList<HashMap<String, String>>) context.getSharedPreferences().getSerializable("cookies");
for (Cookie map : cookieStore.getCookies()) {
Cookie cookie = new BasicClientCookie(map.getName(), map.getValue());
cookie.setPath(map.get("path));
...
// Add all the fields you want to restore
cookieStore.add(cookie);
}
}
I'm trying to pass multiple data items in one Intent:
if (strActStat == "Sedentary") {
// passactStat.putString("keySedentary", strActStat);
// passSeden.putString("keyMale", gender);
i = new Intent(CalorieTrackerTargetWeight.this, TargetWeightResults.class);
i.putExtra("keyGender", gender);
i.putExtra("keyAct", strActStat);
//i.putExtra("keyAct", strActStat);
startActivity(i);
}
Why doesn't this work? Why can't I pass multiple items in one Intent?
You can't compare strings with ==.
if (strActStat.equals("Sedentary")) { // should work
Edit:
#Hesam has written a pretty detailed answer but his solution is not really usable. Instead of using an ArrayList<String> you should stick with the putExtra(key, value). Why? Well there are some advantages over the ArrayList solution:
you are not limited to the type of the ArrayList
you are not forced to keep a static order in you list. As you can only work with index values to get a list you need to make sure that the put() was in the same order as get(). Think of the following case: You you often send 3 values, but in some cases you don't want to send the second value. When you use the ArrayList solution, you end up sending null as the second value to ensure that the third value will stay in his place. This is highly confusing coding! Instead you should just send two values and when the receiving activity tries to receive the second value, it can handle the returning null like it want... for example replace it with a default value.
Naming of the key will grant you the knowledge of always knowing what should be inside...
Your key should be declared in the receiving Activity as a constant. So you always know by looking at this constants what intent data the activity can handle. This is good programming!
Hope this helps in clarifying the intent usage a bit.
I think this is not the only problem, first, if (strActStat == "Sedentary") this is wrong. you can't compare to string in this way. Because in this way objects are comparing not the string. Correct way is if (strActStat.equalIgnoreCase("Sedentary")).
If you use Parcelable then you can pass multiple data in just 1 intent.
Also you can use ArrayList<String>.
Here is a skeleton of the code you need:
Declare List
private List<String> test;
Init List at appropriate place
test = new ArrayList<String>();
and add data as appropriate to test.
Pass to intent as follows:
Intent intent = getIntent();
intent.putStringArrayListExtra("test", (ArrayList<String>) test);
Retrieve data as follows:
ArrayList<String> test = data.getStringArrayListExtra("test");
Hope that helps.
Try this:
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
namevalue=name.getText().toString();
overvalue=over.getText().toString();
audiostatus=audio.getText().toString();
Intent intent=new Intent(Settings.this,home.class);
Bundle bundle = new Bundle();
bundle.putString( "namevalue",namevalue);
bundle.putString("overvalue",overvaluse);
bundle.putInt("value",variablename);
intent.putExtras(bundle);
startActivity(intent);
}
});
I faced the same problem.
My mistake was that one of the variable I was transferring was not initialized.
Like gender or strActStat in your case.
I have read about global static technique in which we create a class with static fields which can be accessed in any activity. Is there any other way to pass large data sets like ArrayList<Drawables> or HashMaps ?
I have also read about Serializable but have no idea how to use it. Any example code is welcome...
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("arraylist", new ArrayList<String>());
If your ArrayList contains another Object that you have created yourself, for instance Friend.class, you can implement the Friend.class with Serializable and then:
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("friendlist", new ArrayList<Friend>());
And for receiving it on NextActivity.class:
Bundle extras = getIntent().getExtras();
if(extras != null){
ArrayList<Friend> friends = extras.getSerializable("friendlist");
}
Well, instead of passing an empty ArrayList, you'll have to put values into the ArrayList and then pass it, but you get the idea.
You should pack your information into the Intent object you create to call your next Activity. There is a extras Bundle object.
You can use either the Serializable interface or the Android-specific Parcelable interface to pass non-primitive objects.
The Android Developer site has a handy Notepad Tutorial with an example of putting information into the intent.
From their tutorial:
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
As long as you stay in the same application( speak: same JVM ) you do not need to bother with intents, parcelables, serialisation etc - all objects are on same heap and can be passed via singletons, DI containers like roboguice or whatever you see fit.
If you like to push data to an other application, best technique would be to pass it as JSON/XML serialized stuff.
Passing Hashmap is pretty simple, All Collections objects implement Serializable (sp?) interface which means they can be passed as Extras inside Intent
Use putExtra(String key, Serializable obj) to insert the HashMap and on the other acitivity use getIntent().getSerializableExtra(String key), You will need to Cast the return value as a HashMap though.
I would like to be able to transfer data from one activity to another activity. How can this be done?
Through the below code we can send the values between activities
use the below code in parent activity
Intent myintent=new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity
String s= getIntent().getStringExtra(<StringName>);
There are couple of ways by which you can access variables or object in other classes or Activity.
A. Database
B. shared preferences.
C. Object serialization.
D. A class which can hold common data can be named as Common Utilities it depends on you.
E. Passing data through Intents and Parcelable Interface.
It depend upon your project needs.
A. Database
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.
Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html
B. Shared Preferences
Suppose you want to store username. So there will be now two thing a Key Username, Value Value.
How to store
// Create object of SharedPreferences.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", "stackoverlow");
//commits your edits
editor.commit();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
How to fetch
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");
http://developer.android.com/reference/android/content/SharedPreferences.html
C. Object Serialization
Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.
Use java beans and store in it as one of his fields and use getters and setter for that
JavaBeans are Java classes that have properties. Think of
properties as private instance variables. Since they're private, the only way
they can be accessed from outside of their class is through methods in the class. The
methods that change a property's value are called setter methods, and the methods
that retrieve a property's value are called getter methods.
public class VariableStorage implements Serializable {
private String inString ;
public String getInString() {
return inString;
}
public void setInString(String inString) {
this.inString = inString;
}
}
Set the variable in you mail method by using
VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);
Then use object Serialzation to serialize this object and in your other class deserialize this object.
In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
If you want tutorial for this refer this link
http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html
Get variable in other classes
D. CommonUtilities
You can make a class by your self which can contain common data which you frequently need in your project.
Sample
public class CommonUtilities {
public static String className = "CommonUtilities";
}
E. Passing Data through Intents
Please refer this tutorial for this option of passing data.
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
When you passing data from one activity to another activity perform like this
In Parent activity:
startActivity(new Intent(presentActivity.this, NextActivity.class).putExtra("KEY_StringName",ValueData));
or like shown below in Parent activity
Intent intent = new Intent(presentActivity.this,NextActivity.class);
intent.putExtra("KEY_StringName", name);
intent.putExtra("KEY_StringName1", name1);
startActivity(intent);
In child Activity perform as shown below
TextView tv = ((TextView)findViewById(R.id.textViewID))
tv.setText(getIntent().getStringExtra("KEY_StringName"));
or do like shown below in child Activity
TextView tv = ((TextView)findViewById(R.id.textViewID));
TextView tv1 = ((TextView)findViewById(R.id.textViewID1))
/* Get values from Intent */
Intent intent = getIntent();
String name = intent.getStringExtra("KEY_StringName");
String name1 = intent.getStringExtra("KEY_StringName1");
tv.setText(name);
tv.setText(name1);
Passing data from one activity to other in android
Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);
Retrieving bundle data from android activity
Intent intent = getIntent();
if (intent!=null) {
String stringData= intent.getStringExtra(KEY);
int numberData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue); }
Hopefully you will find the answer from here Send Data to Another Activity - Simple Android Login
You just have to send extras while calling your intent
like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class); intent.putExtra("Variable Name","Value you want to pass"); startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this
If the value u sent was in "long"
long value = getIntent().getLongExtra("Variable Name which you sent as an extra", defaultValue(you can give it anything));
If the value u sent was a "String"
String value = getIntent().getStringExtra("Variable Name which you sent as an extra");
If the value u sent was a "Boolean"
Boolean value = getIntent().getStringExtra("Variable Name which you sent as an extra",defaultValue);
Your Purpose
Suppose You want to Go From Activity A to Activity B.
So We Use an Intent to switch activity
the typical code Looks Like this -
In Activity A [A.class]
//// Create a New Intent object
Intent i = new Intent(getApplicationContext(), B.class);
/// add what you want to pass from activity A to Activity B
i.putExtra("key", "value");
/// start the intent
startActivity(i);
In Activity B [B.class]
And to Get the Data From the Child Activity
Intent i = getIntent();
if (i!=null) {
String stringData= i.getStringExtra("key");
}
This works best:
Through the below code we can send the values between activities
use the below code in parent activity(PARENT CLASS/ VALUE SENDING CLASS)
Intent myintent=new Intent(<PARENTCLASSNAMEHERE>.this,<TARGETCLASSNAMEHERE>.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity(TARGET CLASS/ACTIVITY)
String s= getIntent().getStringExtra(<StringName>);
Please see here that "StringName" is the name that the destination/child activity catches while "value" is the variable name, same as in parent/target/sending class.