简体   繁体   中英

Android JSON Parsing Crashing Application

I am using a JSON Parser to put my JSON data into a list view. 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.

I will post all my code along with the error logs I am getting from android studio debugger.

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

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

The content of the URL is a JSON object, it is not an array. However, you are using JSONArray(line) . You should try considering it as a JSON object though.

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.

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(); json. And BTW, it is Invalid JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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