使用Web服务在Android上执行异步任务

时间:2017-08-22 20:46:37

标签: android web-services android-asynctask google-places-api

所以我有这个应用程序,我正在努力。我只想从上一个Activity的意图中得到的地方ID的地方照片,我想知道如何通过异步任务更改我的代码。

这是活动代码:

public class CrearViajeActivity2 extends AppCompatActivity {
private String TAG="URL ERROR >>> : ";
private Intent intent;
private String Placeid, imageURL ,reference;
private final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private ImageView PlaceImage;
URLService service;
private ArrayList<String> photosR;


public CrearViajeActivity2()  {

}

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

    intent = getIntent();
    Placeid = intent.getStringExtra("PlaceID");


    PlaceImage = findViewById(R.id.imageView2);


    // THIS IS WHAT I HAVE TO FIX , WITH AN ASYNC TASK OR SOMETHING , IF I COMMENT THIS 2 LINES THE APP THROWS AN EXCEPTION AND STOPS WORKING BUT I DONT KNOW HOW TO IMPLEMENT IT(DO IT) .
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    //HERE I GET THE REFERENCE OF THE PLACE

    reference=String.format("https://maps.googleapis.com/maps/api/place/details/json?placeid=%s&key=%s",Placeid,API_KEY);


    service= new URLService();
    String jsonStr = service.URLService(reference);


    photosR = new ArrayList<>();

    if(jsonStr!=null){

        try{
            JSONObject jsonObj = new JSONObject(jsonStr);

            JSONObject jsonObjResult = jsonObj.getJSONObject("result");

            JSONArray photos = jsonObjResult.getJSONArray("photos");


            for (int i = 0; i < photos.length(); i++) {

                JSONObject c = photos.getJSONObject(i);

                String photoReference = c.getString("photo_reference");

                photosR.add(photoReference);

            }


        }catch(JSONException ex){
            Log.e(TAG, "JSON FAILED: " + ex.getMessage());

            Toast.makeText(getApplicationContext(),
                    "JSON FAILED: " + ex.getMessage(),
                    Toast.LENGTH_LONG)
                    .show();
        }

    }else{
        Log.e(TAG, "JSON FAILED.");
    }


    // AND HERE I FINALLY GET THE PHOTO
    imageURL =String.format("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=%s&key=%s",photosR.get(0),API_KEY);
    try{
        URL url = new URL(imageURL);
        Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        PlaceImage.setImageBitmap(bmp);
    }catch(MalformedURLException ex){

    }catch(IOException ex){

    }
}
}

这是服务类:

private static final String TAG = URLService.class.getSimpleName() +" >> : ";

public URLService() {


}


private String convertirStreamaString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

public String URLService(String reqUrl) {
    String ref = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // READS THE REFERENCE OF THE PHOTO
        InputStream in = new BufferedInputStream(conn.getInputStream());
        ref = convertirStreamaString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return ref;
}
}

0 个答案:

没有答案