How to pass an arrayList between two intent in Android - java

I am new in Android and I have a question regarding intent. I want to pass an String ArrayList between two activities by using intent. I have tried this:
`
ArrayList<String> playerName = new ArrayList<>();
Intent intent = new Intent(this,Game.class);
intent.putStringArrayListExtra("Player",playerName);
startActivity(intent);`
Then I tried to receive my intent like that:
`
ArrayList<String> playerNameList= new ArrayList<>();
playerNameList = getIntent().getStringArrayListExtra("Player");
int listSize = playerNameList.size();
StringBuilder str = new StringBuilder(" ");
str.append(listSize);
textView.setText(str);
StringBuilder str1 = new StringBuilder(" ");
str1.append(playerNameList.get(2));
textView2.setText(str1);`
I can get the correct listSize; however I am not able to get any element of my arrayList. I always get the "index(0)" element. I would be really appreciated to any advice and help

you can easily to by using Gson
Intent intent = new Intent(this,Game.class);
intent.putExtra("Player",new Gson().toJson(playerName));
startActivity(intent);
at Game.class
ArrayList<String> playerNameList = playerNameList = new ArrayList<>();
String str = getIntent().getStringExtra("Player");
playerNameList = new Gson().fromJson(str,new TypeToken<ArrayList< String >>(){}.getType());

Check your code to add data to ArrayList playerName. The code to putStringArrayListExtra to Intent and getStringArrayListExtra from Intent is correct.

Related

Speech to text app replaces old text with new

The app overwrites the old text with the new one but that's not the purpose. I want the new text to retain old text in addition to new, like turning old and new into strings and then combining them?
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
resultText.setText(matches.get(0));
}
});
So you want to append the results to the TextView ?
That's easy:
resultText.append(matches.get(0));
With space:
resultText.append(" " + matches.get(0));
Another way:
resultText.setText(resultText.getText() + " " + matches.get(0));

Convert JSON String to Arraylist for Spinner

