簡體   English   中英

Android JSON 解析崩潰應用

[英]Android JSON Parsing Crashing Application

我正在使用 JSON 解析器將我的 JSON 數據放入列表視圖中。 當我加載視圖時,它會立即使應用程序崩潰。 正如您在我的代碼中看到的,我還有一些注釋代碼添加到應用程序內的列表中,如果我更改代碼以使用它,它可以正常工作,因此它表明它與布局或列表視圖無關與從 JSON 文件中獲取信息有關。

我將發布我所有的代碼以及我從 android studio 調試器獲得的錯誤日志。

謝謝

錯誤日志

01-31 10:50:41.117: I/MicroDetectionWorker(2115): Micro detectionmode: [mDetectionMode: [1]]. 
01-31 10:50:41.117:I/AudioController(2115): Using mInputStreamFactoryBuilder 01-31
10:50:41.124: I/MicroRecognitionRunner(2115): Starting detection.
01-31 10:50:41.124: I/MicrophoneInputStream(2115): mic_starting com.google.android.apps.gsa.staticplugins.z.c@a4038dd 01-31
10:50:41.125: W/APM_AudioPolicyManager(1292): getInputForAttr() failed opening input: samplingRate 16000, format 1, channelMask 10 01-31
10:50:41.126: E/AudioRecord(2115): Could not get audio input for session 2145, record source 1999, sample rate 16000, format 0x1,channel mask 0x10, flags 0 01-31 
10:50:41.127:E/AudioRecord-JNI(2115): Error creating AudioRecord instance: initialization check failed with status -22. 01-31 10:50:41.127:E/android.media.AudioRecord(2115): Error code -20 when initializingnative AudioRecord object. 01-31 
10:50:41.127:I/MicrophoneInputStream(2115): mic_startedcom.google.android.apps.gsa.staticplugins.z.c@a4038dd 01-31
10:50:41.128: E/ActivityThread(2115): Failed to find provider info forcom.google.android.apps.gsa.testing.ui.audio.recorded 01-31
10:50:41.128: I/MicroDetectionWorker(2115): onReady 01-31
10:50:41.133: I/MicrophoneInputStream(2115): mic_closecom.google.android.apps.gsa.staticplugins.z.c@a4038dd 01-31
10:50:41.133: I/MicroRecognitionRunner(2115): Detection finished 01-31
10:50:41.133: W/ErrorReporter(2115): reportError [type: 211, code:524300]: Error reading from input stream 01-31 
10:50:41.134:I/MicroRecognitionRunner(2115): Stopping hotword detection. 01-31
10:50:41.134: W/ErrorProcessor(2115):onFatalError, processing errorfrom engine(4) 01-31 10:50:41.134: W/ErrorProcessor(2115):
com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream 01-31 10:50:41.134: W/ErrorProcessor(2115):  at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
01-31 10:50:41.134: W/ErrorProcessor(2115): at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
01-31 10:50:41.134: W/ErrorProcessor(2115): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
01-31 10:50:41.134: W/ErrorProcessor(2115): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 01-31
10:50:41.134: W/ErrorProcessor(2115): at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
01-31 10:50:41.134: W/ErrorProcessor(2115): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
01-31 10:50:41.134: W/ErrorProcessor(2115): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
01-31 10:50:41.134: W/ErrorProcessor(2115): atjava.lang.Thread.run(Thread.java:761) 01-31 10:50:41.134:
W/ErrorProcessor(2115): at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
01-31 10:50:41.134: W/ErrorProcessor(2115): Caused by:com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space. 01-31
10:50:41.134: W/ErrorProcessor(2115): at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531) 01-31
10:50:41.134: W/ErrorProcessor(2115): at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555) 01-31
10:50:41.134: W/ErrorProcessor(2115): at java.io.InputStream.read(InputStream.java:101) 01-31 10:50:41.134:
W/ErrorProcessor(2115): at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362) 01-31
10:50:41.134: W/ErrorProcessor(2115): at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
01-31 10:50:41.134: W/ErrorProcessor(2115): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
01-31 10:50:41.134: W/ErrorProcessor(2115): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 01-31
10:50:41.134: W/ErrorProcessor(2115): at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
01-31 10:50:41.134: W/ErrorProcessor(2115): at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)

Main2Activity.java

package com.example.curtisboylan.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.TextView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

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

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;



public class Main2Activity extends AppCompatActivity {

    ListView simpleList;
    ArrayList<Item> animalList = new ArrayList<>();

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

        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        TextView tv = (TextView) findViewById(R.id.textView2);
        tv.setText(message);

        simpleList = (ListView) findViewById(R.id.simpleListView);
          //animalList.add(new Item("Lion",R.drawable.testimage));
        // animalList.add(new Item("Tiger",R.drawable.testimage));
        // animalList.add(new Item("Monkey",R.drawable.testimage));
        // animalList.add(new Item("Elephant",R.drawable.testimage));
        // animalList.add(new Item("Dog",R.drawable.testimage));
        // animalList.add(new Item("Cat",R.drawable.testimage));

         MyAdapter myAdapter=new MyAdapter(this,R.layout.list_view_items,this.fetchData());
          simpleList.setAdapter(myAdapter);
    }

    public ArrayList<Item> fetchData() {
        ArrayList<Item> listItems = new ArrayList<Item>();

        try {
            URL twitter = new URL(
                    "http://curtisboylan.me/test.json");
            URLConnection tc = twitter.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(tc
                    .getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
                System.out.println(line);
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    listItems.add(new Item(jo.getString("name"),R.drawable.testimage));
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block e.printStackTrace(); } catch
        } catch (IOException e) { // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (JSONException e) { // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return listItems;
    }
}

我的適配器

package com.example.curtisboylan.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

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

import java.util.List;

public class MyAdapter extends ArrayAdapter<Item> {

    public MyAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        // TODO Auto-generated constructor stub
    }

    private List<Item> items;

    public MyAdapter(Context context, int resource, ArrayList<Item> objects) {

        super(context, resource, objects);

        this.items = objects;
    }
    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.list_view_items, null);
        TextView textView = (TextView) v.findViewById(R.id.textView);
        ImageView imageView = (ImageView) v.findViewById(R.id.imageView);
        textView.setText(items.get(position).getAnimalName());
        imageView.setImageResource(items.get(position).getAnimalImage());
        return v;

    }


}

項目.java

package com.example.curtisboylan.myapplication;

/**
 * Created by curtisboylan on 31/01/2017.
 */

public class Item {

    String animalName;
    int animalImage;

    public Item(String animalName,int animalImage)
    {
        this.animalImage=animalImage;
        this.animalName=animalName;
    }
    public String getAnimalName()
    {
        return animalName;
    }
    public int getAnimalImage()
    {
        return animalImage;
    }
}

URL 的內容是一個 JSON 對象,它不是一個數組。 但是,您使用的是JSONArray(line) 不過,您應該嘗試將其視為 JSON 對象。

我的最終建議是閱讀所有內容,然后一次解析整個內容,而不是逐行解析。 否則,您的代碼可能會嘗試解析非 JSON 數據,以防將對象拆分為多行。

更改此代碼

String line;
while ((line = in.readLine()) != null) {
       JSONArray ja = new JSONArray(line);
       System.out.println(line);
       for (int i = 0; i < ja.length(); i++) {
             JSONObject jo = (JSONObject) ja.get(i);
             listItems.add(new Item(jo.getString("name"),R.drawable.testimage));
       }
}

用下面的代碼

StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
       sb.append(line);
       break;
}

in.close();

在此之后你應該解析String json = sb.toString(); json。 順便說一句,它是無效的 JSON。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM