android Arraylist.add无法在AsyncTask

时间:2015-09-17 04:58:18

标签: android json arraylist

我正在尝试解析json数据,添加arraylist并将其传递给listview。但是当我尝试使用android AsyncTask Arraylist.add函数中的doInBackground将项添加到列表时,它无效。当我尝试从列表中读取数据时,我的屏幕崩溃了。

public class QueueManagement extends Activity {

    String queueUrl = "http://dev.woofyz.com/api/pet/queue";

    ListView list;
    ArrayList<String> petImage = new ArrayList<String>();
    ArrayList<String> petName = new ArrayList<String>();
    ArrayList<String> petSpecie = new ArrayList<String>();
    ArrayList<String> petBreed = new ArrayList<String>();
    ArrayList<String> petAge = new ArrayList<String>();
    ArrayList<String> petOwner = new ArrayList<String>();
    ArrayList<String> petToken = new ArrayList<String>();

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

        //TOP MENU
        CustomActionBar customAactionBar = new CustomActionBar(QueueManagement.this);
        ActionBar actionBar = customAactionBar.getActionBar();
        actionBar.setCustomView(R.layout.custom_queue_menu);

        //SETTING VALUE IN NAV SPINNER
        MenuSpinner mspinner = new MenuSpinner(QueueManagement.this);
        ArrayAdapter dataAdapter = mspinner.getQueueSpinner();
        Spinner spinner = (Spinner) findViewById(R.id.righttext);
        spinner.setAdapter(dataAdapter);

        //MAKE DOCTOR PROFILE CIRCULAR
        ImageView imageView = (ImageView) findViewById(R.id.doctorProfilepic);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.doctor);
        RoundImage roundImage = new RoundImage();
        Bitmap circle = roundImage.getRoundImage(bitmap);
        imageView.setImageBitmap(circle);
    }

    @Override
    protected void onResume() {
        super.onResume();
        new AsyncCaller().execute();
    }

    private class AsyncCaller extends AsyncTask<Void, Void, Void> {
       ProgressDialog pdLoading = new ProgressDialog(QueueManagement.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdLoading.setMessage("\tLoading...");
            pdLoading.show();
        }

        @Override
        protected Void doInBackground(Void... params) {

            JsonParser jParser = new JsonParser();  
            JSONArray json = jParser.getJsonFromUrl(queueUrl);

            for (int i = 0; i < json.length(); i++) {
                try {
                     JSONObject jo = json.getJSONObject(i);
                    //petImage.add(jo.getString("image"));
                    petName.add(jo.getString("name"));
                    //petSpecie.add(jo.getString("species"));
                    //petBreed.add(jo.getString("breed"));
                    //petAge.add(jo.getString("age"));
                    //petOwner.add(jo.getString("owner"));
                    //petToken.add(jo.getString("token"));
                }catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            pdLoading.dismiss();
            CustomQueueListview adapter = new CustomQueueListview(QueueManagement.this,petImage,petName,petSpecie,petBreed,petAge,petOwner,petToken);
            list=(ListView)findViewById(R.id.queuelist);
            list.setAdapter(adapter);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // INFLATE THE MENU
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.queue_menu, menu);
        return true;
    }

    @Override
    public void onStart() {
        super.onStart();

        TextView name = (TextView) findViewById(R.id.doctorname);
        name.setText(petName.get(0));

        //FILTER  ClICK
        ImageView filter = (ImageView) findViewById(R.id.filter);
        filter.setOnClickListener(new View.OnClickListener() {
            public void onClick(View myView){
                CustomPopup popup = new CustomPopup(QueueManagement.this);
                popup.getFilterPopup();
            }
        });

        //SENDNEXT  ClICK
        Button sendNext = (Button) findViewById(R.id.sendnext);
        sendNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View myView){
                Intent intent = new Intent(QueueManagement.this, PetProfile.class);
                startActivity(intent);
            }
        });
    }

}

这是我的json解析器代码

public class JsonParser {

    static InputStream is = null;
    static JSONArray jarray = null;
    static String json = "";

    public JsonParser() {

    }

    public JSONArray getJsonFromUrl(String url) {

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpPost = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();    
        } catch (Exception e) {
            e.printStackTrace();
        }


        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            json = sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        // try parse the string to a JSON ARRAY
        try {
            jarray = new JSONArray(json);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // return JSON ARRAY
        return jarray;
    }

}

这是我的logcat

