简体   繁体   English

Android JSON 解析崩溃应用

[英]Android JSON Parsing Crashing Application

I am using a JSON Parser to put my JSON data into a list view.我正在使用 JSON 解析器将我的 JSON 数据放入列表视图中。 When I load up the view it crashes the application straight away.当我加载视图时,它会立即使应用程序崩溃。 As you can see in my code I also have some commented code that adds to a list inside the app and if I change the code to use that it works fine so it shows that it is nothing to do with the layout or list view its just to do with getting the information from the JSON file.正如您在我的代码中看到的,我还有一些注释代码添加到应用程序内的列表中,如果我更改代码以使用它,它可以正常工作,因此它表明它与布局或列表视图无关与从 JSON 文件中获取信息有关。

I will post all my code along with the error logs I am getting from android studio debugger.我将发布我所有的代码以及我从 android studio 调试器获得的错误日志。

Thanks谢谢

Error Log错误日志

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 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;
    }
}

MyAdapter.java我的适配器

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;

    }


}

Item.java项目.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;
    }
}

The content of the URL is a JSON object, it is not an array. URL 的内容是一个 JSON 对象,它不是一个数组。 However, you are using JSONArray(line) .但是,您使用的是JSONArray(line) You should try considering it as a JSON object though.不过,您应该尝试将其视为 JSON 对象。

And my final suggestion is to read all the content and then parse the whole at once, not line-by-line.我的最终建议是阅读所有内容,然后一次解析整个内容,而不是逐行解析。 Otherwise, your code may try to parse a non-JSON data in case the object is splitted into multiple lines.否则,您的代码可能会尝试解析非 JSON 数据,以防将对象拆分为多行。

Change this code更改此代码

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));
       }
}

with below code用下面的代码

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

in.close();

After this you should parse String json = sb.toString();在此之后你应该解析String json = sb.toString(); json. json。 And BTW, it is Invalid JSON.顺便说一句,它是无效的 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM