HttpURLConnection无法获取数据并在ListView

时间:2016-02-03 11:24:20

标签: android httpurlconnection

我有这个代码,我试图在对它进行各种更改后运行。问题是我已添加权限并添加仍然发现代码似乎无法正常工作。 如果有人能帮我找到错误,那将是一个很大的帮助。 我哪里错了。 这是 .java 文件。

    package com.example.adityapc.phpfeeddisplay;

    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

            public class ActivityMain extends Activity {

                private static final String TAG = "Http Connection";

                private ListView listAct = null;

                private ArrayAdapter arrayAdapter = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listAct = (ListView) findViewById(R.id.listActivity);
    final String url = "http://anonymoous.marshalcadetacademy.com/notification.php";
    new AsyncHttpTask().execute(url);
}

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        Integer result = 0;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("GET");
            int statusCode = urlConnection.getResponseCode();
            if (statusCode ==  200) {
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                String response = convertInputStreamToString(inputStream);
                parseResult(response);
                result = 1;
            }else{
                result = 0;
            }
        }
        catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
        return result;
    }
    @Override
    protected void onPostExecute(Integer result) {
        if(result == 1){
            arrayAdapter = new ArrayAdapter(ActivityMain.this, android.R.layout.simple_list_item_1,R.id.listActivity);
            listAct.setAdapter(arrayAdapter);
        }
        else{
            Log.e(TAG, "Failed to fetch data!");
        }
    }
}

private String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null){
        result += line;
    }

    if(null!=inputStream){
        inputStream.close();
    }
    return result;
}
private void parseResult(String result) {
    try{
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("posts");
        String[] blogTitles = new String[posts.length()];
        for(int i=0; i< posts.length();i++ ){
            JSONObject post = posts.optJSONObject(i);
            String title = post.optString("title");
            blogTitles[i] = title;
        }
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }

这是 .xml 代码:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/linear" >

        <ListView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/listActivity"
            android:layout_gravity="center">


        </ListView>
    </LinearLayout>

如果您有任何建议,我们将不胜感激。

0 个答案:

没有答案