Asynk Task calling in loop not giving the value return

こ雲淡風輕ζ 提交于 2020-01-16 09:41:08

问题


I am try to create a application that will update the weather of multiple cities .Each row will have diffrent temp so i have use a AsynkTask. But i am not able to update the UI after getting the response from the API.

My Main Activity

public class MainActivity extends Activity {
    LinearLayout depart_arrivals_details;
    LayoutInflater inflater;
    TextView depart_time,
    depart_airport_city, depart_airport, arrival_time,
    arrival_airport_city, arrival_airport, pnr_number,temprature,humidity;
    ImageView flight_depart_image;
    public static String url = "";
    WeatherResponse response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        depart_arrivals_details = (LinearLayout) findViewById(R.id.depart_arrivals_details);
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        setSectorData();
    }

    void setSectorData() {
        for (int i = 0; i < 1; i++) {
            inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            RelativeLayout layout = (RelativeLayout) inflater.inflate(
                    R.layout.sector_details, depart_arrivals_details, false);
            depart_time = (TextView)layout.findViewById(R.id.depart_time);
            depart_airport_city = (TextView)layout.findViewById(R.id.depart_airport_city);
            temprature = (TextView)layout.findViewById(R.id.temprature);
            humidity = (TextView)layout.findViewById(R.id.humidity);
            flight_depart_image = (ImageView)layout.findViewById(R.id.flight_depart_image);
            WeatherResponse responseUpdate = requestWeatherUpdate("DEL");

        depart_time.setText("20:45");
        depart_airport_city.setText("Mumbai");
        /*
         * This part will be updated when we will se the request and get the response 
         * then we have to set the temp and humidity for each city that we have recived
         * */
        temprature.setText(responseUpdate.getTempInC()+(char) 0x00B0);//Here it is showing null pointer exception after that the respone is coming from the server .So can we do this 
        humidity.setText(responseUpdate.getHumidity());

            flight_depart_image.setImageResource(R.drawable.f1);

            depart_arrivals_details.addView(layout, i);
        }
    }

    /*
     * Here the location will be dynamic and have to send the request for all the location i have 
     * */
    private WeatherResponse requestWeatherUpdate(String location) {
        url = "http://api.worldweatheronline.com/free/v1/weather.ashx?&format=xml&num_of_days=2&key=uysakmq923nbd5y549yz3aaw&q="
                + location;
        Log.d("URL for Weather Upadate", url);
        WeatherUpdateAsyncTask weatherReq = new WeatherUpdateAsyncTask(new CallBack() {
            @Override
            public void run(Object result) {
                try {
                    String AppResponse = (String) result;
                    response = ParseWeatherResponseXML
                            .parseMyTripXML(AppResponse);
                } catch (Exception e) {
                    Log.e("TAG Exception Occured",
                            "Exception is " + e.getMessage());
                }
            }
        });
        weatherReq.execute(url);
        return response;

    }

This is my requestWeatherUpdate

   private WeatherResponse requestWeatherUpdate(String location) {
        url = ""
                + location;
        Log.d("URL for Weather Upadate", url);
        WeatherUpdateAsyncTask weatherReq = new WeatherUpdateAsyncTask(new CallBack() {
            @Override
            public void run(Object result) {
                try {
                    String AppResponse = (String) result;
                    response = ParseWeatherResponseXML
                            .parseMyTripXML(AppResponse);
                } catch (Exception e) {
                    Log.e("TAG Exception Occured",
                            "Exception is " + e.getMessage());
                }
            }
        });
        weatherReq.execute(url);
        return response;

    }

And if i try to set the value that i have recieved is throwing null pointer exception


回答1:


Try this

First In the for Loop

depart_arrivals_details.removeAllViews();
 for (int i = 0; i < 2; i++) {
            requestWeatherUpdate("BLR");
            }

Function WeatherResponse

private WeatherResponse requestWeatherUpdate(String location) {
        url = ""
                + location;
        Log.d("URL for Weather Upadate", url);
        WeatherUpdateAsyncTask weatherReq = new WeatherUpdateAsyncTask();
        String weatherRequestResponse="";
        try {
            weatherRequestResponse=weatherReq.execute(url).get();
            parsedWeatherResponse = ParseWeatherResponseXML
                    .parseMyTripXML(weatherRequestResponse);
        } catch (InterruptedException e) {

            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return parsedWeatherResponse;

    }

And then AsynkTask

public class WeatherUpdateAsyncTask extends AsyncTask<String, Void, String> {
    Context context;
    CallBack callBack;

   @Override
    protected String doInBackground(String... arg0) {
        String responseString = "";
        HttpClient client = null;
        try {
            client = new DefaultHttpClient();
            HttpGet get = new HttpGet(arg0[0]);
            client.getParams().setParameter("http.socket.timeout", 6000);
            client.getParams().setParameter("http.connection.timeout", 6000);
            HttpResponse responseGet = client.execute(get);
            HttpEntity resEntityGet = responseGet.getEntity();
            if (resEntityGet != null) {
                responseString = EntityUtils.toString(resEntityGet);
                Log.i("GET RESPONSE", responseString.trim());
            }
        } catch (Exception e) {
            Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
        }
        Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
        client.getConnectionManager().shutdown();
        return responseString.trim();

    }

    @Override
    protected void onPostExecute(String result) {
       super.onPostExecute(result);
    }

}



回答2:


You can update the Views that run on the UI Thread after you get the result using AsyncTask's onPostExecute(). Also, you need to call AsyncTask's execute() for the AsyncTask to actually start.



来源:https://stackoverflow.com/questions/19174411/asynk-task-calling-in-loop-not-giving-the-value-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!