【问题标题】:Android JSON Parsing Crashing ApplicationAndroid JSON解析崩溃应用
【发布时间】:2017-01-31 10:52:40
【问题描述】:

我正在使用 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;
    }
}

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

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

【问题讨论】:

  • 你应该异步做网络请求?
  • @ManojFrekzz 我不确定,我以前在网上看到过这个示例,并且任何示例都具有相同类型的布局。我只是希望能够从 JSON 中获取信息。
  • 我的建议是使用 RecyclerView 而不是 ListView。 ListView 是一种旧视图,它的性能不是很好。这是一个如何使用它的例子。 androidhive.info/2016/01/android-working-with-recycler-view 另外,将 Retrofit 与 Gson 一起使用。 Retrofit 是一个网络库,Gson 是一个 JSON 解析器。它真的很容易使用。 square.github.io/retrofit

标签: java android json io inputstream


【解决方案1】:

URL 的内容是一个 JSON 对象,它不是一个数组。但是,您使用的是JSONArray(line)。不过,您应该尝试将其视为 JSON 对象。

我最后的建议是阅读所有内容,然后一次解析整个内容,而不是逐行解析。否则,您的代码可能会尝试解析非 JSON 数据,以防对象被拆分为多行。

【讨论】:

    【解决方案2】:

    更改此代码

    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。

    【讨论】:

      猜你喜欢
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多