0

我的onPostExecute方法需要返回一个结果,onCreate()以便它可以用它做一些事情,但我很难到达那里。

public class ScheduleList extends Activity {

    public String url = "http://www.bbc.co.uk/bbcnews/programmes/schedules/today.json";

    private DownloadJSON mTask = null;


    public static String fetchedJSON = "";
    public static String getFetchedJSON() {
       return fetchedJSON;
    }
  public static void setFetchedJSON(String fetchedJSON) {
     ScheduleList.fetchedJSON = fetchedJSON;
  }


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_schedule_list);

    // Show the Up button in the action bar.
    setupActionBar();

    TextView tvNotice = (TextView) findViewById(R.id.schedulePreamble);
    tvNotice.setText("Well, hello there...");

    System.out.println("Hello");
    downloadPage();
    System.out.println(getFetchedJSON());

}


public class DownloadJSON extends AsyncTask<String, Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected String doInBackground(String... urls) {
        String response = "";
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(new InputStreamReader(
                        content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    @Override
    public void onPostExecute(String result) {
        setFetchedJSON(result);
    }


}

private void downloadPage() {
    if (mTask != null && mTask.getStatus() != DownloadJSON.Status.FINISHED) {
        mTask.cancel(true);
    }
    mTask = (DownloadJSON) new DownloadJSON().execute(new String[] { url });
}

}

每次我运行代码时,System.out.println(getFetchedJSON());什么都不返回,这意味着我onPostExecute实际上并没有改变任何变量的内容,是吗?

4

2 回答 2

0

我已经修改了我的代码。这段代码将从 Url 获取您的 JSON 并将其转换为 String 和 Json Objecct 这现在可以使用

public class MainActivity extends Activity {
InputStream is = null;
JSONObject jObj = null;
String json = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b = (Button) findViewById(R.id.button1);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // Making HTTP request
            try {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

                StrictMode.setThreadPolicy(policy); 
                // defaultHttpClient
                String url = "http://api.androidhive.info/contacts/";
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();           

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

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

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            // return JSON String

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

在 Android Manifest 中添加这一行:-

    <uses-permission android:name="android.permission.INTERNET" />
于 2013-11-10T11:52:24.333 回答
0

该方法downloadPage()启动您的任务。此任务在其他线程中执行,并且在您启动任务后立即打印结果,但任务尚未结束。试试这个代码:

公共类 ScheduleList 扩展 Activity {

public String url = "http://www.bbc.co.uk/bbcnews/programmes/schedules/today.json";

private DownloadJSON mTask = null;


public static String fetchedJSON = "";
public static String getFetchedJSON() {
    return fetchedJSON;
}
public static void setFetchedJSON(String fetchedJSON) {
    ScheduleList.fetchedJSON = fetchedJSON;
}


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_schedule_list);

    // Show the Up button in the action bar.
    setupActionBar();

    TextView tvNotice = (TextView) findViewById(R.id.schedulePreamble);
    tvNotice.setText("Well, hello there...");

    System.out.println("Hello");
    downloadPage();

}

public void printFetchedJSON() {
    System.out.println(getFetchedJSON());
}


public class DownloadJSON extends AsyncTask<String, Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected String doInBackground(String... urls) {
        String response = "";
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(new InputStreamReader(
                        content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    @Override
    public void onPostExecute(String result) {
        setFetchedJSON(result);
        printFetchedJSON();
    }


}

private void downloadPage() {
    if (mTask != null && mTask.getStatus() != DownloadJSON.Status.FINISHED) {
        mTask.cancel(true);
    }
    mTask = (DownloadJSON) new DownloadJSON().execute(new String[] { url });
}

}

于 2013-11-10T12:04:42.930 回答