简体   繁体   中英

How to access REST API localhost from Java Code in AndroidStudio

So I'm trying to get my database from my local json-server (rest api) using Volley in my AndroidStudio project, but nothing seems to work. It doesn't even get past the first lines of code, debugger doesn't seem to help either.

What I've been seeing is that it just jumps over alle the code when it hits new Response.Listener<JSONObject>(...) and next thing my debugger shows me is the last closing bracelet, nothing happened, not any error or exception and I find. Or is this just a debugger thing that i can't debug in overrides classes given as parameters?

note: localhost works just fine, can even send requests using postman. Even tried it using Unirest instead of Volley.

In Android Manifest:

 <uses-permission android:name="android.permission.INTERNET"/>

Code Snippet:

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

// ...

    private void parseJSON() {
        String url = "http://localhost:3000/db";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArrayProjects = response.getJSONArray("projects");

                            for (int i = 0; i < jsonArrayProjects.length(); i++) {
                                JSONObject projectJO = jsonArrayProjects.getJSONObject(i);
                                Log.d("PROJEKT-Name: ", projectJO.getString("name")); // just printing result to see if it works
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        requestQueue.add(request);
    }

For me it seems more like a problem of not being able to reach the server. Any help is appreciated!

EDIT : changed http://localhost:3000/db to http://10.0.2.2:3000/db which now seems to work, I can open my server in emulator's chrome, but I still cannot retrieve the data.

Just to make sure if it isn't a small mistake in my JSON: This should work using above code, right?

{
  "projects": [
    {
      "id": 1,
      "name": "History Paper",
      "description": "The Wild West",
      "comments": [],
      "appointments": [],
      "handlers": [],
      "processors": [],
      "type": "PAPER"
    },
    {
      "id": 2,
      "name": "Paper social studies",
      "description": "The society",
      "comments": [],
      "appointments": [],
      "handlers": [],
      "processors": [],
      "type": "PAPER"
    }
  ]
}

You shouldnt use localhost for a mobile application, because it will be running in a separate device ( either real or virtual ) and not on your computer

  • Here is what you should do:

1) Create an access point from your computer or connect to your home WiFi using an ip address and write it in your code

private void parseJSON() {
    String ip = " your_ip_address_here ";
    String url = "http://"+ip+":3000/db";
    ...

2) From the device running the application, connect to the WiFi or the access point using an ip address from same network

Then you can run it successfully

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM