How to Get JSON String to Int then to Arg Bundle? - android

I'm trying to pass an Int value pulled from a JSON String to reduce code redundancy.
Within my JSON file, I have a string value in "resFile". I store this string into TAG_RES_FILE where I want to pass it in a Bundle as an Int.
If you look in my code, you will see comment //TRY #1//. This works as expected but I need that Int to come from a variable that stores my TAG_RES_FILE. At comment //TRY #2// is just an example to what I want to function - obviously it does not. In the next line, I tried converting the tag string to a Int but this gives a runtime error of:
java.lang.NumberFormatException: Invalid int: "resFile"
I have even tried putting 0x7f060000 (from R.java) into the JSON String.
So my question is: How do I accomplish this? Am I on the right track or should I go about it a completely different way?
Thnx for your help and input - please show code examples in your answer.
JSON String Snippit:
[
{
"_id": "1",
"label": "A Lable",
"title": "Some Title",
"description": "Bla, bla, bla",
"containerID": "Some container id",
"isRawRes": "boolean value here",
"resFile": "R.raw.advisory_circulators_sort_list"
}, {. . .
]
In my HashMap:
// Parse the string to a JSON object
for (int i = 0; i < json.length(); i++) {
JSONObject json_data = json.getJSONObject(i);
// Storing each json item in variable
String id = json_data.getString(TAG_ID);
String label = json_data.getString(TAG_LABEL);
String title = json_data.getString(TAG_TITLE);
String description = json_data.getString(TAG_DISCR);
String containerID = json_data.getString(TAG_FRAG_ID);
String isRawRes = json_data.getString(TAG_IS_RAW_RES);
String resFile = json_data.getString(TAG_RES_FILE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LABEL, label);
map.put(TAG_TITLE, title);
map.put(TAG_DISCR, description);
map.put(TAG_FRAG_ID, containerID);
map.put(TAG_IS_RAW_RES, isRawRes);
map.put(TAG_RES_FILE, resFile);
// adding HashList to ArrayList
mList.add(map);
}
In my ListViews setOnItemClickListener:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
. . .
final Bundle args = new Bundle();
//TRY #1//int rawRes = R.raw.advisory_circulators_sort_list; <--I NEED TO GET THIS IN FROM MY TAG!!
//TRY #2//int rawRes = TAG_RES_FILE; <-- TO SOMETHING LIKE THIS!!
int passResFile = Integer.parseInt(TAG_RES_FILE);//<--THIS GIVES A NPE!!
args.putInt("KEY_RES_FILE", passResFile);
bolean isRawRes = true;
args.putBoolean("KEY_IS_RAW_RES", isRawRes);
// Delayed to improve animations
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ListViewFragment lvf = new ListViewFragment();
lcFT.replace(R.id.listContainer, lvf).commit();
lvf.setArguments(args);
}
}, 300);
}

Instead, just store advisory_circulators_sort_list as opposed to R.raw.advisory_circulators_sort_list. Then, to get the Integer identifier, use this method:
int passResFile = getResources().getIdentifier( resFile, "raw", getPackageName() );

Related

Parsing Single JSON object in Android Studio

I have a JSON Object I want to parse at this URL https://api.adviceslip.com/advice with this content:
{"slip": { "id": 137, "advice": "You're not that important; it's what you do that counts."}}
I have written this code in Android Studio but it does not seem to work.
String jsonString = handler.httpServiceCall(url);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject slip = jsonObject.getJSONObject("slip");
String id = slip.getString("id");
Log.d("slip id:", id);
String advice = slip.getString("advice");
Log.d("slip adv:", advice);
HashMap<String, String> map = new HashMap<>();
map.put("id", id);
map.put("advice", advice);
adviceSlip.setText(map.get("advice"));
}
Any help would be appreciated :)
One problem is that you are trying to get a String on an Int object, and perhaps this is one of your errors, please change your
splip.getString("id");
by
slip.getInt("id);
Another one is that you are creating a HashMap<String,String> but the id you getting from the json is an Int and perhaps you should change it to use HashMap<Int,String>
You can get the value from the jsonobject and simple set that value on the textview.
String jsonString = handler.httpServiceCall(url);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject slip = jsonObject.getJSONObject("slip");
String id = slip.getString("id");
Log.d("slip id:", id);
String advice = slip.getString("advice");
adviceSlip.setText(advice);
}

How to edit an item in a json file?

I have this structure that is generated by my application and I read in a listView:
[{
"phone": "202020",
"name": "Jhon",
"id": 10,
"age": 20
},
{
"phone": "303030",
"name": "Rose",
"id": 11,
"age": 22
}]
When I select an item in the listview, I open a screen form passing the values ​​of the clicked item.
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String age = ((TextView) view.findViewById(R.id.age)).getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_AGGE, age);
in.putExtra(TAG_PHONE, phone);
startActivity(in);
}
});
This screen opens when you click on the item is a form where I put the values ​​passed from the previous screen fields.
My question is: When you click save in this form, I have to get the new values ​​and update the json file. How to do this?
Ex: I want to change the record ID 22, which is the user Rose.
ADD MORE INFORMATION:
I already use the Gson to generate items.
Code to generate:
btnSalvar.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
gson = new GsonBuilder().setPrettyPrinting().create();
final File file = new File(Environment.getExternalStorageDirectory() + "/download/ibbca/auditar.json");
// to check if file exists before before it maybe will be created
if (file.exists())
fileExists = true;
try{
// create file or get access to file
raf = new RandomAccessFile(file, "rw");
if (fileExists) // start new file as an array
raf.seek(file.length() - 1);
else { // start writing inside the bracket
raf.writeBytes("[");
raf.seek(file.length());
}
UserTestJson obj1 = new UserTestJson();
obj1.setId(10);
obj1.setName("Jhon");
obj1.setAge(20);
obj1.setPhone("202020");
toJson(obj1);
// end file
raf.writeBytes("]");
raf.close();
}catch(FileNotFoundException f){
f.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
And the Class UserTestJson, i created with get and seters for each variable.
The Simplest way is, Just go to that json Object and set the desired value for the key.
JSONArray arr = new JSONArray(str);
for(int i = 0; i < arr.length(); i++){
JSONObject jsonObj = (JSONObject)arr.get(i); // get the josn object
if(jsonObj.getString("name").equals("Rose")){ // compare for the key-value
((JSONObject)arr.get(i)).put("id", 22); // put the new value for the key
}
textview.setText(arr.toString());// display and verify your Json with updated value
}
It's perhaps a good time to switch to an ArrayAdapter.
I recommend to transfer the JSON into a custom model bean first:
class Person {
long id;
String phone, name, age;
}
Then you can use an JSON parser library like gson to parse the array into a List<Person> and use this array to drive your list. (See Gson help with parse array - works without array but won't with array) for an example on the parsing.
Finally, when you are ready to write back the data, simply re-generate the JSON from the array. This question got an example for that: Trouble with Gson serializing an ArrayList of POJO's
Pros:
Once your JSON data model changes, only a small change in your model is needed to read the new format.
You can use standard Java tools like ArrayList and POJOs
Cons:
You will need to import GSON or equivalent into your project.
Also check this question: How to parse JSON in Android
I cant find a direct way to do so.
But you can use this function to solve the problem first. See if there is other solution
private JSONObject setJSONVal(JSONObject jsonObject, String index, String value) throws JSONException{
String jsonString = jsonObject.toString().trim();
jsonString = jsonString.replace("\"" + index + "\":\"" + jsonObject.getString(index) + "\"", "\"" + index + "\":\"" + value + "\"");
return new JSONObject(jsonString);
}

Retrieve value of a spinner after validation

I have a problem to retrieve the value of a spinner when I want to validate my insertion.
here is how I fill my spinner :
ArrayList<HashMap<String, String>> myArrayList;
myArrayList= new ArrayList<HashMap<String, String>>();
for (int i = 0; i < studentList.length(); i++) {
JSONObject c = studentList.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
myArrayList.add(map);
}
and after :
SpinnerAdapter studentAdapter = new SimpleAdapter(
MyActivity.this, myArrayList,
R.layout.student, new String[] { "id", "name"},
new int[] { R.id.id, R.id.name });
mySpinner.setAdapter(studentAdapter);
When I click on my button "OK", and I get the value of the spinner with
mySpinner.getSelectedItem().toString();
I get :
{id=2, name=Smith}
But i'm sure there is another method to retrieve only the name, but how? By getting the adapter with the spinner? It is my problem...
Thank you
The object the Spinner is giving you is a HashMap. Cast it as such, and then extract the value the way you normally would:
String studentName = ((HashMap)mySpinner.getSelectedItem()).get("name");
Another option: rather than using ArrayList<HashMap> to populate your Spinner, you may want to do it with ArrayList<Student> (assuming Student is a class you already have at your disposal). You can then cast the currently-selected object to Student and use it as you please:
String studentName = ((Student)mySpinner.getSelectedItem()).name;
i'm sure there is another method to retrieve only the name, but how?
You can use an OnItemSelectedListener which will always have the user's current choice:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
// Do with name as you please
}
Or you could use the same technique with getSelectedView() to only get the name after your validation.
String data="{id=2, name=Smith}";//you retrieved
String array[]=data.split("name=");//split in values of '**id=2,** ' and '**Smith**'
String name=array[array.length-1]; //take last value
You will have 'Smith' in name variable. Not prefered but if no choice then use it

How to use Dictionary (like iphone NSDictionary) in android?

I have worked in soap message, and to parse the value from Webservice, the values are stored in ArrayList.
Example:
values are Employee name (Siva) and Employee id (3433fd), these two values are stored in arraylist, but I want to stored in Dictionary, How?
you can use HashMap like this
Map <String,String> map = new HashMap<String,String>();
//add items
map.put("3433fd","Siva");
//get items
String employeeName =(String) map.get("3433fd");
You can use Bundle.
as it offers String to various types of Mapping.
Bundle b = new Bundle();
b.putInt("identifier", 121);
b.putString("identifier", "Any String");
b.putStringArray("identifier", stringArray);
int i = b.getInt("identifier");
...
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText textview = (EditText) findViewById(R.id.editTextHash);
EditText textviewNew = (EditText) findViewById(R.id.editTextHash2);
Map<String, String> map = new HashMap<String,String>();
map.put("iOS", "100");
map.put("Android", "101");
map.put("Java", "102");
map.put(".Net", "103");
String TextString = "";
// Set<E> keys = map.keySet();
Set keys = map.keySet();
System.out.println("keys "+keys);
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
System.out.println("key "+key);
String value = (String) map.get(key);
System.out.println("value "+value);
textview.append(key + " = " + value);
TextString+=(key + " = " + value);
}
//textviewNew.setText(TextString);
// Iterator iterator = map.keySet().iterator();
//
// while (iterator.hasNext())
// {
// String object = (String) iterator.next();
// textview.setText(object);
// }
//
// //textview.setText(map.get("Siva"));
//
// System.out.println(map);
}
}
A Dictionary is an abstract class that maps keys to values and there is Dictionary Class in android refer link you can find a note at Class Overview
Do not use this class since it is obsolete. Please use the Map
interface for new implementations.
An attempt to insert either a null key or a null value to a dictionary will result to a NullPointerException,but you can use Map interface,it provides the exact same functionality of a dictionary.you can use it as bellow
//put values
Map Message = new HashMap();
Message.put("title", "Test message");
Message.put("description", "message description");
Message.put("email", "email#gmail.com");
//get values
Log.d("get Message","Message title -"+Message.get("title"));
you can also use A custom class as below
public class MessageObject {
String title;
String description;
String email;
}
you can use Getters and Setters to get and put values,not needed to remember the key names every time you may get some other advantages by this way.

