Error of sendUserActionEvent() mView == null is coming - json

I am parsing a json response file got through the Volley Request Libraries and populating List by the json array.
public void getAllContacts() {
queue = Volley.newRequestQueue(getApplicationContext());
String tag_json_obj = "json_obj_req";
String url = "http://52.25.169.219:3000/users";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONArray cast = response.getJSONArray("users");
for (int i=0; i<cast.length(); i++)
{
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
String phoneno = actor.getString("contact");
name1.add(name);
phno1.add(phoneno);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
VolleyLog.d("Tag", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Error in fetching contacts", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjReq);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.show();
}
But getting volley error and toast as error in fetching contacts.
My json file format is
{"users":"[{\"id\":1,\"name\":\"test_name\",\"contact\":\"23456543\",\"gender\":\"F\",\"age\":234,\"city\":\"delhi\",\"state\":\"india\",\"created_at\":\"2015-07-19T17:58:42.000Z\",\"updated_at\":\"2015-07-19T17:58:42.000Z\",\"district\":\"test_district\"},{\"id\":2,\"name\":\"test_name\",\"contact\":\"23456543\",\"gender\":\"F\",\"age\":234,\"city\":\"delhi\",\"state\":\"india\",\"created_at\":\"2015-07-19T17:58:42.000Z\",\"updated_at\":\"2015-07-19T17:58:42.000Z\",\"district\":\"test_district\"}]"}
Error is
08-02 21:20:57.264: E/ViewRootImpl(31835): sendUserActionEvent() mView == null

Related

parsing Json in Android Studio when result is empty

I try to load datas from a Json that is on my server to my smartphone.
When the json is like this, it works and i get the label "spanishguitar":
{"file": "image.jpg", "objects": [{"bbox": [611, 82, 1231, 1265], "label": "spanishguitar", "prob": 0.991}]}
Here is my code:
public void updateLabel() {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
if (200 == jsonResponse.getStatusLine().getStatusCode()) {
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonResult jsonResult = new Gson().fromJson(json, JsonResult.class);
instrumentname = jsonResult.objects.get(0).label;
But sometimes the json is empty like this:
{"file": "image.jpg", "objects": []}
So my plan is that if objects == null to get something like:
Toast.makeText(getApplicationContext(), "Uuuups, itś empty", Toast.LENGTH_SHORT).show();
Do you know how to parse the json, so that i get a message in the case of an empty "objects"?
Thank you!
Now it works. Here is my code:
#RequiresApi(api = Build.VERSION_CODES.N)
private void empty() throws IOException {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(String.valueOf(json));
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if (objects == null || objects.size() == 0) {
/////////////
runOnUiThread(new Runnable() {
#Override
public void run() {
noResult.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Identification failed", Toast.LENGTH_SHORT).show();
}});
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
} else {
updateLabel();
}
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
Thank you a lot for your help!
'Empty' is not 'null'.You can use
ArrayUtils.isEmpty(objects)
or
objects == null || objects.length() == 0
to detect whether you got an empty objects.
I writed a demo for you:
import com.google.gson.*;
public class Main
{
public static void main(String[] args)
{
JsonParser parser = new JsonParser();
// JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": []}");
JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": [{\"bbox\": [611, 82, 1231, 1265], \"label\": \"spanishguitar\", \"prob\": 0.991}]}");
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if(objects == null || objects.size() == 0) {
System.out.println("objects is empty");
}else{
JsonObject firstObj = objects.get(0).getAsJsonObject();
System.out.println("objects[0].label="+firstObj.get("label"));
}
}
}

okhttp returns null response

```protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
ctx=getApplicationContext();
txtString= (TextView)findViewById(R.id.txtString);
httpClient = new OkHttpClient();
try {
sendGETT();
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected void sendGETT() throws IOException {
httpClient = new OkHttpClient();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://devru-gaana-v1.p.rapidapi.com/featuredAlbums.php")
.get()
.addHeader("x-rapidapi-host", "devru-gaana-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "my api key")
.build();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response.body().string());
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " +
responseHeaders.value(i));
Main3Activity.txtString.setText(response.header("Server"));
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.body().charStream());
final String prettyJsonString = gson.toJson(je);
runOnUiThread(new Runnable() {
#Override
public void run() {
txtString.setText(prettyJsonString);
}
});
}
}
});
}
}```
I'm trying to use okhttpclient with okhttp3, but it return a null value.i tried another url with headers which work fine but when i try this it gives null respone.I tried many solutions from net but I can't figured this out.hope for the help.thanks
This code works fine, for example,
for
Response response = client.newCall(request).execute();
Request request = new Request.Builder()
.url("https://httpbin.org/get")
.addHeader("custom-key", "mkyong") // add request headers
.addHeader("User-Agent", "OkHttp Bot")
.build();
or any other website but I want to get the content of website using rapid api with add headers
```Request request = new Request.Builder()
.url("https://devru-gaana-v1.p.rapidapi.com/featuredAlbums.php")
.get()
.addHeader("x-rapidapi-host", "devru-gaana-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "mine api for site")
.build();```

org.json.JSONException: No value for opening_hours ,how to handle this type of error

logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)

Java/Android: Backslashes in JSON in Double Quotation places

I try to send "POST" request to serwer. Request includes JSON. Server returns "ok" or my JSON (in value of "message" key), if data in not correct. And I get strange backslashes ( \ sing) in my JSON, sent to server.
I get JSON response:
{"message":{"{\"phone_number\":\"_380661111111\",\"password\":\"112233aa\",\"military_id\":\"12345\",\"email\":\"won#mail_ru\"}":""}}
Normal JSON:
{"phone_number":"380666320670","password":"112233aa","military_id":"12345","email":"wovilon#mail.ru"}
Full code:
class SendLoginData extends AsyncTask<Void, Void, Void> {
String[] key,value;
String mResultString;
SendLoginData(String[] inKey, String[] inValue ){
this.key=new String[inKey.length];
this.value=new String[inValue.length];
this.key=inKey;
this.value=inValue;
}
String resultString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {// http://oasushqg.beget.tech/users
String myURL = "http://y937220i.bget.ru/users";
byte[] data = null;
InputStream is = null;
try {
URL url = new URL(myURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
for (int i=0; i<this.key.length; i++) {
jsonParam.put(this.key[i], this.value[i]);
}
data=jsonParam.toString().getBytes("UTF-8");
os.write(data);
Log.d("MyLOG", "data is next: "+new String(data, "UTF-8"));
data = null;
conn.connect();
int responseCode= conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (responseCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
JSONObject jsonObj=new JSONObject(resultString);
mResultString=jsonObj.getString("message");
} else {
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(resultString != null) {
Log.d("MyLOG", "postExecute run");
Log.d("MyLOG", mResultString);
}
}}

Json parsing Using Volley does not get cahced

I Parse json using volley framework, which every time gets response from the server, does not check the cache, It has taken a whole day, Here is my code. Any of you have used volley for parsing json are expected to help
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(diag_url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
// handle data, like converting it to xml, json, bitmap etc.,
// Parsing json
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
try {
DiagRegPojo test = new DiagRegPojo();
JSONObject obj = jsonArray.getJSONObject(i);
String testName = obj.getString("content");
Log.d("Response From Cache", testName);
test.setTitle(testName);
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
// Creating volley request obj
JsonArrayRequest testReq = new JsonArrayRequest(diag_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DiagRegPojo test = new DiagRegPojo();
test.setTitle(obj.getString("content"));
Log.d("Response From Server", obj.getString("content"));
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
})
{
//**
// Passing some request headers
//*
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Set-Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Content-Type", "application/x-www-form-urlencoded");
//headers.put("Content-Type","application/json");
headers.put("Accept", "application/x-www-form-urlencoded");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(testReq);
}
}
To cache images, I have used this. sure it can be of some help to you.
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
.
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}