1

我有使用 asynctask 从 URL 下载 JSON 数据并将其传递给新活动的启动活动,女巫需要解析它并填充列表视图,但是在下载应用程序崩溃后,在日志聊天中说它无法将字符串转换为 json 对象,这里是飞溅活动代码

public class Init extends Activity {

static final String DEFAULT_URL = "http://api.androidhive.info/music/music.xml";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.init);

    WebView loader = (WebView) findViewById(R.id.loader);
    loader.loadUrl("file:///android_asset/index.html");

    new LoadingTask().execute(DEFAULT_URL);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public class LoadingTask extends AsyncTask<String, Object, Object>{
    XMLParser parser = new XMLParser();
    JSONParser jParser = new JSONParser();
    @Override
    protected Object doInBackground(String... params) {
        // TODO Auto-generated method stub
        String URL = params[0];
        JSONObject json = jParser.getJSONFromUrl(URL);
        //String xml = parser.getXmlFromUrl(URL); // getting XML from URL
         // getting DOM element
        return json;
    }

    protected void onPostExecute(Object result){
        Intent startApp = new Intent("com.example.androidhive.HOME");
        startApp.putExtra("json", result.toString());
        startActivity(startApp);
        //finish();
    }       
   }
 }

这是主要活动的来源

public class Home extends Activity {
    // All static variables

    // XML node keys
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";

    public static final String TAG_NEWS = "news";
    public static final String TAG_ID = "id";
    public static final String TAG_TITLE = "title";
    public static final String TAG_STORY = "story";
    public static final String TAG_SH_STORY = "shorten";
    public static final String TAG_DATETIME = "datetime";
    public static final String TAG_AUTHOR = "author";
    public static final String TAG_IMG = "img";

    ListView list;
    LazyAdapter adapter;
    Button mBtnNaslovnica;
    private ViewSwitcher viewSwitcher;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
        mBtnNaslovnica.setSelected(true);
        TextView txtView=(TextView) findViewById(R.id.scroller);
    txtView.setSelected(true);              

            ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();             

                JSONObject jsonobj;
                try {
                    jsonobj = new JSONObject(getIntent().getStringExtra("json"));
                    JSONArray news = jsonobj.getJSONArray(TAG_NEWS);
                    for(int i = 0; i < news.length(); i++){
                        JSONObject c = news.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String title = c.getString(TAG_TITLE);
                        String story = c.getString(TAG_STORY);
                        String shorten = c.getString(TAG_SH_STORY);
                        String author = c.getString(TAG_AUTHOR);
                        String datetime = c.getString(TAG_DATETIME);
                        String img = c.getString(TAG_IMG);


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

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_TITLE, title);
                        map.put(TAG_SH_STORY, shorten);
                        map.put(TAG_IMG, img);
                        map.put(TAG_AUTHOR, author);

                        // adding HashList to ArrayList
                        homeList.add(map);}
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }               

            list=(ListView)findViewById(R.id.list);

            // Getting adapter by passing xml data ArrayList
            adapter=new LazyAdapter(this, homeList);        
            list.setAdapter(adapter);


            // Click event for single list row
            list.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                    String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
                    String cur_artis = ((TextView) view.findViewById(R.id.artist)).getText().toString();
                    String cur_duration  = ((TextView) view.findViewById(R.id.duration)).getText().toString();
                    ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
                    String cur_img_url = (String) cur_img.getTag();

                    Intent i = new Intent("com.example.androidhive.CURENTNEWS");
                    i.putExtra("CUR_TITLE", cur_title);
                    i.putExtra("CUR_ARTIS", cur_artis);
                    i.putExtra("CUR_DURATION", cur_duration);
                    i.putExtra("CUR_IMG_URL", cur_img_url);
                    startActivity(i);
                }
            });     
        }               
    }

这是包含适配器的类的来源

public class LazyAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader; 

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}



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

public Object getItem(int position) {
    return position;
}

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

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_row, null);

    TextView title = (TextView)vi.findViewById(R.id.title); // title
    TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
    TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

    HashMap<String, String> n = new HashMap<String, String>();
    n = data.get(position);

    // Setting all values in listview
    title.setText(n.get(Home.TAG_TITLE));
    artist.setText(n.get(Home.TAG_AUTHOR));
    duration.setText(n.get(Home.TAG_DATETIME));
    thumb_image.setTag(n.get(Home.TAG_IMG));
    imageLoader.DisplayImage(n.get(Home.TAG_IMG), thumb_image);
    return vi;
  }
}

这是日志聊天

 08-31 14:34:41.066: V/xcli2(2349): DnsResolver.createDnsResolver() ok in run of WebCoreThread
08-31 14:34:42.546: E/JSON Parser(2349): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
08-31 14:34:42.546: W/dalvikvm(2349): threadid=1: thread exiting with uncaught exception (group=0x400207d8)
08-31 14:34:42.546: E/AndroidRuntime(2349): FATAL EXCEPTION: main
08-31 14:34:42.546: E/AndroidRuntime(2349): java.lang.NullPointerException
08-31 14:34:42.546: E/AndroidRuntime(2349):     at com.example.androidhive.Init$LoadingTask.onPostExecute(Init.java:58)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at android.os.AsyncTask.finish(AsyncTask.java:417)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at android.os.Looper.loop(Looper.java:123)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at android.app.ActivityThread.main(ActivityThread.java:4645)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at java.lang.reflect.Method.invokeNative(Native Method)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at java.lang.reflect.Method.invoke(Method.java:521)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
08-31 14:34:42.546: E/AndroidRuntime(2349):     at dalvik.system.NativeStart.main(Native Method)
4

2 回答 2

3

Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject

从这个apihttp://api.androidhive.info/music/music.xml看来没有JSONObject 你,最好看看android-xml-parsing-tutorial

于 2012-08-31T12:53:17.987 回答
1

你好请看看这个。

>     ?xml of type java.lang.String cannot be converted to JSONObject
>     You can not change xml to json object.If work on json then you have to use json object and json array.

请有一个链接可能对你有帮助。 http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/

于 2012-08-31T13:15:01.770 回答