从在线数据库加载信息以显示在活动中

时间:2016-03-12 20:23:09

标签: android user-interface general-network-error

我使用json从php文件加载信息。然后我会在加载页面后立即在列表视图中显示它。但是我在我的onCreate()方法中有它,它不允许我在UI线程上进行网络操作。我在哪里可以改为使用以下代码:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chores);

    bChore = (Button) findViewById(R.id.addChore);

    bChore.setOnClickListener(this);

    Bundle extras = getIntent().getExtras();
    final String user = extras.getString("username");


    //The URL is the location of the PHP file to validate a user
    String requestURL = SERVER_ADDRESS+"FetchChoreData.php";

    URL url;
    Chore returnedChore = null;
    try {
        //Opens the connection to the PHP files
        //Sets the conditions of the connection
        url = new URL(requestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(CONNECTION_TIMEOUT);
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        //Opens an output stream to send the data to be verified
        // and then closes the all output streams and flushes the output writer
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

        Uri.Builder builder = new Uri.Builder()
                .appendQueryParameter("username",user);

        String query = builder.build().getEncodedQuery();

        writer.write(query);
        writer.flush();
        writer.close();
        os.close();
        //saves the response code to ensure connection was succesful
        int code = conn.getResponseCode();
        Log.d("code", Integer.toString(code));

        //Opens an input stream to retrieve verified data back from the server
        //Starts a String Builder to read the data off the input
        //Closes the BufferedReader once it has finished building the string
        InputStream responseStream = new BufferedInputStream(conn.getInputStream());
        BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = responseStreamReader.readLine()) != null)
            stringBuilder.append(line + "/n");
            responseStreamReader.close();


            String response = stringBuilder.toString();
            Log.d("response",response);

            JSONObject jsonResponse = new JSONObject(response);

            //Creates a JSON object from the string
            ArrayList<String> chores = new ArrayList<String>();
            JSONArray choresArray = jsonResponse.getJSONArray("chore");
            for(int i=0; i < choresArray.length() ; i++) {
                JSONObject chore = choresArray.getJSONObject(i);
                String current_chore = chore.optString("chore_name");
                String name = chore.optString("child_username");
                String points = chore.optString("point_value");

                String currentChore = "";
                if(name==null)
                    currentChore = current_chore + "\t" + "Not Claimed" + "\t" + points;
                else
                    currentChore = current_chore + "\t" + name + "\t" + points;
                chores.add(currentChore);
                Log.d("Output", currentChore);

            }


            ArrayAdapter<String> choreAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, chores);

            ListView listView = (ListView) findViewById(R.id.choreList);
            listView.setAdapter(choreAdapter);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

您可能应该将此代码放在AsyncTask中,并在AsyncTask's onPostExecute中填充您的用户界面。只需确保不在AsyncTask doInBackground中更新UI,在那里进行数据提取。

实际上你最好使用带有setRetainInstance(true)的非UI片段和AsyncTask,但你可以谷歌。