如何获取 onPostExcecute 的结果值到 onCreate



我怎样才能在这里获得我的AsyncTask结果的值。

    public class JSONPicture 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(finalJSON);
            JSONArray parentArray = parentObject.getJSONArray("tbl_user");
            JSONObject finalObject = parentArray.getJSONObject(0);

            String firstname = finalObject.getString("userImage");
            return firstname;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(result, ivUser);
            Log.d(TAG, result);
        }catch (IllegalArgumentException e){
            Log.d(TAG,e.toString());
        }
    }
}

我像这样在onStart上打电话。所以我可以加载。当它加载时,我想获取图像的字符串。

@Override
protected void onStart() {
    super.onStart();
    new JSONPicture().execute("http://carkila.esy.es/carkila/profile/profileImage.php?username="+pref.getString("username","").toString());
}

我想在单击这样的图像时获取图像的 URL。

        ivUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, ivUser.toString);

        }
    });

你没有。 AsyncTask 的目的是并行运行。 如果您要等待结果,则没有理由使用AsyncTask。 通过强制 UI 线程等待,将使应用对用户无响应。 如果这样做的时间过长,将导致应用程序由于看门狗计时器而崩溃。

正确的做法是将所有需要结果的逻辑放在 onPostExecute 中。 如果需要,请放置加载栏或其他 UI 元素,以显示应用正在等待,直到您获得结果。

可以使用更机械的方式将值存储在缓存存储中,以便从应用中的任何位置检索。我会推荐tinyDB。

gradle 'compile 'com.mukesh:tinydb:1.0.1'

TinyDB tinyDB = new TinyDB(getApplicationContext());
tinyDB.putString("key",value);

然后,可以使用此代码行从应用内的任何位置检索值。

tinyDB.getString("key");

机械但高效。只需先调用onCreate中的异步任务方法,然后调用tinyDB.getString。将字符串存储在 onPostExecute 的 tinyDB 中。

最新更新