Reputation: 19
I am trying to create a mobile client using android to consume a local REST API I have created rest server on eclipse and it is running without problems but i am trying to create my client on android studio and it is running also but when i click on the button nothing is happening.
public class MainActivity extends AppCompatActivity {
private Button btnChercher;
private TextView tvJson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnChercher = (Button) findViewById(R.id.btnchercher);
tvJson = (TextView) findViewById(R.id.tvJson);
btnChercher.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JsonTask().execute("http://localhost:8080/membres");
}
}
);
}
public class JsonTask extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine())!=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject();
JSONArray parentArray = parentObject.getJSONArray("");
JSONObject finalObject = parentArray.getJSONObject(0);
String nomMembre = finalObject.getString("nomMembre");
return nomMembre+"\n";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection!=null){
connection.disconnect();
}
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvJson.setText(result);
}
}
}`
Upvotes: 0
Views: 2996
Reputation: 843
Your example shows the URL "http://localhost:8080/membres"
. Is that intentional? Is your Android application running your web server?
Probably not. "http://localhost:8080/membres"
works on your computer because localhost
is referring to your machine itself.
In order to make your Android app access your REST API, you should to do one of the following:
localhost
with the IP of your server. This will require your Android app to be on the same network as your server.localhost:8080
with the publicly accessible URL.There are other options, but these are the simplest.
Upvotes: 1