Passing Bundle into an AsyncTask - android

I'm struggling with bundles in an AsyncTask. I have two Strings that I want to pass to a AsyncTask, I want to use bundles to accomplish this task.
The code in the MainActivity:
Bundle adresses = new Bundle();
adresses.putString("to", textField1.getText().toString());
adresses.putString("from", textField2.getText().toString());
new PriceTask(getApplicationContext()).execute(adresses);
And in my AsycTask I do it like this:
protected Integer doInBackground(Bundle... b) {
Bundle result = b[0];
String to = result.getString("to");
String from = result.getString("from");
}
It's worth mentioning that my two strings contains something like this
"Sometext here, and sometext here 1234"
Put I can't retrieve the text, my debugger says that the Bundle contains the right information but my String will not contain the right information. When I debug and set breakpoints where my Strings are, it will just have the value:
[t, o]
What am I doing wrong here? Thanks in advance.

In MAin activity replace the below lines::
Bundle adresses = new Bundle();
adresses.putString("to", textField1.getText().toString());
adresses.putString("from", textField2.getText().toString());
new PriceTask(getApplicationContext()).execute(adresses);
with
new PriceTask(getApplicationContext(),textField1.getText().toString(),textField2.getText().toString()).execute();
And in your AsycTask add constructor like below::
String to;
String from;
Context context;
public YourAsyncTask(Context context, String to,String from) {
// TODO Auto-generated constructor stub
this._activity = _activity;
this.to = to;
this.from = from;
}

What you are doing wrong is the way you retrieve the data in the doInBackground method. The argument that method having is a Array type. Please concern the ... What you are doing in the line Bundle result = b[0]; is only getting the 0th element of that Array and pass it to a Bundle reference.
Your given code and details is not enough to give a perfect answer. If all your given codes in the same Java class, you no need to use a Bundle. Instead you can create a ArrayList of type String to contains your values witch you are getting from the TextFields. Then doInBackground also contains a ArrayList as the method argument. Then get all the List items and separate your "to" and "from" values.
If you are stick with the existing code, first try to find out what is inside the result variable.

Related

How to get string from resources strings into a fragment

I tried reading a number of solutions on Stack Overflow and have found they either don't work for my scenario or I simply don't understand their explanation (I am very new to Java and Android.
I have strings set up under res/values/strings.xml that I wish to use in the class:-
public class AttractionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.word_list, container, false);
// create an array list of details
final ArrayList<Details> details = new ArrayList<>();
// Details details
details.add(new Details(getActivity().getString(R.string.fun_bigsplash_name), getString(R.string.fun_bigsplash_addr), R.string.fun_bigsplash_num, R.drawable.bigsplash));
I've tried a number of variants (the reason they are different is just to show what I tried) but can't work it out. The R.drawable.bigsplash works fine (when I'm using literal strings for the others).
The error message states an int, which I assume means it's getting the reference and not the actual string.
How do I get the string from within the fragment?
Thanks.
You can use:
getResources().getString(R.string.my_string);
or just:
getString(R.string.my_string);
Read String value or String Array In Java Code.
Define a string array in strings.xml use string-array xml element.
Show Selection
<string name="auto_complete_text_view_car">Input Favorite Car Name</string>
<string-array name="car_array">
<item>Audi</item>
<item>BMW</item>
<item>Benz</item>
<item>Ford</item>
<item>Toyota</item>
<item>Tesla</item>
<item>Honda</item>
<item>Hyundai</item>
</string-array>
Read String Value In Java Code. Only string name
Inside Activity::
String defaultInputText = getResources().getString(R.string.auto_complete_text_view_car);
Inside Fragment::
String defaultInputText = getActivity().getResources().getString(R.string.auto_complete_text_view_car);
Read the string array in java source code. Please note car_array is just the string array name defined in strings.xml.
Inside Activity::
String carArr[] = getResources().getStringArray(R.array.car_array);
Inside Fragment::
String carArr[] = getActivity().getResources().getStringArray(R.array.car_array);
Simplest way to get string from resource in any part of your code is to override Application class and create static method to obtain "Application context".
For example, check out the application class for my app AB Music.
https://github.com/amit-bhandari/AB-Music-Player/blob/master/app/src/main/java/com/music/player/bhandari/m/MyApp.java
Refer method
public static Context getContext(){
return instance;
}
Now you can get string from resource anywhere in your code by simply calling.
MyApp.getContext().getString(R.string.mystring)
Hope it helps!
try this one
getActivity().getResources().getString(R.string.app_name)

SharedPreferences - Android (different data types)

I have a problem with with sharing data between two different activities. I have data like :
int number
String name
int number_2
int time
int total
I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .
I have an idea of making it in array of object - but data inside was cleared after changing activity.
How can I make it ?
I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.
You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.
Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.
Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...
You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.
public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}
public static ShareData getInstance(){ return shareData}
//create getters and setters;
}
Why not to use Intents
Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);
in the second activity
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");
EDIT if you want to read more about adding array to shared preferences check this
Is it possible to add an array or object to SharedPreferences on Android
also this
http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html

How to clear values of all static variables at the end of an activity Android?

I have created an application that takes in user name and other details for a transaction and then fills them in a database. At times the application shows odd behavior by filling the SAME details in the database twice as two transactions. Even though the new values are read but not STORED in the static variables.
Therefore I needed help in flushing the values of all my static variables at the end of each activity to avoid overriding of the previous values in a fresh transaction.
EDIT :
public class One
{
static String var;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
var="blah";
}
}
public class Two
{
static String variable = One.var;
// This is where i am accessing the value of the variables from previous activities.
//CODE
}
May these help you..
Using Static Variables is like a nightmare in any activity as it stores memory through out the activity..
I think you can try some other memory store to overcome your problem of passing value from one activity to another..
In my opinion u can store values in SharedPreference or either you can pass value through intent to other activity where ever it is required..
Hope these will help you..
EDIT:
Intent in = new Intent(MainActivity.this,SecondActivity.class);
You can use more than one putExtra() method to put several values and can fetch then in Second Activity
in.putStringArrayListExtra(String name, ArrayList<String> value);
StartActivity(in);
In Second Activity:
Intent in = getIntent();
ArrayList<String> Roleids = new ArrayList<String>;
RoleId = in.getStringArrayListExtra(String name, ArrayList<String> value)

Passing multiple data to an Activity?

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.

Pass DoubleArray from the object of one activity to another

i would like to send the values from one activity to another but i got null in the second activity please solve my problem.the first activity contains blog_info the details of that
blog is send to second activity based on these values the second activity search places .
final ArrayList<Blog> blogList = (ArrayList<Blog>) message
.getResultList("Blog");
for (Blog blog : blogList) {
int i=0;
latitude_Array[i] = Double.parseDouble(blog.getLatitude_zzs());
longitude_Array[i]=Double.parseDouble(blog.getLongitude_zzs());
i++;
}
btn = (Button) findViewById(R.id.main_top_map_list);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
MainActivity_MapList.class);
//The method putDoubleArray(String, double[]) in the type Bundle is not applicable for the arguments (String, Double[])
bundle.putDoubleArray("latitude_Array", latitude_Array);
// intent.putExtras(bundle);
finish();
startActivity(intent);
}
});
i have used a series of method such as :
bundle.putDoubleArray(key, value)
bundle.putSparseParcelableArray(key, value)
bundle.putParcelableArray(key, value)
bundle.putSerializable(key, value)
but i just get 'null' or '0.0' in the second activity.
first, in the code you posted, you are putting an arraylist of lists of doubles, but then casting it to an arraylist of ? extends parcelable. those aren't the same type.
i assume you just want to pass a list (or array) of doubles. you can either use putDoubleArray() or putSerializable(). if you want to deal with an array of doubles, you need to have your doubles in a double[], like,
double[] doubles = ...; // whatever
bundle.putDoubleArray(key, doubles);
to get them out on the other side,
double[] doubles = bundle.getDoubleArray(key);
if you want to pass your doubles in an array list, you must have your doubles in an ArrayList<? implements Serializable> ... e.g., ArrayList<Double>. like this,
ArrayList<Double> doubles = ...; // whatever
bundle.putSerializable(key, doubles);
to get them out of the bundle on the other side,
ArrayList<Double> doubles = (ArrayList<Double>)bundle.getSerializableExtra(key);

Categories

Resources