I use an ArrayList to store some data and then pass it to the next activity where it is actually required through the .putStringArrayList() method. I use the same process in a couple of places in a my project where it works absolutely fine. However, in this particular case, when I extract it in the receiving activity, it contains null. To be sure, I even displayed the list before sending it, and it did displayed the strings I require. Here is my code for sending the Arraylist:
for(int i=0; i<AssignmentTitles.size(); i++)
{
System.out.println(AssignmentTitles.get(i));
}
Intent localIntent;
localIntent = new Intent(CourseFolder.this, Assignments.class);
Bundle b=new Bundle();
b.putStringArrayList("titles",AnnouncementTitles);
b.putStringArrayList("links",AnnouncementLinks);
localIntent.putExtras(b);
startActivity(localIntent);
Here is the receiving activity code:
AssignmentTitles = getIntent().getStringArrayListExtra("titles");
AssignmentLinks = getIntent().getStringArrayListExtra("links");
System.out.println("size: " + AssignmentLinks.size() + "TITLES:");
for(int i=0; i<AssignmentTitles.size(); i++)
{
System.out.println(AssignmentTitles.get(i));
}
setListAdapter( new ArrayAdapter<String(Assignments.this,
android.R.layout.simple_list_item_1,
AssignmentTitles));
The problem is that I use the exact same code in another part of my project and it works perfectly, what could be the problem?
Try this way
AssignmentTitles = getIntent().getExtras().getStringArrayList("titles");
AssignmentTitles = getIntent().getExtras().getStringArrayList("links");
Use Intent.getExtras() to get the Bundle first, then extract your array lists.
Related
I am trying to learn retrofit and I have made successful attempts at posting data and now I am trying to retrieve JSON array which looks as follows:
{
"result": "success",
"message": "All Questions Have Been Selected",
"question": {
"all_question_ids": ["1","2","3"]
}
}
I am using the following getter
public ArrayList getAll_question_ids(){
return all_question_ids;
}
I am retrieving using Retrofit as follows
if (resp.getResult().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = pref.edit();
Log.d("Question_IDs", "getAllQuestionID() = " + response.body().getQuestion().getAll_question_ids() );
editor.putString(Constants.All_QUESTION_IDS,((resp.getQuestion().getAll_question_ids().toString())));
editor.apply();
}
progress.setVisibility(View.INVISIBLE);
It is here that I am stuck, as I am retrieving the array ok but I am unsure how to loop out the Array which is now stored in Shared Preferences.
When I place a toast to show me how the IDs are coming across, my toast confirms the data as [1,2,3]
The goal is to add a dynamic button and the individual ID, i.e button 1, button 2 etc every-time the loop is iterated.
I have tried the following:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
for (int i =0; i < questionNumber.length(); i++) {
try {
/*Dynamically create new Button which includes the question name
*/
AppCompatButton btn_question = new AppCompatButton(getActivity());
/*LayoutParams (int width, int height,float weight)
As LayoutParams is defaulted in px, I have called a method called dpToPX to make sure
the dynamically added EditText is the same size on all devices.
*/
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpToPx(280), dpToPx(45), 1);
btn_question.setBackgroundColor(Color.parseColor("#3B5998"));
btn_question.setTextColor(Color.WHITE);
// btn_question.setText(String.valueOf(x));
btn_question.setText("Question "+ pref.getString(Constants.All_QUESTION_IDS,""));
btn_question.setGravity(Gravity.CENTER);
//generate unique ID for each new EditText dynamically created
View.generateViewId();
//Log.d("TEST VALUE", "Question1 generated ID = " + btn_question.generateViewId());
params.setMargins(0, dpToPx(10), 0, dpToPx(10));
btn_question.setPadding(0, 0, 0, 0);
btn_question.setLayoutParams(params);
allEds.add(btn_question);
mLayout.addView(btn_question);
} catch (Exception e) {
Log.d(TAG, "Failed to create new edit text");
}
}
However the above is adding the value as it appears in the array e.g [1,2,3] which is obviously not what I want.
I have added a photo in case my explanation isn't clear. I want a button with 1 number added to it each time the loop iterates but I am unable to figure this out.
I have looked through lots of resource but cannot find an answer that is relevant to my problem, although, if there is, I am not familiar enough to recognise a similar issue.
If someone can offer some assistance, I would appreciate it!
When you call editor.putString(Constants.All_QUESTION_IDS,((SOMETHING.toString())));, what is actually stored depends on the implementation of the toString method in the type of SOMETHING (in this case String[]). So avoid doing that. Instead, since you're already using Gson or Jackson (or others), store the question_idsas JSON:
final String jsonIds = gson.toJson (resp.getQuestion().getAll_question_ids());
editor.putString(Constants.All_QUESTION_IDS, jsonIds);
Your actual stored value no longer depends on the implementation of something that you don't control (String[].toString). It is a valid JSON array and regardless of what tool/library you use to read it back, it's valid.
Now, to read back the stored data:
final String storedJson = pref.getString(Constants.All_QUESTION_IDS, null);
if (null == storedJson) {
// TODO: No question ids found
}
final String[] ids = gson.fromJson (storedJson, String[].class);
for (int i = 0; i < ids.length; i++) {
// make your buttons
}
This is a problem of saving and then reading out a List of items (in this case, String instances).
You've chosen to save the list by calling editor.putString() with a value of getAll_question_ids().toString(). That toString() call is going to return a string representation of your list, or, in other words, a String instance with the value [1, 2, 3]. At this point, you no longer have a List proper, but a String that looks like a list.
This is all technically fine, but it means you have to take this into account when you're trying to read out that list.
You've written this to read the list back out:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
Once this line executes, questionNumber will be a String instance with the value [1, 2, 3]. Again, this is fine, but now we come to the key point: we have to convert this String back into a List.
If you know for sure that the values in this list won't have commas in them, you can do it easily:
Trim the braces off the string using substring()
Create a String[] using split()
Convert your array to a list using Arrays.asList() (you could even skip this step since iterating over an array is just as easy as iterating over a list)
Put that together and you get:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
questionNumber = questionNumber.substring(1, questionNumber.length() - 1);
String[] array = questionNumber.split(", ");
List list = Arrays.asList(array);
At this point, you can iterate over your array or list:
for (String value : list) {
...
btn_question.setText("Question " + value);
...
}
I want to save multiple files to my database one by one.
And what happen here using my codes is this:
What I want to happen is like this one:
here is my code:
//Arraylist for getting the multiple brand code
ArrayList<String> content = new ArrayList<String>();
for (int j=0; j<checkSelected.length; j++) {
if(checkSelected[j]==true) {
String values = BrandListAdapter.mListItems.get(j);
//content.add(values);
Cursor rSubBrand = databaseHandler.getReport_SubBrandCode(values);
String SubBrandCode = rSubBrand.getString(rSubBrand.getColumnIndex(Constants.SUBBRAND_CODE));
content.add(SubBrandCode);
//Casting and conversion for SubBrand Code
String subBrand = content.toString();
//SAVE SUBBRAND
databaseHandler.SaveSubBrand(new Cons_iReport (ReportCode, subBrand));
Toast.makeText(getApplicationContext(), subBrand, Toast.LENGTH_LONG).show();
}
}
Mistakes:
content.add(SubBrandCode);
do you know how to remove the '[ ]' in the saved data? (e.g. [AC001]) All I want to save is the AC001 only.
Solutions:
Call clear() method of ArrayList before adding new values into it.
Its giving you [AC001] as you are subBrand by doing content.toString();. Don't convert it to string, instead use content.getString(position) and it will give you String value.
I want to put an int[] into an Android Intent. For various reasons I am getting a LinkedList<Integer>, so I tried (roughly) this:
LinkedList<Integer> myList = getIntegerList();
Intent intent = new Intent (context, class);
intent.putExtra("com.me.INTARRAY", myList.toArray());
This didn't work because toArray() was giving me an Object[]. I thought I could fix it by doing
intent.putExtra("com.me.INTARRAY", (Integer[]) myList.toArray(new Integer[myList.size()]) )
which does indeed produce an Integer[]; however, getting it out of the Intent STILL doesn't work.
Ultimately this isn't too hard to work around with a for loop so I ask more for curiosity than any other reason, but ... how do you get an Integer[] into an Intent extra as though it were an int[]?
I have not tested this thoroughly, but I believe it should work. You can try it.
Integer[] integerArray = {/*something */ };
intent.putExtra("com.me.INTARRAY", integerArray);
And then (not working)
Integer[] newArray = (Integer[]) getIntent().getSerializableExtra("com.me.INTARRAY");
EDIT:
Ahh.. After a little research and testing it seems the above is not possible. It is not possible because the compiler would have to iterate through every element to verify the cast. A solution(and I have testet it this time) would be to do this instead:
Object[] s = (Object[]) getIntent().getSerializableExtra("com.me.INTARRAY");
Integer[] newArray = Arrays.copyOf(s, s.length, Integer[].class);
I found the explanation here: Deserializing Arrays on Android
You can change the array to int[] and pass it as extras using putExtra(java.lang.String, int[]). On the other side you will need to get that extra using getIntArrayExtra.
Here is the code that works fine, caller first and receiver follows:
LinkedList<Integer> myList = getIntegerList();;
int iArray[] = new int[myList.size()];
for (Integer i : myList)
iArray[myList.indexOf(i)] = i;
Intent intent = new Intent();// create your actual intent
intent.putExtra("com.your.package.name.int", iArray);
startActivity(intent);
and the other side:
int array[] = getIntent().getExtras().getIntArray("com.your.package.name.int");
Another alternate, (which is better i guess) is to convert the LinkedList to Integer ArrayList. This works as follows, sender first receiver followed.
intent.putIntegerArrayListExtra("com.your.package.name.array", new ArrayList<Integer>(myList));
and on the other side:
ArrayList<Integer> array = getIntent().getExtras().getIntegerArrayList("com.your.package.name.array");
Hope this helps :)
I have tried all day to do this and haven't had any luck. I have an ArrayList with an Array of Coordinate types inside, and I want to pass this from one activity to another. I don't think this is possible through using Intent. So I am wondering what other option do I have? I want something simple..
I'd probably put the values in a database in your first activity and only pass some unique identifier on to the second activity so it can recreate the ArrayList on the other side. But if you want a quick solution, use the intent bundle and serialize/deserialize the coordinates yourself:
ArrayList<Coordinate> mCoords = new ArrayList<Coordinate>();
private void startOtherActivity()
{
int numCoords = mCoords.size();
Intent intent = new Intent();
intent.putExtra("coord_size", numCoords);
for (int i = 0; i < numCoords; i++)
{
Coordinate coord = mCoords.get(i);
intent.putExtra("coord_x_" + i, coord.getX());
intent.putExtra("coord_y_" + i, coord.getY());
}
//start other activity...
}
Then grab the values out of the bundle on the other side and regen the ArrayList.
Edit: Just realized you're talking about Coordinate[]s. Same principle still applies, just nest another for loop in there and keep track of each individual array's length as well.
Update: On the other side, you'd have something like
int len = intent.getIntegerExtra("coord_size", 0);
for(int i = 0; i < len; i++)
{
float x = intent.getFloatExtra("coord_x_" + i, 0.0);
float y = intent.getFloatExtra("coord_y_" + i, 0.0);
mCoords.add(new Coordinate(x, y));
}
You can have a singleton "Model" class, on which you can store the ArrayList object from one activity, and retrieve it from another.
Create Bundle and try to put the ArrayList. Then send the bundle in the intent.
You could write a ParcelableCoordinate class that implements Parcelable, and then have it convert the Coordinate objects into ParcelableCoordinate objects, put them in the intent, and then do the reverse on the other side.
InboxDetailActivity.java:
Intent i = new Intent(InboxDetailActivity.this,Compose.class);
Bundle b = new Bundle();
b.putString("To", ConstantData.inbox_from);
Log.d("From Value", ConstantData.inbox_from);
b.putString("Subject", "RE:" + ConstantData.inbox_subject);
Log.d("Subject Value", ConstantData.inbox_subject);
b.putString("FromId", ConstantData.inbox_fromid);
Log.d("From Id Value",ConstantData.inbox_fromid);
i.putExtras(b);
startActivity(i);
Compose.java:
Intent i = getIntent();
Bundle b = i.getExtras();
to = b.getString("To");
subject = b.getString("Subject");
toId = b.getString("FromId");
I am getting NullPointerException at to = b.getString("To");
Bundle b = i.getExtras();
getExtras() returns null.
Agree with John's answer adding possible solution.
What you are doing is create a bundle , insert values in this and then pass this bundle.
And than you just fetch all the values one by one using its keys.
I am working with bundles but I simply add desired values directly using putExtra method. And I haven't got any problem till date. I recommend you to use put extra and check whether it works or not.
I would like to know what makes you to apply this way for bundles? Have you just read it somewhere and started applying this method ? or you have got some options and after some consideration you found it better to apply this method OR your requirement states that. Because normally me and my peers doesn't use bundles and directly pass the extras. And that works for me every time.
using this instead of bundle
i.putString("To", ConstantData.inbox_from);
Log.d("From Value", ConstantData.inbox_from);
i.putString("Subject", "RE:" + ConstantData.inbox_subject);
Log.d("Subject Value", ConstantData.inbox_subject);
i.putString("FromId", ConstantData.inbox_fromid);
Log.d("From Id Value",ConstantData.inbox_fromid);
and in another class..
to = getIntent().getString("To");