2

I am trying to create a news viewing part of my final task for graduate studies. What this (UserNewsActivity) does is it fetches data on create by calling my method, like so:

ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_news);

    InstanciateListViewValues();
}

and fetches data from api I created in Asp .Net Web Api 2 (cause there is also web part in mvc).

Fetched data should be then stored in static var that is in "Global.NewsItemsList", and after that I populate my (custom) ListView with data. Problem is that I am constantly getting error for 200 reponse:

   E/Volley: [110] BasicNetwork.performRequest: Unexpected response code 200 for  http://192.168.56.1:5000/News/GetNews

   I/System.out: NetworkError

And sometimes it just works :S I am 100% sure I am getting properly data (checked in browser, 200 status (OK), check bottom link), and I have used volley to fetch even more data before in project in same way and it works 100% of the time. Method looks like so:

   private void InstanciateListViewValues() {
    if (Global.NewsItemsList == null) {
        final String url = ApiLink + "/News/GetNews";
        RequestQueue queue = Volley.newRequestQueue(this);

        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Iterator<String> keys = response.keys();                                
                            String str_Name = keys.next();                                
                            String jsonString = response.optString(str_Name);

                            Gson gson = new Gson();
                            Global.NewsItemsList = gson.fromJson(jsonString, new TypeToken<List<NewsDetailsViewModel>>() {
                            }.getType());

                            setAdapterData();
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                            Toast.makeText(UserNewsActivity.this, "An error occured, please try later.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(UserNewsActivity.this, "An error occured, please try later.",
                                Toast.LENGTH_SHORT).show();

          //System.out.println(error.getMessage());//if left uncommented will break app
                        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                            System.out.println("TimeoutError || NoConnectionError");
                        } else if (error instanceof AuthFailureError) {
                            System.out.println("AuthFailureError");
                        } else if (error instanceof ServerError) {
                            System.out.println("ServerError");
                        } else if (error instanceof NetworkError) {
                            System.out.println("NetworkError");
                            NetworkResponse response = error.networkResponse;
                            if (error instanceof ServerError && response != null) {
                                try {
                                    String res = new String(response.data,
                                            HttpHeaderParser.parseCharset(response.headers, "utf-8"));

                                    JSONObject obj = new JSONObject(res);
                                    System.out.println(obj.toString());
                                } catch (UnsupportedEncodingException e1) {
                                    System.out.println(e1.getMessage());
                                    e1.printStackTrace();
                                } catch (JSONException e2) {
                                    System.out.println(e2.getMessage());
                                    e2.printStackTrace();
                                }
                                catch (Exception e3) {
                                    System.out.println(e3.getMessage());
                                    e3.printStackTrace();
                                }
                            }
                        } else if (error instanceof ParseError) {
                            System.out.println("ParseError");
                        }
                    }
                }
        );            
        queue.add(getRequest);
    } else {
        setAdapterData();
    }
}

If it worth noting I am using VisualStudio to run my services locally, and then using IISExpress to proxy my port, and finally using Genymotion as a emulator.

To keep this question clean, here is link to pastebin, with Global and NewsItemsList classes and response from Web api: https://pastebin.com/5Za6yLDP

Kadaj
  • 615
  • 3
  • 13
  • 31
  • log the whole exception and the stacktrace instead of just the message – njzk2 Apr 11 '17 at 21:02
  • `catch (Exception e) {` is very harsh. Try catching some *specific* exception – OneCricketeer Apr 11 '17 at 21:02
  • @cricket_007 "catch (Exception e) {" part is if gson fails to deserialize JSON. – Kadaj Apr 11 '17 at 21:03
  • 1
    I am aware, but "proper" exception handling would catch the particular error that only Gson throws, not anything within the try block – OneCricketeer Apr 11 '17 at 21:05
  • @njzk2 I have catched erros like so "if (error instanceof NetworkError) { System.out.println("NetworkError");" and tried to log them like so: https://pastebin.com/Ub8TMF5R (2 long for comment sorry). But I am not getting nothing in logcat. – Kadaj Apr 11 '17 at 21:06
  • 1
    Anyways, replace the line with `e.getMessage()` with `e.printStackTrace()` method call – OneCricketeer Apr 11 '17 at 21:06
  • I'll also point out that `Global.NewsItemsList` is a poor design because `static` global variables are often an anti-pattern in Android. – OneCricketeer Apr 11 '17 at 21:10
  • @cricket_007 Thank you for all this usefull info. I am really struggling with android cause I have to do some open source programming since I took Asp .Net app as main app, so I don't know best practices for android. Also, if i put "e.printStackTrace()" it is still not showing anything. – Kadaj Apr 11 '17 at 21:14
  • It's supposed to get more logs, so you may [edit] the question with the problem so that we can help more than guessing what `e.getMessage()` tries to say – OneCricketeer Apr 11 '17 at 21:17
  • @cricket_007 I added errors logs in a way I tried them. If it is of any help, right after my get fails, I get many of these messages " [ 04-11 21:17:27.823 56: 56 D/ ] Socket deconnection". – Kadaj Apr 11 '17 at 21:22
  • You are looking for `E/` messages if you have **E**rrors. That would be a debug – OneCricketeer Apr 11 '17 at 21:23
  • And use `Log.e` instead of `System.out.println` for errors – OneCricketeer Apr 11 '17 at 21:23
  • @cricket_007 Nah man, still nothing. Tried Log.e, tried to catch more general exceptions etc. nothing. I have been batling this FFS for 2 days now. Is there any alternative that you would recommend to replace volley? – Kadaj Apr 11 '17 at 21:28
  • http://stackoverflow.com/questions/16902716/comparison-of-android-networking-libraries-okhttp-retrofit-and-volley – OneCricketeer Apr 11 '17 at 21:34
  • Thank you for your time man, I am really sorry if I disturbed/angered you with my inability to properly log exceptions. I'm gonna sleep now, good night. – Kadaj Apr 11 '17 at 21:35
  • 1
    I'm not angered :) I would simply prefer you [edit] the question with more log messages – OneCricketeer Apr 11 '17 at 21:37
  • In my case was because I was using Charles proxy and I didn't configure my emulator. Here is my solution: https://stackoverflow.com/a/55291344/2091181 – Jorge Casariego Mar 22 '19 at 00:54

1 Answers1

0

Hej Kadaj,
I was just looking at your code but what took my attention most is "If it worth noting I am using VisualStudio to run my services locally, and then using IISExpress to proxy my port, and finally using Genymotion as a emulator."
I encountered that sometimes that proxy will fail to work if you use first address that iisexpress-proxy (in my case it is 192.168.0.1) cause that is usually gateway address.
For sake of testing this properly take a look at this question (Configure IIS Express for external access to VS2010 project), and after that it should work just fine (at least it did to me :D).

Community
  • 1
  • 1
dot404
  • 198
  • 1
  • 12
  • Hej man, I just tested out what you told me, and you are absolutely right. It works like a charm now :) – Kadaj Apr 13 '17 at 07:39