Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.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
Java 将JSON数据解析到ListView时出错_Java_Android_Xml_Json_Listview - Fatal编程技术网

Java 将JSON数据解析到ListView时出错

Java 将JSON数据解析到ListView时出错,java,android,xml,json,listview,Java,Android,Xml,Json,Listview,这些代码中没有错误。相反,我得到的是一个没有数据解析的空列表。Splash是启动程序活动,该按钮打开由ListView布局组成的菜单活动。Splash活动只有一个按钮,它基本上是通过intent打开菜单活动的,其他什么都没有,所以我不会在这里发布这个类的代码。post是JSONParser活动的布局。代码如下: Menu.java package com.example.test; import java.util.ArrayList; import java.util

这些代码中没有错误。相反,我得到的是一个没有数据解析的空列表。Splash是启动程序活动,该按钮打开由ListView布局组成的菜单活动。Splash活动只有一个按钮,它基本上是通过intent打开菜单活动的,其他什么都没有,所以我不会在这里发布这个类的代码。post是JSONParser活动的布局。代码如下:

Menu.java

    package com.example.test;

    import java.util.ArrayList;
    import java.util.HashMap;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;

    public class Menu extends ListActivity{

    private ProgressDialog pDialog;

    private static final String READ_DB_URL ="http://10.0.2.2:1337/webservice/lib.php";

    private static final String TAG_TITLE = "title";
    private static final String TAG_POSTS = "posts";

    private JSONArray mComments = null;

    private ArrayList<HashMap<String, String>> mCommentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);
    }

    public void updateJSONdata() {

    mCommentList = new ArrayList<HashMap<String, String>>();
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.getJSONFromUrl(READ_DB_URL);

    try{
        mComments = json.getJSONArray(TAG_POSTS);

        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            String title = c.getString(TAG_TITLE);

        HashMap<String, String> map = new HashMap<String, String>();

        map.put(TAG_TITLE, title);

        mCommentList.add(map);
    }
    } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void updateList() {

        ListAdapter adapter = new SimpleAdapter(this, mCommentList, 
        R.layout.post, new String[] { TAG_TITLE}, 
        new int[] { R.id.title,});

        setListAdapter(adapter);

        ListView lv = getListView();    
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                    }
                });
            }

    public class LoadComments extends AsyncTask<Void, Void, Boolean>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Menu.this);
            pDialog.setMessage("Loading Comments...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            updateJSONdata();
            return null;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            updateList();
        }
    }
    }
    package com.example.test;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.util.Log;

    public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

       // constructor
       public JSONParser() {

       }


     public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

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

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to 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 the JSON Object.
        return jObj;

        }


        // function get json from url
       // by making HTTP POST or GET mehtod
       public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

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

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                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
        return jObj;

         }
        }
package com.example.test;
导入java.util.ArrayList;
导入java.util.HashMap;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
公共类菜单扩展了ListActivity{
私人对话;
私有静态最终字符串读取\u DB\u URL=”http://10.0.2.2:1337/webservice/lib.php";
私有静态最终字符串标记_TITLE=“TITLE”;
私有静态最终字符串标记_POSTS=“POSTS”;
私有JSONArray mComments=null;
私有数组列表mCommentList;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
}
public void updateJSONdata(){
mCommentList=newarraylist();
JSONParser jParser=新的JSONParser();
JSONObject json=jParser.getJSONFromUrl(READ_DB_URL);
试一试{
mComments=json.getJSONArray(TAG_POSTS);
对于(int i=0;i
menu.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.test.Menu" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

    </RelativeLayout>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.test.JSONPaerser" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="30dp" />

    </RelativeLayout>

JSONParser.java

    package com.example.test;

    import java.util.ArrayList;
    import java.util.HashMap;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;

    public class Menu extends ListActivity{

    private ProgressDialog pDialog;

    private static final String READ_DB_URL ="http://10.0.2.2:1337/webservice/lib.php";

    private static final String TAG_TITLE = "title";
    private static final String TAG_POSTS = "posts";

    private JSONArray mComments = null;

    private ArrayList<HashMap<String, String>> mCommentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);
    }

    public void updateJSONdata() {

    mCommentList = new ArrayList<HashMap<String, String>>();
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.getJSONFromUrl(READ_DB_URL);

    try{
        mComments = json.getJSONArray(TAG_POSTS);

        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            String title = c.getString(TAG_TITLE);

        HashMap<String, String> map = new HashMap<String, String>();

        map.put(TAG_TITLE, title);

        mCommentList.add(map);
    }
    } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void updateList() {

        ListAdapter adapter = new SimpleAdapter(this, mCommentList, 
        R.layout.post, new String[] { TAG_TITLE}, 
        new int[] { R.id.title,});

        setListAdapter(adapter);

        ListView lv = getListView();    
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                    }
                });
            }

    public class LoadComments extends AsyncTask<Void, Void, Boolean>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Menu.this);
            pDialog.setMessage("Loading Comments...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            updateJSONdata();
            return null;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            updateList();
        }
    }
    }
    package com.example.test;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.util.Log;

    public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

       // constructor
       public JSONParser() {

       }


     public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

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

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to 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 the JSON Object.
        return jObj;

        }


        // function get json from url
       // by making HTTP POST or GET mehtod
       public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

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

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                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
        return jObj;

         }
        }
package com.example.test;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.utils.URLEncodedUtils;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.util.Log;
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
公共JSONObject getJSONFromUrl(最终字符串url){
//发出HTTP请求
试一试{
//构造客户端和HTTP请求。
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
//执行POST请求并在本地存储响应。
HttpResponse HttpResponse=httpClient.execute(httpPost);
//从响应中提取数据。
HttpEntity HttpEntity=httpResponse.getEntity();
//打开包含数据内容的inputStream。
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
//创建一个BufferedReader以通过inputStream进行解析。
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
//声明字符串生成器以帮助解析。
StringBuilder sb=新的StringBuilder();
//声明一个字符串以字符串形式存储JSON对象数据。
字符串行=null;
//构建字符串直到为null。
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
//关闭inpu