json android: parsing json

I have a json :
[ {user:"John",s:"Ldh",e:"usa"},{user:"Paul",s:"bukit panjang ",e:"FedExForum - Memphis"},{user:"ross",s:"bukit panjang ",e:"FedExForum - Memphis "}]
I am parsing this with the following code to retrieve all the values of "user" ..
public class ListViewAndroidActivity extends ListActivity {
private String newString, user;
ArrayList<String> results = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestServiceActivity test = new TestServiceActivity(); //This returns json from the server
newString = test.readPooledFeed(); // returned json in string format
JSONArray rootArray = new JSONArray(newString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject obj = rootArray.getJSONObject(i);
user = obj.optString("user");
results.add(user);
}
}
This gives me no error.. but nothing is shown on the screen .. kindly help!
optString : Get an optional string associated with a key.
I don't see the key u in your JSON object, shouldn't it be user = obj.optString("user");
JSON formatting
Your JSON data is not valid, it's valid as javascript, but not as JSON.
All properties should be quoted in JSON:
[
{ "user": "John", "s": "Ldh", "e": "usa"},
{ "user":"Paul", "s":"bukit panjang ", "e": "FedExForum - Memphis" },
{ "user": "ross", "s":"bukit panjang ", "e":"FedExForum - Memphis "}
]
Indentation is not needed, I just did it to make it clearer.
Missing field
Your parser seems to ignore that your input data is invalid. Other problem could be as others mentioned you're requesting the u property at user = obj.optString("u"); which does not exists.

Categories

Resources