【问题标题】:Loading information from online db to display in activity从在线数据库加载信息以显示在活动中
【发布时间】:2016-03-12 20:23:08
【问题描述】:

我正在使用 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();
    }
}

【问题讨论】:

  • 查看如何使用 AsyncTask 或使用 Volley 之类的库

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


【解决方案1】:

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

实际上,您最好将非 UI 片段与 setRetainInstance(true) 与 AsyncTask 一起使用,但您可以在 Google 上搜索。

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 2017-02-25
    • 2018-05-06
    • 2017-04-07
    • 1970-01-01
    • 2020-10-23
    • 2011-09-16
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多