I got my JSON string from my server which contains this values:
{"server_response":[{"violation":"Driving with No Helmet"},{"violation":"Try"}]}
What I'm trying to do is convert this JSON string into String Array or Arraylist
with the values of Driving with no Helmet and Try and use it as options on an Autocomplete Textview. But I cant seem to convert them correctly. Any help or tips on what I should do? Currently I am getting the JSON String from another activity and passing it to the activity where it should be used using this:
String json_string2 = getIntent().getExtras().getString("json_data");
Anyone has time I'm willing to learn. :) Thanks
PS: Managed to get it working. #Suhafer's answer is perfect. Thanks to everyone for the warm help! :)
I think first, you need to parse the json to get the list of string that you want:
String json_string2 = getIntent().getExtras().getString("json_data");
List<String> lStringList = new ArrayList<>();
try {
JSONObject lJSONObject = new JSONObject(json_string2);
JSONArray lJSONArray = lJSONObject.getJSONArray("server_response");
for (int i = 0; i < lJSONArray.length(); i++)
{
lStringList.add(
lJSONArray.getJSONObject(i).getString("violation"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
Then, you need to set that list to your adapter:
ArrayAdapter<String> yourListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lStringList);
Next, implement the adapter to your AutoCompleteTextView.
lAutoCompleteTextView.setAdapter(lStringArrayAdapter);
Hope, that helps you.
Reading your comment I think you want this list to populate on an AutoCompleteTextView. I have written thoroughly what to do this will surely help If you follow these steps carefully.
First get the response and convert it to List<String> list = new ArrayList<>() format, Create a ArrayAdapter of this list by
yourListAdapter = new ArrayAdapter<String>(YourActivity.this,
android.R.layout.simple_list_item_1, list);
After this set your yourAutoCompleteTextBoxName.setAdapter(yourListAdapter);
In your Activity initialize this:
yourAutoCompleteTextBoxName.setOnEditorActionList(...){...}
also if you want your list to be clicked from AutoComplete TextView then do this:
yourAutoCompleteTextBoxName.setOnItemClickListener(...){...}
You can do this as below by using jettinson.jar
try {
String data = "{\"server_response\":[{\"violation\":\"Driving with No Helmet\"},{\"violation\":\"Try\"}]}";
JSONObject jsonObject = new JSONObject(data);
JSONArray temp = jsonObject.getJSONArray("server_response");
int length = temp.length();
if (length > 0) {
String[] recipients = new String[length];
for (int i = 0; i < length; i++) {
JSONObject nObject = new JSONObject(temp.getString(i));
recipients[i] = nObject.getString("violation");
}
}
} catch (JSONException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
For getting your list of strings:
You can use Jackson's ObjectMapper class.
public class Data {
String violation;
...
}
List<Data> violations = objectMapper.readValue(json, new TypeReference<List<Data>>(){});
Below: "array" will have all the violations. (You will require some try / catch to surround with). Have a good day!
JSONObject json = new JSONObject(json_string2);
JSONArray violations = json.getJSONArray("server_response");
String[] array = new String[violations.length()];
for(int i = 0; i < violations.length(); i++) {
JSONObject violation = new JSONObject(violations.getString(i));
array[i] = violation.getString("violation");
}
You can use Gson library https://github.com/google/gson
Generate Plain Old Java Objects from JSON or JSON-Schema http://www.jsonschema2pojo.org/
YourJsonData jsonObject;
String json_string2 = getIntent().getExtras().getString("json_data");
Gson gson = new Gson();
jsonObject = gson.fromJson(json_string2, YourJsonData.class);
from jsonObject you can get your list i.e server_response array list.

How to convert an ArrayList of byte[] to an array of Integer in Android?

I'm trying to convert an ArrayList<byte[]> listByte to an Integer[] arrInteger. I'm getting the listByteof pictues from a server through an object. My goal is to get this Array of Integer(pictures) to later use it in a ListView(arrayAdapter = new MyClass(MyActivity.this, stringArr, arrInteger);.
I tried like this:
ArrayList<Integer> integerList = new ArrayList<>();
for (int i = 0; i < objectList.size(); i++) {
integerList.add(ByteBuffer.wrap(objectList.get(i).getPicture()).getInt(i));
/*integerList.add(new BigInteger(objectList.get(i).getImage()).intValue());*/ //I tried this too
}
and to an Array of Integer, like this:
Integer[] arrInteger = new Integer[integerList.size()];
arrInteger = integerList.toArray(arrInteger);
When i run the app, the ListViewis showing without pictures. So I used debug and I found that my arrInteger = null!. How do I convert correctly?
Decode back to Bitmap
ArrayList<Bitmap> imgs = new ArrayList<Bitmap>();
for(byte[] array: listByte)
{
Bitmap bm = BitmapFactory.decodeByteArray(array, 0, array.length); //use android built-in functions
imgs.add(bm);
}

Check if elements in a check list are ticked and send those via email?

Intent next = new Intent(Intent.ACTION_SENDTO);
next.setData(Uri.parse("mailto:zuron7#gmail.com"));
next.putExtra(Intent.EXTRA_SUBJECT, "Attendance");
String message = "";
Resources r = getResources();
String name = getPackageName();
int[] ids = new int[3];
for(int i =0; i<3;i++){
String x = "check"+i;
ids[i]= r.getIdentifier(x,"id", name);
}
for(int i = 0; i<3;i++){
CheckBox checkbox = (CheckBox) findViewById(ids[i]);
if(checkbox.isChecked()){
message=message+getResources().getString(R.string.Swag1);
}
}
next.putExtra(Intent.EXTRA_TEXT,message);
if (next.resolveActivity(getPackageManager()) != null)
startActivity(next);
When I run the app on my phone and hit the button which launches this method, it stops unexpectedly. I'm not really sure where the problem is. I basically want to take attendance for a group of students and send the names of those absent to the coordinator.
Maybe this will solve your problem: ACTION_SENDTO for sending an email
Basically you should try to pass your subject and message via the URI in setData.

append a Name Value pair to other one

here is the code of the calling method -
NameValuePair[] data = {
new NameValuePair("first_name", firstName),
new NameValuePair("last_name", lastName),
new NameValuePair("email", email),
new NameValuePair("company", organization),
new NameValuePair("phone", phone)
};
SalesForceFormSubmissionUtil.submitForm(data,CONTACT_FOR_TYPE);
In the called method -
public static void submitForm(NameValuePair[] givendata, String contactType) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(Constants.SALESFORCE_URL);
NameValuePair[] data = {
new NameValuePair("oid", Constants.SALESFORCE_OID),
new NameValuePair(Constants.SALESFORCE_CAMPAIGN_ID, contactType)
};
post.setRequestBody(data);
i want to add both the givendata & data and send it as a post request. Can you guys suggest me how to append both.
If you just want to combine the two arrays you can create a third array (combinedData) with a size of givenData.length + data.length, then you'll have to copy the elements from your source arrays.
Though, there are plenty of other methods to solve this, as an example; below is an implementation using a ArrayList as a middle-man/helper.
String[] A1 = {"hello","world"};
String[] A2 = {"I","am","bored"};
...
ArrayList<String> temp = new ArrayList<String> (A1.length + A2.length);
temp.addAll (Arrays.asList (A1));
temp.addAll (Arrays.asList (A2));
String[] A3 = temp.toArray (new String[temp.size ()]);
...
for (int i=0; i < A3.length; ++i)
System.out.println (A3[i]);
output
hello
world
I
am
bored
public static void submitForm(NameValuePair[] givendata, String contactType) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(Constants.SALESFORCE_URL);
post.setRequestBody(givendata);
post.addParameters({
new NameValuePair("oid", Constants.SALESFORCE_OID),
new NameValuePair(Constants.SALESFORCE_CAMPAIGN_ID, contactType)
});
...

Categories

Resources