use textview to display message when json response is null - android

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
}

Related

check playerSSign fail

When verifying the signature, the background server displays {"rtnCode":-1,"errMsg":"check playerSSign fail"}
The data provided by the client is
if(huaweiid != null){
PlayersClient player = Games.getPlayersClient(this, huaweiid);
player.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
#Override
public void onSuccess(Player player) {
String ts = player.getSignTs();
String playerId = player.getPlayerId();
int playerLevel = player.getLevel();
String playerSign = player.getPlayerSign();
//String displayName = player.getDisplayName();
//Uri hiResImageUri = player.getHiResImageUri();
//Uri iconImageUri = player.getIconImageUri();
JSONObject jo = new JSONObject();
try {
jo.put("signTs", ts);
jo.put("playerId", playerId);
jo.put("playerLevel", playerLevel);
jo.put("playerSign", playerSign);
EditText ed = findViewById(R.id.editText);
ed.setText(jo.toString());
Log.i("huawei user info", jo.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("huawei user info", Objects.requireNonNull(e.getMessage()));
}
}
});
}
Use the preceding four data items and the following description document:
https://developer.huawei.com/consumer/cn/doc/HMSCore-References-V5/verify-login-signature-0000001050123503-V5
An error always occurs during the verification in the background.
{"rtnCode":-1,"errMsg":"check playerSSign fail"}
appId/cpid is obtained from agconnect-services.json and agconnect-services.json is downloaded from the background.
what’s the reason?
The following table describes the typical setting errors of the input parameters. Please verify the parameter settings.
https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/faq-check-login-0000001050746133-V5

Android Json tag into String

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.

JSON parsing not encoding string with underscore in Android using Volley

I am trying to encode a string which contains a URL, I have a strange issue where the complete string is not being returned, I have noticed that it may be related to the underscore, I have tried a few solution where I replace the underscore, but haven't had much luck with that solution. Below is the JSON.
[{"id":"1","source":"BBC WORLD NEWS",
"time_date":"Sat, 25 Oct 2014 10:49:13",
"title":"Iran hangs woman despite campaign","description":"Iran defies an international campaign and hangs a woman who killed a man she said was trying to sexually abuse her.",
"link":"http:\/\/www.bbc.co.uk\/news\/world-middle-east-29769468#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa",
"image":"http:\/\/news.bbcimg.co.uk\/media\/images\/78529000\/jpg\/_78529517_78528720.jpg"},
I am trying to retrieve the image element from the json. The following is what I receive from my parsing.
http://news.bbcimg.co.uk/media/images/78526000/jpg
I am using this code at the moment:
String imageurl = feed.getImage();
try {
imageurl = URLDecoder.decode(imageurl, "UTF-8");
System.out.println("---------------------------"+imageurl);
imageurl.replace("_", "%5f");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
getimage method:
private String image;
public String getImage() {
return image;
}
private void requestNewsData(String uri) {
RestAdapter api = new RestAdapter.Builder().setEndpoint(ENDPOINT).build();
NewsAPI restapi = api.create(NewsAPI.class);
restapi.news(new Callback<List<RssObject>>() {
public void success(final List<RssObject> newsFeed, Response response) {
Log.v("nas", "the webservice success " + response.getReason());
for (int i = 0; i < newsFeed.size(); i++) {
System.out.println(newsFeed.get(i).description);
newsList.add(newsFeed.get(i).description);
FeederModel feed = new FeederModel();
feed.setSource(newsFeed.get(i).source);
feed.setImage(newsFeed.get(i).image); // adding setimage
}
}
The retrieved string is missing the final part of the url.
Any suggestion would be gratefully appreciated. Thanks.

Running an FQL query while parsing a Graph API result gives arrayindexoutofbound exception

After making a call to the "me/home" Graph API, while parsing the JSON result, I am trying to make another query using FQL. The FQL query problem was solved in my earlier question.
The background of my implementation is: I am using a BaseAdapter and from the main activity, I am sending the data parsed from JSON using multiple ArrayLists. If I am not making the FQL query, everything is peachy. But when I introduce the FQL query, the query is always run after the adapter has been set to the ListView. This keeps causing the arrayindexoutofbound exception.
This is the code that I am using including the additional FQL query while parsing the JSON result. To keep the code short, I will include the relevant part as the rest works just fine. If more is needed, however, I will put that up too.
// GET THE POST'S LIKES COUNT
if (json_data.has("likes")) {
JSONObject feedLikes = json_data.optJSONObject("likes");
String countLikes = feedLikes.getString("count");
postLikesCountArrayList.add(countLikes);
// TEST STARTS
Runnable run = new Runnable() {
#Override
public void run() {
graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'"
+ finalThreadID + "\'";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
Utility.mAsyncRunner.request(null, params, new LikesListener());
}
};
TestNewsFeeds.this.runOnUiThread(run);
// TEST ENDS
} else {
String countLikes = "0";
postLikesCountArrayList.add(countLikes);
}
And this is the code for the LikesListener class. It is a private class declared in the same activity:
private class LikesListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
// Log.e("response", response);
try {
JSONArray JALikes = new JSONArray(response);
// Log.v("JALikes", JALikes.toString());
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
// Log.e("JOTemp", JOTemp.toString());
if (JOTemp.has("likes")) {
JSONObject optJson = JOTemp.optJSONObject("likes");
// Log.v("optJson", optJson.toString());
if (optJson.has("user_likes")) {
String getUserLikeStatus = optJson.getString("user_likes");
Log.e("getUserLikeStatus", getUserLikeStatus);
arrayLikeStatus.add(getUserLikeStatus);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have figured out using debugging that the cause of the crash is the setAdapter being called before the second query completes. I see the log's being added to logcat after the crash has occured.
Any help on a solution for this is appreciated
UPDATE: Figured out the solution almost when I was about to give up.
SOLUTION
So instead of calling the BaseRequestListener as used in the question, this modification had to be made.
try {
graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'"
+ finalThreadID + "\'";
// Log.d("finalThreadID", finalThreadID);
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
// Utility.mAsyncRunner.request(null, params, new LikesListener());
String fqlResponse = Utility.mFacebook.request(params);
// Log.e("fqlResponse", fqlResponse);
JSONArray JALikes = new JSONArray(fqlResponse);
// Log.v("JALikes", JALikes.toString());
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
// Log.e("JOTemp", JOTemp.toString());
if (JOTemp.has("likes")) {
JSONObject optJson = JOTemp.optJSONObject("likes");
// Log.v("optJson", optJson.toString());
if (optJson.has("user_likes")) {
String getUserLikeStatus = optJson.getString("user_likes");
// Log.e("getUserLikeStatus", getUserLikeStatus);
arrayLikeStatus.add(getUserLikeStatus);
// Log.d("arrayLikeStatus", arrayLikeStatus.toString());
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
Hope this helps someone save time if they are stuck like I was.

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