Android application using data from webservice

I want to write an Android application that can display some data received (polled) from an Internet resource.

I assume that I need to write some logic that will periodically call and receive data from some endpoint, analyze the response and display it. Is there a good tutorial for all these steps?

I know very little about Android programming at the moment, and it might be better to start with something simpler. I just want to know what to look for when studying the collected resources on this.

+2
source share
1 answer

What you want to do is create a rest api that provides data for your Android application. For instance. you have the content that you want to use in your application, then you can write a php script that simply returns this data in a specific format.

eg. mysite.net/rest/fetchAllLocations.php?maybe_some_parameters

This will return locations, for example. json, here is an example of how it looks:

[{"ID": 1, "shop_lng": +8.5317153930664, "shop_lat": +52.024803161621, "shop_zipcode": 33602, "shop_city": "Bielefeld", "shop_street": "Arndtstra \ u00dfe", "shop_snumber": 3, "shop_name": "M \ u00fcller", "shop_desc": "Kaufhaus"}]

api :

http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld

, , Android. :

public class JsonGrabber{

    public static JSONArray receiveData(){  
        String url = "your url";
        String result = "";

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet method = new HttpGet(url);
        HttpResponse res = null;

        try {
            res = client.execute(method);
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        try{
            InputStream is = res.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
             StringBuilder sb = new StringBuilder();
             String line = null;
             while ((line = reader.readLine()) != null) {
                     sb.append(line + "\n");
             }
             is.close();
             result = sb.toString();
        }catch(Exception e){
             Log.e("log_tag", "Error converting result "+e.toString());
        }

        JSONArray jArray = null;

        try{
             jArray = new JSONArray(result);
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }
}

, json, :

JSONArray test = (JSONArray) JsonGrabber.receiveData() 

try { 
    for(int i=0;i<test.length();i++){
    JSONObject json_data = test.getJSONObject(i);
    int id = json_data.getInt("id");
    }
}

- , . AsyncTask. :

Threading , Android-

+3

Source: https://habr.com/ru/post/1779319/


All Articles