Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从联机数据库加载信息以在“活动”中显示_Android_User Interface_General Network Error - Fatal编程技术网

Android 从联机数据库加载信息以在“活动”中显示

Android 从联机数据库加载信息以在“活动”中显示,android,user-interface,general-network-error,Android,User Interface,General Network Error,我正在使用json从php文件加载信息。然后,我尝试在加载页面后立即将其显示在列表视图中。但是,我的onCreate()方法中有它,它不允许我在UI线程上执行网络操作。我可以将以下代码放在何处: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chores); bChore

我正在使用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();
    }
}
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u杂务);
bChore=(按钮)findViewById(R.id.addChore);
bChore.setOnClickListener(此);
Bundle extras=getIntent().getExtras();
最终字符串user=extras.getString(“用户名”);
//URL是用于验证用户的PHP文件的位置
String requestURL=SERVER_ADDRESS+“FetchChoreData.php”;
网址;
Chore returnedChore=null;
试一试{
//打开与PHP文件的连接
//设置连接的条件
url=新url(请求url);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(连接超时);
连接设置连接超时(连接超时);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
//打开输出流以发送要验证的数据
//然后关闭所有输出流并刷新输出写入程序
OutputStream os=conn.getOutputStream();
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(os,“UTF-8”));
Uri.Builder=新的Uri.Builder()
.appendQueryParameter(“用户名”,用户);
字符串查询=builder.build().getEncodedQuery();
writer.write(查询);
writer.flush();
writer.close();
os.close();
//保存响应代码以确保连接成功
int code=conn.getResponseCode();
Log.d(“code”,Integer.toString(code));
//打开输入流以从服务器检索已验证的数据
//启动字符串生成器以从输入中读取数据
//完成构建字符串后关闭BufferedReader
InputStream responseStream=新的BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader=新的BufferedReader(新的InputStreamReader(responseStream));
弦线;
StringBuilder StringBuilder=新的StringBuilder();
而((line=responseStreamReader.readLine())!=null)
stringBuilder.append(第+“/n行”);
responseStreamReader.close();
字符串响应=stringBuilder.toString();
Log.d(“响应”,响应);
JSONObject jsonResponse=新的JSONObject(响应);
//从字符串创建JSON对象
ArrayList琐事=新建ArrayList();
JSONArray choresArray=jsonResponse.getJSONArray(“chore”);
for(int i=0;i
您可能应该将此代码放入
AsyncTask
中,并在
AsyncTask的
onPostExecute
中填充UI。只需确保不在AsyncTask的
doInBackground
中更新UI,在那里进行数据提取


实际上,您最好将带有setRetainInstance(true)的非UI片段与AsyncTask一起使用,但您可以通过谷歌搜索它。

查找如何使用AsyncTask或使用类似Volley的库