JSON已解析但未存储到所需的arraylist

时间:2017-10-17 03:53:13

标签: java android json arraylist android-asynctask

当我尝试在toast中显示json数据时,会解析json数据,但是arraylist仍为空。我该如何解决这个问题?

这是Asynctask解析json的代码

public class DownloadDetailImages extends AsyncTask<Void, Void, String> {

    Context context;
    ArrayList<String> arrayList = new ArrayList<>();
    String urlAddress;

    public DownloadDetailImages(Context context, ArrayList<String> arrayList, String urlAddress) {
        this.context = context;
        this.arrayList = arrayList;
        this.urlAddress = urlAddress;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String json) {
        super.onPostExecute(json);

        try {
            JSONArray jsonArray = new JSONArray(json);
            JSONObject jsonObject;

            arrayList.clear();

            for ( int i = 0; i < jsonArray.length(); i++ )
            {
                jsonObject = jsonArray.getJSONObject(i);

                String imageUrl = jsonObject.getString("ProductImage");
                arrayList.add(imageUrl);
            }

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

    @Override
    protected String doInBackground(Void... params) {
        HttpURLConnection httpURLConnection = Connector.connect(urlAddress);

        try{
            InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            StringBuffer jsonData = new StringBuffer();

            while((line = bufferedReader.readLine()) != null)
            {
                jsonData.append(line+"\n");
            }

            bufferedReader.close();
            inputStream.close();

            httpURLConnection.disconnect();

            return  jsonData.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

这是主要活动

public class MainActivity extends AppCompatActivity implements BaseSliderView.OnSliderClickListener,
        ViewPagerEx.OnPageChangeListener {

    SliderLayout sliderLayout;
    ArrayList<String> images = new ArrayList<String>();
    String urlAddress = "http://10.10.90.70/slider/sliderImage.php";


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

        sliderLayout = (SliderLayout) findViewById(R.id.slider);

        new DownloadDetailImages(this, images, urlAddress).execute();

        for (int i = 0; i < images.size(); i++) {
            TextSliderView textSliderView = new TextSliderView(MainActivity.this);
            textSliderView
                    .image(images.get(i).toString())
                    .setScaleType(BaseSliderView.ScaleType.Fit)
                    .setOnSliderClickListener(this);
            textSliderView.bundle(new Bundle());
            sliderLayout.addSlider(textSliderView);
        }

        sliderLayout.setPresetTransformer(SliderLayout.Transformer.Accordion);
        sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        sliderLayout.setCustomAnimation(new DescriptionAnimation());
        sliderLayout.setDuration(3000);
        sliderLayout.addOnPageChangeListener(this);

    }

    @Override
    protected void onStop() {
        sliderLayout.stopAutoCycle();
        super.onStop();
    }

    @Override
    public void onSliderClick(BaseSliderView slider) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        Log.d("Slider Demo", "Page Changed: " + position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

}

这是我用来连接webserver的类 公共类连接器{

public static HttpURLConnection connect(String urlAddress)
{
    try {
        URL url = new URL(urlAddress);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        //connection properties
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setConnectTimeout(3000);
        httpURLConnection.setReadTimeout(3000);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        return httpURLConnection;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

}

这是JSON响应

[{
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/mejakerja.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/mejakerja.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/fax.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/fax.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/kursikerja.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/kursikerja.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/printer.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/printer.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/projector.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/projector.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/scanner.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/scanner.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/brankas.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/brankas.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/copier.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/copier.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/copier1.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/copier1.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/PC.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/PC.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/PC1.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/PC1.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/laptop1.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/laptop1.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/laptop2.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/laptop2.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/nikon.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/nikon.jpg"
}, {
    "0": "http:\/\/10.10.90.70\/babex\/Gambar\/handycam.jpg",
    "ProductImage": "http:\/\/10.10.90.70\/babex\/Gambar\/handycam.jpg"
}]

谢谢。

2 个答案:

答案 0 :(得分:0)

试试这个

  public class MainActivity extends AppCompatActivity implements BaseSliderView.OnSliderClickListener,
            ViewPagerEx.OnPageChangeListener {

        SliderLayout sliderLayout;
        ArrayList<String> images = new ArrayList<String>();
        String urlAddress = "http://10.10.90.70/slider/sliderImage.php";


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

            sliderLayout = (SliderLayout) findViewById(R.id.slider);

            new DownloadDetailImages(this, images, urlAddress).execute();

            for (int i = 0; i < images.size(); i++) {
                TextSliderView textSliderView = new TextSliderView(MainActivity.this);
                textSliderView
                        .image(images.get(i).toString())
                        .setScaleType(BaseSliderView.ScaleType.Fit)
                        .setOnSliderClickListener(this);
                textSliderView.bundle(new Bundle());
                sliderLayout.addSlider(textSliderView);
            }

            sliderLayout.setPresetTransformer(SliderLayout.Transformer.Accordion);
            sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
            sliderLayout.setCustomAnimation(new DescriptionAnimation());
            sliderLayout.setDuration(3000);
            sliderLayout.addOnPageChangeListener(this);

        }

        @Override
        protected void onStop() {
            sliderLayout.stopAutoCycle();
            super.onStop();
        }

        @Override
        public void onSliderClick(BaseSliderView slider) {

        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Log.d("Slider Demo", "Page Changed: " + position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }

     class DownloadDetailImages extends AsyncTask<String, Void, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String json) {
            super.onPostExecute(json);

            try {
                JSONArray jsonArray = new JSONArray(json);
                JSONObject jsonObject;

                images.clear();

                for ( int i = 0; i < jsonArray.length(); i++ )
                {
                    jsonObject = jsonArray.getJSONObject(i);

                    String imageUrl = jsonObject.getString("ProductImage");
                    images.add(imageUrl);
                }

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

        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection httpURLConnection = Connector.connect(params[0]);

            try{
                InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                StringBuffer jsonData = new StringBuffer();

                while((line = bufferedReader.readLine()) != null)
                {
                    jsonData.append(line+"\n");
                }

                bufferedReader.close();
                inputStream.close();

                httpURLConnection.disconnect();

                return  jsonData.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

    }

    }

答案 1 :(得分:0)

当你访问arraylist时,

可能是你的asynctask类没有完成,检查asynctask是否完成,然后访问arraylist。