使用JSON的图像自动滑块

时间:2014-10-09 05:25:09

标签: android json

制作图片 auto slider,我已编写代码to parse JSON但仍使用drawable张图片

其实我是concern,如何在幻灯片中使用online images而不是drawables

clear给我,因为如果将来same kind 问题,我将能够make changes

检查下面的代码:

public class MainActivity extends Activity {

ArrayList<Actors> actorsList;
public int currentimageindex = 0;
ImageView slidingimage;

// using drawable images
// in place of these static images, how can i use my arraylist 
// along with DownloadImageTask class, i have written posted below
private int[] IMAGE_IDS = {
        R.drawable.splash0,
        R.drawable.splash1, 
        R.drawable.splash2,
        R.drawable.splash3
    };

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

    actorsList = new ArrayList<Actors>();
    // execute AsyncTask
    new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");

    // handler to set duration and to upate animation
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {             
            AnimateandSlideShow();              
        }
    };

    int delay = 0000;
    int period = 4000;

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

    public void run() {
         mHandler.post(mUpdateResults);
    }
    }, delay, period);
}

// AsyncTask to get data from server
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

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

    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            //------------------>>
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);


                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("actors");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    Actors actor = new Actors();

                    actor.setImage(object.getString("image"));
                    Log.d("image: ", object.getString("image"));

                    actorsList.add(actor);

                }
                return true;
            }

            //------------------>>

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
        if(result == false)
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
    }
}

// method to show slide show
private void AnimateandSlideShow() {
    slidingimage = (ImageView)findViewById(R.id.ImageView3_Left);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);           
    currentimageindex++;                
}

// method to dowload online images
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
        }
    }
}

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <ImageView
        android:id="@+id/ImageView3_Left"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" />

</RelativeLayout>

logcat的:

10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/cruise.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/johnny.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/jolie.jpg
10-09 05:21:34.666: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/tom.jpg
10-09 05:21:34.666: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/will.jpg

1 个答案:

答案 0 :(得分:5)

这是我的代码。我使用View Flipper

public class MainActivity extends Activity {

ArrayList<String> actorsList;
ViewFlipper viewFlipper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
    actorsList = new ArrayList<String>();
    // execute AsyncTask
    new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");

    // handler to set duration and to upate animation
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            AnimateandSlideShow();
        }
    };

    int delay = 500;
    int period = 4000;

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            mHandler.post(mUpdateResults);
        }
    }, delay, period);



}

  // AsyncTask to get data from server
  class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

ProgressDialog dialog;

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = new ProgressDialog(MainActivity.this);
    dialog.setMessage("Loading, please wait");
    dialog.setTitle("Connecting server");
    dialog.show();
    dialog.setCancelable(false);
}

@Override
protected Boolean doInBackground(String... urls) {
    try {

        //------------------>>
        HttpGet httppost = new HttpGet(urls[0]);
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);

        // StatusLine stat = response.getStatusLine();
        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);


            JSONObject jsono = new JSONObject(data);
            JSONArray jarray = jsono.getJSONArray("actors");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

              //  Actors actor = new Actors();
                actorsList.add(object.getString("image"));
             //   actor.setImage(object.getString("image"));
                Log.d("image: ", object.getString("image"));

             //   actorsList.add(actor);

            }
            return true;
        }

        //------------------>>

    } catch (ParseException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return false;
}

protected void onPostExecute(Boolean result) {
    dialog.cancel();
    if(result == false){
        Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
    else{
        setFlipperImage( actorsList);
       }
    }
  }
  private void setFlipperImage(ArrayList<String> actorsList) {

 for(int i=0;i<actorsList.size();i++){
 Log.i("Set Filpper Called", actorsList.get(i).toString()+"");
 ImageView image = new ImageView(getApplicationContext());
// image.setBackgroundResource(res);
Picasso.with(MainActivity.this)
.load(actorsList.get(i).toString())
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.into(image);
 viewFlipper.addView(image);
 }
}
// method to show slide show
 private void AnimateandSlideShow() {
 viewFlipper.showNext();
 }}
  

我使用Picasso来加载图像......