E/AndroidRuntime(13507):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
E/AndroidRuntime(13507):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
E/AndroidRuntime(13507):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
E/AndroidRuntime(13507):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
E/AndroidRuntime(13507):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(13507):    at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(13507):    at android.app.ActivityThread.main(ActivityThread.java:5086)
E/AndroidRuntime(13507):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13507):    at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(13507):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
E/AndroidRuntime(13507):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
E/AndroidRuntime(13507):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(13507): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
E/AndroidRuntime(13507):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
E/AndroidRuntime(13507):    at java.util.ArrayList.get(ArrayList.java:308)
E/AndroidRuntime(13507):    at org.woofyz.QueueManagement.onStart(QueueManagement.java:145)
E/AndroidRuntime(13507):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1194)
E/AndroidRuntime(13507):    at android.app.Activity.performStart(Activity.java:5258)
E/AndroidRuntime(13507):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2171)
E/AndroidRuntime(13507):    ... 11 more
E/cutils  (  245): Failed to mkdirat(/storage/sdcard1/Android): Read-only file system
E/chromium(16926): [ERROR:simple_index_file.cc(223)] Failed to write the temporary index file
E/chromium(16926): [ERROR:simple_index_file.cc(223)] Failed to write the temporary index file
E/chromium_android_linker(13558): Open: Could not open libchrome.so: Could not map at 0x54b7f000 requested, backing out
E/chromium_android_linker(13558): Unable to load library: libchrome.so
E/libEGL  (13558): validate_display:254 error 3008 (EGL_BAD_DISPLAY)
E/libEGL  (13558): validate_display:254 error 3008 (EGL_BAD_DISPLAY)
E/OMXMaster(13558): A component of name 'OMX.qcom.audio.decoder.aac' already exists, ignoring this one.
E/cutils  (  245): Failed to mkdirat(/storage/sdcard1/Android): Read-only file system
E/NetworkScheduler.SchedulerReceiver( 1351): Invalid parameter app
E/NetworkScheduler.SchedulerReceiver( 1351): Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
E/AuthorizationBluetoothService( 1351): Proximity feature is not enabled.
E/AuthorizationBluetoothService( 1351): Proximity feature is not enabled.
E/dalvikvm(13849): Could not find class 'android.telecom.TelecomManager', referenced from method com.google.android.gms.wearable.service.y.a
E/MDM     ( 1237): [79] b.run: Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}
E/MDM     ( 1237): [79] b.run: Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}
E/ActivityThread(13818): Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider
E/ActivityThread(13818): Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider
E/dalvikvm(13898): Could not find class 'android.app.Notification$Action$Builder', referenced from method g.a
E/dalvikvm(13898): Could not find class 'android.app.RemoteInput$Builder', referenced from method g.a
E/dalvikvm(13898): Could not find class 'android.app.Notification$Action$Builder', referenced from method g.a
E/dalvikvm(13898): Could not find class 'android.text.style.TtsSpan', referenced from method g.a
E/dalvikvm(13898): Could not find class 'ax', referenced from method g.a
E/dalvikvm(13898): Could not find class 'az', referenced from method g.a
E/dalvikvm(13898): Could not find class 'android.app.RemoteInput[]', referenced from method g.a
E/dalvikvm(13898): Could not find class 'com.google.android.apps.hangouts.telephony.TeleConnectionService', referenced from method g.l
E/dalvikvm(13898): Could not find class 'android.telecom.TelecomManager', referenced from method g.n
E/SQLiteLog(13898): (1) no such table: mmsconfig
E/Babel_SMS(13898): canonicalizeMccMnc: invalid mccmnc nullnull
E/dalvikvm(13898): Could not find class 'fzc', referenced from method com.google.android.libraries.hangouts.video.sdk.ScreenVideoCapturer.<init>
E/dalvikvm(13898): Could not find class 'android.telecom.PhoneAccount$Builder', referenced from method dry.f
E/dalvikvm(13898): Could not find class 'android.telecom.TelecomManager', referenced from method dry.i
E/chromium(16926): [ERROR:simple_index_file.cc(223)] Failed to write the temporary index file
E/chromium(16926): [ERROR:simple_index_file.cc(223)] Failed to write the temporary index file
E/libEGL  (13974): validate_display:254 error 3008 (EGL_BAD_DISPLAY)
E/libEGL  (13974): validate_display:254 error 3008 (EGL_BAD_DISPLAY)
E/OMXMaster(13974): A component of name 'OMX.qcom.audio.decoder.aac' already exists, ignoring this one.
E/MDMCTBK (  583): MdmCutbackHndler,Could not open ''
E/MDMCTBK (  583): MdmCutbackHndler,Could not open ''
E/audio_a2dp_hw(  260): adev_set_parameters: ERROR: set param called even when stream out is null
E/chromium(16926): [ERROR:simple_index_file.cc(223)] Failed to write the temporary index file
E/chromium(16926): [ERROR:get_updates_processor.cc(243)] PostClientToServerMessage() failed during GetUpdates
E/pIntent (18302): started scanning called
E/MDMCTBK (  583): MdmCutbackHndler,Could not open ''
E/MDMCTBK (  583): MdmCutbackHndler,Could not open ''
E/WakeLock(13053): callingPackage is not supposed to be empty for wakelock Config Service fetch!
E/pIntent (18302): started scanning called

1 个答案:

答案 0 :(得分:0)

为了解析JSON对象,我们将创建一个类JSONObject的对象,并指定一个包含JSON数据的字符串。它的语法是:

String in;
JSONObject reader = new JSONObject(in);

最后一步是解析JSON。 JSON文件由具有不同键/值对e.t.c的不同对象组成。所以JSONObject有一个单独的函数来解析JSON文件的每个组件。其语法如下:

JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");

JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");

方法getJSONObject返回JSON对象。方法getString返回指定键的字符串值。

对于教程,你可以see这个