Android Json tag into String - android

I use this code for reading a tag by a specific URL:
public static String ter(final String PRIVATE) {
JsonParser parser = new JsonParser();
try {
Object obj = parser.parse(new FileReader("my url string"));
JSONObject jsonObject = (JSONObject) obj;
String event = (String) jsonObject.get("EVENT");
return event;
} catch (Exception e) {
e.printStackTrace();
}
return PRIVATE;
}
Then I set my subTitle with PRIVATE in this way:
getActionBar().setSubtitle("test"+ter(PRIVATE));
But when I run my app, in subTitle I read only text "test" with text "null" and it doesn't read the tag of JSON. Anyone has any idea? Is my code wrong?

Because you may have not initializes your variable therefore it is pointing towards null values....
When ever we create object,either by calling that method or by initializing variable at declaration, we can avoid null pointer exception...
Please refer to this POST

You are setting the subtitle to PRIVATE, but if your parsing succeeds, you're returningevent. You're also sending PRIVATE into this function, for some reason.

Related

passing JSON object to a web service through AsyncTask

I am trying to pass a JSON object to a web service through Asynctask. I call a collectStatistics method in the MainActivity. This method collects some statistics of the mobile device and combines them together in a JSON object. JSON object is then passed to Asynctask.
JSONObject jsonProperties = new JSONObject();
try {
jsonProperties.put("_device" , _device);
jsonProperties.put("_model", _model);
jsonProperties.put("_product", _product);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonProperties.length() > 0)
{
//call to async class
//String.valueOf(jsonProperties)
//new SendJsonProperties().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, jsonProperties); //instead of execute
Toast.makeText(context,jsonProperties.toString(),Toast.LENGTH_LONG).show();
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new SendJsonProperties().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, jsonProperties);
Log.i("msg","calling asynctask");
} else {
new SendJsonProperties().execute(jsonProperties);
Log.i("msg","NOT calling asynctask");
}
}
The Asynctask receives JSON parameter
class SendJsonProperties extends AsyncTask <JSONObject,String,String>
I call a web service caller method in doInBackground
protected String doInBackground(JSONObject... params)
{
//(...) elippsis make the input array
Log.i("msg", "do in bkgnd");
WebServicesCaller webServicesCaller = new WebServicesCaller();
result = webServicesCaller.storeStatistics(params[0]);
return null;
}
But I get this error
java.lang.RuntimeException: Cannot serialize: {"_product":"ms013gxx","_model":"SM-G7102","_device":"ms013g"}
I cannot figure out the problem in serialization. Any help will be much appreciated. Thanks in advance.
You have to make Model POJO class of your JSONObject parameters.
Use this link to create POJO class according to JSON REsponse.
http://www.jsonschema2pojo.org/
I was trying to send a JSON object to a web method which takes a string parameter
public string storeStatistics(string jsonObj)
So I changed
jsonProp.setType(JSONObject.class);
request.addProperty(jsonProp, obj);
to
jsonProp.type = PropertyInfo.STRING_CLASS;
request.addProperty(jsonProp, obj.toString());

A value of a json str sometimes is a String, sometimes is a object, how could i use gson to parse it

Like the title , my json str sometimes like this:
{
"data": {
"changebaby": "no change",
"changemama": {
"mamacontext": "mama is a good mama",
"mamaico": "",
"mamatitle": "mama"
}
}
}
sometimes it like this:
{
"data": {
"changebaby": "no change",
"changemama": "no change"
}
}
as you see,the value of the "changebaby" key and the "changemama" key sometimes is a String, sometimes is a object, how should i parse it by gson? Could anybody help me?
Don't use the android api to parse the json string, need to use the gson lib of google to parse the json string, could anybody help me?
if(jsonObject.optJSONObject("changemama") != null)
{
JSONObject changemama=jsonObject.optJSONObject("changemama");
//Its JSON object, do appropriate operation
}
else if(jsonObject.optString("changemama") != null)
{
//Its string, do appropriate operation
}
if you have more number of possibilities like boolean or int or long, refer this
optJSONObject
Returns the value mapped by name if it exists and is a JSONObject, or
null otherwise.
Or go with the way lawrance has given : Determine whether JSON is a JSONObject or JSONArray
Try with this :
JSONObject changemama=jsonObject.optJSONObject("changemama");
if(changemama== null){
String str=jsonObject.optString("changemama");
}
Try this code.
JSONObject data;
try {
data = jsonObj.getJSONObject("changemama");
// do stuff
} catch (JSONException e) {
data = jsonObj.getString("changemama");
// do stuff
}
try this :
if(obj.has("changemama")){
if(obj.optString("changemama").length() > 0){}
else if(obj.optJSONObject("changemama").length() > 0){}}
To simplyfy android development, we can ask for the backend developers to change the Mobile API.The new API could returen the json string that cann't change the value.The value of all keys cann't sometimes be a string, sometimes a object.

