解析来自JSON响应的数据并填充到listview

时间:2014-01-01 06:51:59

标签: java android json listview

这是我的JSON结构

网址 ::

http://54.218.73.244:7004/DescriptionSortedPrice/

JSON ::

{
    "restaurants": [
        {
            "Sl_no": 1,
            "Person_Name": "salmanKhan",
            "Image_Name": "image.jpg"
        },

Adapter.java

public class Adapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public Adapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView name;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.single_item, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.title_textView_id);

        // Capture position and set results to the TextViews
        name.setText(resultp.get(MainActivity.NAME));


        return itemView;
    }
}

MainActivity.java

public class MainActivity extends Activity{
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    Adapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";


    String TYPE_FILTER;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.activity_main);

        listview = (ListView) findViewById(R.id.listView_id);

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();

            // Retrieve JSON Objects from the given URL address
            jsonobject = Parser.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put(MainActivity.NAME, jsonobject.getString("Person_Name"));

                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new Adapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

Parser.java

public class Parser {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        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();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

日志::

01-01 12:13:14.600: E/log_tag(715): Error in http connection java.net.SocketException: Permission denied
01-01 12:13:14.610: E/log_tag(715): Error converting result java.lang.NullPointerException
01-01 12:13:14.620: E/log_tag(715): Error parsing data org.json.JSONException: End of input at character 0 of 
01-01 12:13:14.660: W/dalvikvm(715): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-01 12:13:14.690: E/AndroidRuntime(715): FATAL EXCEPTION: AsyncTask #1
01-01 12:13:14.690: E/AndroidRuntime(715): java.lang.RuntimeException: An error occured while executing doInBackground()
01-01 12:13:14.690: E/AndroidRuntime(715):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.lang.Thread.run(Thread.java:1096)
01-01 12:13:14.690: E/AndroidRuntime(715): Caused by: java.lang.NullPointerException
01-01 12:13:14.690: E/AndroidRuntime(715):  at com.example.singleitemlistview.MainActivity$DownloadJSON.doInBackground(MainActivity.java:71)
01-01 12:13:14.690: E/AndroidRuntime(715):  at com.example.singleitemlistview.MainActivity$DownloadJSON.doInBackground(MainActivity.java:1)
01-01 12:13:14.690: E/AndroidRuntime(715):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-01 12:13:14.690: E/AndroidRuntime(715):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-01 12:13:14.690: E/AndroidRuntime(715):  ... 4 more
01-01 12:13:17.215: E/WindowManager(715): Activity com.example.singleitemlistview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@45fbe1e8 that was originally added here
01-01 12:13:17.215: E/WindowManager(715): android.view.WindowLeaked: Activity com.example.singleitemlistview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@45fbe1e8 that was originally added here
01-01 12:13:17.215: E/WindowManager(715):   at android.view.ViewRoot.<init>(ViewRoot.java:247)
01-01 12:13:17.215: E/WindowManager(715):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-01 12:13:17.215: E/WindowManager(715):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-01 12:13:17.215: E/WindowManager(715):   at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-01 12:13:17.215: E/WindowManager(715):   at android.app.Dialog.show(Dialog.java:241)
01-01 12:13:17.215: E/WindowManager(715):   at com.example.singleitemlistview.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
01-01 12:13:17.215: E/WindowManager(715):   at android.os.AsyncTask.execute(AsyncTask.java:391)
01-01 12:13:17.215: E/WindowManager(715):   at com.example.singleitemlistview.MainActivity.onCreate(MainActivity.java:41)
01-01 12:13:17.215: E/WindowManager(715):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-01 12:13:17.215: E/WindowManager(715):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-01 12:13:17.215: E/WindowManager(715):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-01 12:13:17.215: E/WindowManager(715):   at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-01 12:13:17.215: E/WindowManager(715):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-01 12:13:17.215: E/WindowManager(715):   at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 12:13:17.215: E/WindowManager(715):   at android.os.Looper.loop(Looper.java:123)
01-01 12:13:17.215: E/WindowManager(715):   at android.app.ActivityThread.main(ActivityThread.java:4627)
01-01 12:13:17.215: E/WindowManager(715):   at java.lang.reflect.Method.invokeNative(Native Method)
01-01 12:13:17.215: E/WindowManager(715):   at java.lang.reflect.Method.invoke(Method.java:521)
01-01 12:13:17.215: E/WindowManager(715):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-01 12:13:17.215: E/WindowManager(715):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-01 12:13:17.215: E/WindowManager(715):   at dalvik.system.NativeStart.main(Native Method)

从日志引用 ::

  • 第58行 :: mProgressDialog.show();
  • line41 :: new DownloadJSON()。execute();
  • line71 :: map.put(MainActivity.NAME,jsonobject.getString(“Person_Name”));

问题 ::我无法在列表视图中显示已解析的项目

3 个答案:

答案 0 :(得分:6)

您是否已获得清单中的许可

<uses-permission android:name="android.permission.INTERNET" />

因为从你的日志中得到了

http connection java.net.SocketException: Permission denied

如果您未授予互联网权限并尝试访问互联网,则会发生这种情况。

答案 1 :(得分:2)

从您的日志显示:

Error in http connection java.net.SocketException: Permission denied
Error converting result java.lang.NullPointerException
Error parsing data org.json.JSONException: End of input at character 0 of 

确保您已在清单中提供 INTERNET 权限。

 <uses-permission android:name="android.permission.INTERNET" />

还要更改您的适配器方法,如下所示:

@Override
public Object getItem(int position) {
    return data.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

答案 2 :(得分:0)

使用此代码块更新解析器

try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }