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.
Related
I have a edit text in login page, and I have a condition for edit text MaxLength="12". In my JSON response I have a string with 15 letters (or Nor's), I need to check (or compare) up to 12 letters(or Nor's) from it, If both letters are same up to 12 Letter(or Nor's), then I have to enter into my app.
{
ID No="123456789012.00"
}
Hello Suresh Use String#substring
try {
JSONObject jObj = new JSONObject("{\"id_no\":\"123456789012.00\"}");
String strJNumber = jObj.optString("id_no").substring(0,11);
String strENumber = etNumber.getText().toString();
if(strENumber.equals(strJNumber)){
// TODO: true both are same
}else {
// TODO: true both are not same
}
} catch (JSONException e) {
e.printStackTrace();
}
You can use "substring" and "equals" methods:
(I assume your strings' names are editTextString and jsonString)
First, get substring of first 12 chars from json string:
String jsonFirst12Chars = jsonString.substring(0,12);
Then use equals method to compare them:
if(editTextString.equals(jsonFirst12Chars)) {
// They are same, do something
} else {
// They are not same..
}
{"data":
{
"userId":"+919923911289",
"inTime":"2016-07-25 12:09:47+05:30",
"outTime":"0",
"totalTime":"0",
"type":"attendance"
}
}
And the second json response is
{"data":"please try again..."}
I am using retrofit to get the response . For the first json i have created the Gson model.But , when the response is in the second json format i didn't have any response model for it.
I am displaying the data using the GsonModel for the first json response.
And if there is second type of response what should i do here.Will i use the TypeToken here or something else.
And it also giving me the parsing exception wich i understand.But , i didn't know what i have to do.
Create a another model
class ErrorModel{
String data;
}
and in your main method:
try{
GsonModel model = gson.fromJson(response,GsonModel.class);
// ...
}catch(JsonSyntaxException e){
ErrorModel model = gson.fromJson(response,ErrorModel.class);
// show error
}
if (data.equalsIgnoreCase("please try again...") {
//show error
} else {
//do your work with response
}
if(data.has("userId") && !data.isNull("userId") ){
String user_Id=data.getString("userId");
}else{
////show message "please try again..." here....
}
{"data":
{
"userId":"+919923911289",
"inTime":"2016-07-25 12:09:47+05:30",
"outTime":"0",
"totalTime":"0",
"type":"attendance"
}
}
And the second json response is
{"data":"please try again..."}
I am using retrofit to get the response . For the first json i have created the Gson model.But , when the response is in the second json format i didn't have any response model for it.
I am displaying the data using the GsonModel for the first json response.
And if there is second type of response what should i do here.Will i use the TypeToken here or something else.
And it also giving me the parsing exception wich i understand.But , i didn't know what i have to do.
Create a another model
class ErrorModel{
String data;
}
and in your main method:
try{
GsonModel model = gson.fromJson(response,GsonModel.class);
// ...
}catch(JsonSyntaxException e){
ErrorModel model = gson.fromJson(response,ErrorModel.class);
// show error
}
if (data.equalsIgnoreCase("please try again...") {
//show error
} else {
//do your work with response
}
if(data.has("userId") && !data.isNull("userId") ){
String user_Id=data.getString("userId");
}else{
////show message "please try again..." here....
}
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.
I am trying to retrieve a new column called "address" I created in Parse User in my android app. But it returns me nullPointerException error and returns me nothing although I filled the address in the table.
This link only shows the way to store your custom field in the user table but I need to retrieve what I stored there.
This is my code:
ParseUser pUser = ParseUser.getCurrentUser();
userAddress.setText(pUser.getString("address").toString());
I tried get("address") as well but still it returns me nothing. Is there something I'm missing here?
Alright, I found the answer on my own. It turns out that Parse caches the ParseUser.getCurrentUser() object locally and the reason I wasn't able to get the data from server was because I changed the data on server and the client cache wasn't updated.
I was able to fix this by fetching the ParseUser object from the server:
ParseUser.getCurrentUser().fetchInBackground();
and then after the object is retrieved from the server I was able to get the address field on my client.
You need to call it using a Query, then display it in a textView/editText. Try the following:
final ParseQuery<ParseObject> address = ParseQuery.getQuery("//Class Name");
address.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject reqAdd, ParseException e) {
if (address != null) {
Log.d("quizOne", "Got it");
//Retrieve Age
String //CreateNewString = reqAdd.getString("//Column name");
TextView //textView Name = (TextView) findViewById(R.id.//textView ID);
//textViewName.setText(//StringName);
Toast.makeText(getApplicationContext(),
"Successfully Recieved Address",
Toast.LENGTH_LONG).show();
} else {
Log.d("//EnterName", "//Enter Error Message");
Toast.makeText(getApplicationContext(),
"Can't receive address", Toast.LENGTH_LONG)
.show();
}
}
});
Short answer: that user probably just doesn't have an address set.
Long answer: your code snippet will throw exceptions often, and you should expect and handle those, or use tests to avoid throwing them.
Read this page: http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException
Key example/excerpt:
Object obj = null;
obj.toString(); // This statement will throw a NullPointerExcept
So pUser.getString("address") appears correct. But calling .toString() on the result requires you to be try/catching the exception. Maybe do
ParseUser pUser = ParseUser.getCurrentUser();
if (pUser.getString("address") != null) {
userAddress.setText(pUser.getString("address"));
}
BTW, I believe the error is "nullPointerException" fyi! :)