use textview to display message when json response is null

In my JSON response I am get nothing in value and at that I want to print message using textview I am trying but its not showing nothing,can any one help?the response is looks like this
{"name":"Patel Monali","age":24,"location":"","mother_tounge":"","occupation":"","income":"","height":"","cast":"","marital_status":"","religion":"","gotra":"","manglik":"","rashi":"","education":"","eating":"","drink":"","smoke":"","about_me":"","profile_pic":"Imaege","user_status":"Accept","interest_id":1288}
and here is the code:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
...............
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
..............
uname.setText(user_name);
fdetail.setText(user_age+" years");
androidAQuery.id(ucover).image(user_pro, true, true);
}catch (JSONException e)
{
e.printStackTrace();
}
If I understand your question correctly here is what you need
if(user_name==null)
{
uname.setText("not willing to specify");
}
else
{
uname.setText(user_name);
}
If you need something more please update your question or tell me in comments.
.
Hope it help
All you have to do is check if the received string is null.
for example:
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation.length==0){
user_occupation="not willing to specify";//set your message here
}
OR
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation==null){
user_occupation="not willing to specify";//set your message here
}

Android: json's value is null

In my Android project when user log in, it will access our server and return to the client a json data, when user enter a wrong username or password, server will return the json data just like this:
{"d":{"__type":"FMService.LoginUser:#StarHope.FMS.Web.Pages.Service","Error":"worng","Permissions":null,"UserInfo":null}}
But when user enter the right username and password the return data "Error" is null.So the value of key "Error" is null. I try this to deal with it.
try
{
//when Error is not null
String error = (String) map.get("Error");
}
catch (Exception e)
{
//when Error is null
}
Is this OK? Anything wrong with this? Thang you.
parse your json string as use isNull to check if jsonobject content NULL or not before adding value to Map:
JSONObject jobject=new JSONObject("YOUR_JSON_STRING");
if(!jobject.isNull("d")){
JSONObject jobjd=jobject.getJSONObject("d");
String strtype,strError;
if(jobjd.isNull("__type")){
strtype=jobjd.getString("__type");
}
else{
//do some code here
strtype="is null";
}
if(jobjd.isNull("Error")){
strError=jobjd.getString("Error");
}
else{
//do some code here
strError="is null";
}
//.....same code here for Permissions and UserInfo
}
else{
//do some code here
}
You can use getString(). This method will raise a JSONException if the mapping is missing.
public String getString (String name)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary.
Throws JSONException if no such mapping exists.
You can also test if the mapping exists or is null using isNull()
Note that the Error field is inside the d object, not the root.

how to read attribute value in json using android

I want to read json attribute value, my json format like this
{"content":{"#attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}},
I want to read total_record's value from json attributes. How can I read ? Please help me
Thanks
John Rick
First of all check your JSON String.Change it to
{"content":{"#attributes" : { "start_limit" :"x","end_limit" : "x","total_records" : "x"}},"item":[{"category":"x","distance':"x"}]}} from
{"content":{"#attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}}
In which you left one closing curly brace before "item".
Now below is the code to get value of "total_records"
String jsonString = "{'content':{'#attributes' : { 'start_limit' :'x','end_limit' : 'x','total_records' : 'x'}},'item':[{'category':'x','distance':'x'}]}}";
public String getTotalRecords(String jsonString){
try {
JSONObject mainObject = new JSONObject(jsonString);
JSONObject contentObject = mainObject.getJSONObject("content");
JSONObject attributesObject = contentObject.getJSONObject("#attributes");
String totalRecords = attributesObject.getString("total_records");
Log.i("Total Records", totalRecords);
} catch (JSONException e) {
e.printStackTrace();
}
return totalRecords;
}
Hope you understand the problem.
Simply use JSONObject.
JSONObject obj = new JSONObject(src);
String totalRecs = obj.getString("total_records");
Not 100% sure it works, but it is a good example where to start.
Hope you've already given it a try before asking in SO. If not, here are a few urls (which I googled):
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/ and http://about-android.blogspot.com/2010/03/androind-json-parser.html

Categories

Resources