如何解析JSON文件在android?JSON文件位于WAMP服务器中.做不到



我在android应用程序中做JSON解析。我想解析位于WAMP服务器上的JSON文件。我正在传递JSON文件的url。我在安卓代码中没有任何错误,但我不知道…每当我运行android应用程序时,它就会被强制关闭。

This My JSONParse类通过传递url解析JSON

package com.example.notificationjson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
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(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            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;
    }
}

这个JSON文件url: localhost:8080/BestVoyage_PHP/webservices/notification.json这是我的JSON文件输出:{"posts":[{"notification":"Opening shortly in Surat and Jamnagar"},{"notification":"Our New destinations are brazil, argentina, beijing, shanghai, and Scandianvian Countries"}]}

这是我的活动类,我在listview中显示JSON数据

package com.example.notificationjson;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends ListActivity {
private static String url = "http://10.0.2.2:8080/BestVoyage_PHP/webservices/notification.json";
    // JSON Node names
    private static final String TAG_POSTS = "posts";
    private static final String TAG_NOTIFICATION = "notification";
    // contacts JSONArray
    JSONArray posts = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(url, "urlurl");
        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting Array of Contacts
            posts = json.getJSONArray(TAG_POSTS);
            // looping through All Contacts
            for(int i = 0; i < posts.length(); i++){
                JSONObject c = posts.getJSONObject(i);
                // Storing each json item in variable
                String notification = c.getString(TAG_NOTIFICATION);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                // adding each child node to HashMap key => value
                map.put(TAG_NOTIFICATION, notification);
                // adding HashList to ArrayList
                contactList.add(map);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item,
                new String[] {TAG_NOTIFICATION}, new int[] {R.id.notification});
        setListAdapter(adapter);
        // selecting single ListView item
        ListView lv = getListView();
        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String noti = ((TextView) view.findViewById(R.id.notification)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(TAG_NOTIFICATION, noti);
                startActivity(in);
            }
        });

    }

}

这是logcat:

01-01 23:10:37.105: D/AndroidRuntime(730): Shutting down VM
01-01 23:10:37.105: W/dalvikvm(730): threadid=1: thread exiting with uncaught exception (group=0x40015560)
01-01 23:10:37.125: E/AndroidRuntime(730): FATAL EXCEPTION: main
01-01 23:10:37.125: E/AndroidRuntime(730): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notificationjson/com.example.notificationjson.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.os.Looper.loop(Looper.java:123)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-01 23:10:37.125: E/AndroidRuntime(730):  at java.lang.reflect.Method.invokeNative(Native Method)
01-01 23:10:37.125: E/AndroidRuntime(730):  at java.lang.reflect.Method.invoke(Method.java:507)
01-01 23:10:37.125: E/AndroidRuntime(730):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-01 23:10:37.125: E/AndroidRuntime(730):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-01 23:10:37.125: E/AndroidRuntime(730):  at dalvik.system.NativeStart.main(Native Method)
01-01 23:10:37.125: E/AndroidRuntime(730): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.ListActivity.onContentChanged(ListActivity.java:243)
01-01 23:10:37.125: E/AndroidRuntime(730):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:210)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.Activity.setContentView(Activity.java:1657)
01-01 23:10:37.125: E/AndroidRuntime(730):  at com.example.notificationjson.MainActivity.onCreate(MainActivity.java:40)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-01 23:10:37.125: E/AndroidRuntime(730):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-01 23:10:37.125: E/AndroidRuntime(730):  ... 11 more

当您的活动启动时,问题已经发生了(尚未涉及JSON解析)。扩展了ListActivity类。这个类要求你在你的布局中定义一个id为android.R.id.list的ListView。

您可以从日志目录中的这一行看到:

Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

它来自你的接口XML,你的ListView必须被称为list如果你要扩展ListActivity

相关内容

  • 没有找到相关文章

最新更新