如何刷新视图寻呼机在Android的? [英] How to refresh view pager in android?

查看:131
本文介绍了如何刷新视图寻呼机在Android的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的看法寻呼机一些图片,我的删除按钮删除图像,但在删除图像后,我要刷新视图寻呼机和并希望显示在我的应用程序剩下的图像任何一个可以有什么错?

I have some images in my view pager and i am deleting images from delete button,but after deleting image i want to refresh view pager and and want to display remaining image in my application can any one what is mistake?

public class PhotoView extends Activity{

private Button btn;
private String User_IDs;
private String total;
private String max;
ArrayList<Integer> userImgidArrayList;
ArrayList<String> userstatusArrayList;
ArrayList<String> userphotoArrayList;
private ImageView imageView;
private Button btndelete;
private Button btnsetprofilepic;
int singlepicid;
// Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();

private static final String DELT_SETPRO_URL = "my url";
private static final String DELT_SETPRO_STATUS = "status";
private static final String DELT_SETPRO_MSG = "msg";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.photoview);

    User_IDs=this.getIntent().getStringExtra("id");
    System.out.println("photo upload view user id"+User_IDs);
   IMAGE_URL="my url"+User_IDs;

    total=this.getIntent().getStringExtra("totals");
    System.out.println("photo total "+total);

    max=this.getIntent().getStringExtra("maxs");
    System.out.println("photo maximum "+max);

    userImgidArrayList = getIntent().getIntegerArrayListExtra("photoid");
    System.out.println(userImgidArrayList);

    userstatusArrayList=getIntent().getStringArrayListExtra("imgstatus");
    System.out.println(userstatusArrayList);

    userphotoArrayList=getIntent().getStringArrayListExtra("pics");
    System.out.println(userphotoArrayList);

    for(int i=0;i< userImgidArrayList.size();i++)
    {
        singlepicid=userImgidArrayList.get(i);
        System.out.println(singlepicid);
    }

    for(int i=0;i< userphotoArrayList.size();i++)
    {
        String singleimage=userphotoArrayList.get(i);
        System.out.println(singleimage);
    }

    for(int i=0;i< userstatusArrayList.size();i++)
    {
        String singlestatus=userstatusArrayList.get(i);
        System.out.println(singlestatus);

    }

    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
       ImageAdapter adapter = new ImageAdapter(this);
       viewPager.setAdapter(adapter);

  imageView = (ImageView) findViewById(R.id.full_image_views);

    btn=(Button)findViewById(R.id.goforupload);

    btn.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {

            Intent intent=new Intent(getApplicationContext(),PhotoUpload.class);
            intent.putExtra("id", User_IDs);
            startActivity(intent);

        }
    });

    btndelete=(Button)findViewById(R.id.deleteimage);
    btndelete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            singlepicid = userImgidArrayList.get(viewPager.getCurrentItem());


            new AttemptLogin().execute();
            userphotoArrayList.remove(viewPager.getCurrentItem());
             //  adapter.notifyDataSetChanged();
               viewPager.getAdapter().notifyDataSetChanged();
        }
    });
    btnsetprofilepic=(Button)findViewById(R.id.setprofilepic);
    btnsetprofilepic.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

}
public class ImageAdapter extends PagerAdapter {
     Context context;


      ImageAdapter(Context context)
     {
     this.context=context;
     }
      @Override
      public int getCount() {
      return userphotoArrayList.size();
      }

      @Override
        public void destroyItem(View container, int position, Object object) {
             ((ViewPager) container).removeView((View) object);
        }
     @Override
     public boolean isViewFromObject(View view, Object object) {
     return view == ((ImageView) object);
     }

     @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            int padding = context.getResources().getDimensionPixelSize(
                    R.dimen.activity_horizontal_margin);
            imageView.setPadding(padding, padding, padding, padding);
            //imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            Picasso.with(context).load(userphotoArrayList.get(position)).into(imageView);



            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }
     @Override
    public int getItemPosition(Object object) {


        viewPager.setAdapter(adapter);
        return POSITION_NONE;
    }


     }

class AttemptLogin extends AsyncTask<String, String, String> {

    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(PhotoView.this);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String...args) {
        //Check for success tag

        String btnmethod=btndelete.getTag().toString();
        /*String val=null;
        singlepicid=Integer.parseInt(val);*/
        Looper.prepare();

         try {
             //Building Parameters


             List<NameValuePair> params = new ArrayList<NameValuePair>();
             params.add(new BasicNameValuePair("user_login_id", User_IDs));
             params.add(new BasicNameValuePair("method", btnmethod));
             params.add(new BasicNameValuePair("user_photo_id", String.valueOf(singlepicid)));
             params.add(new BasicNameValuePair("version", "apps"));

             Log.d("request!", "starting");
             // getting product details by making HTTP request
             JSONObject json = jsonParser.makeHttpRequest (
                 DELT_SETPRO_URL, "POST", params);
             System.out.println(params);
             //check your log for json response
             Log.d("Processing", json.toString());

             JSONObject jobj = new JSONObject(json.toString());
             final String msg = jobj.getString("msg");

             System.out.println("MSG : " + msg);

             runOnUiThread(new  Runnable() 
             {
                @Override
                public void run() 
                {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                } 
            });
             return json.getString(DELT_SETPRO_STATUS);


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


    protected void onPostExecute(String file_url) {
        //dismiss the dialog once product deleted


        pDialog.dismiss();

}}

class LoadImages extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {


     String photoid;
     int  userPhotoId;
    String userstatus;
     String uploadedpics;

  @Override
  protected void onPreExecute() {
      super.onPreExecute();
      prDialog = new ProgressDialog(PhotoView.this);
      prDialog.setMessage("Refreshing...");
      prDialog.setIndeterminate(false);
      prDialog.setCancelable(false);
      prDialog.show();
  }
  protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
      ServiceHandler sh = new ServiceHandler();

      // Making a request to url and getting response
      ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
      String jsonStr = sh.makeServiceCall(IMAGE_URL, ServiceHandler.GET);

      Log.d("Response: ", "> " + jsonStr);


          try {
              jsonobj = new JSONObject(jsonStr);


                  // creating new HashMap
                  HashMap<String, String> map = new HashMap<String, String>();

                  // adding each child node to HashMap key => value
                  map.put(IMAGE_USERLOGIN_ID, jsonobj.getString(IMAGE_USERLOGIN_ID));
                  map.put(IMAGE_TOTAL_PHOTO,jsonobj.getString(IMAGE_TOTAL_PHOTO));
                  map.put(IMAGE_MAX_UPLOAD, jsonobj.getString(IMAGE_MAX_UPLOAD));


                  final String totalphota = jsonobj.getString("user_total_photo");
                  Log.d("Value: ", "> " + totalphota);
                  final String maximumphota = jsonobj.getString("max_upload_photo");
                  Log.d("Value: ", "> " + maximumphota);


                  userImgidArrayList = new ArrayList<Integer>();
                  image_list = (JSONArray) jsonobj.get("image_list");
                  for(int i=0;i< image_list.length();i++)
                  {
                     JSONObject imageListItem = image_list.getJSONObject(i);
                     userPhotoId = imageListItem.getInt("user_photo_id");
                     userImgidArrayList.add(userPhotoId);
                     Log.d("mylog", "i ="+i+" and user_photo_id =" + userPhotoId);
                  }

                  userstatusArrayList = new ArrayList<String>();
                  image_list = (JSONArray) jsonobj.get("image_list");
                  for(int i=0;i< image_list.length();i++)
                  {
                     JSONObject statusListItem = image_list.getJSONObject(i);
                     userstatus = statusListItem.getString("status");

                     userstatusArrayList.add(userstatus);
                     Log.d("mylog", "i ="+i+" and status =" + userstatus);
                  }

                  userphotoArrayList = new ArrayList<String>();
                  image_list = (JSONArray) jsonobj.get("image_list");
                  for(int i=0;i< image_list.length();i++)
                  {
                     JSONObject photoListItem = image_list.getJSONObject(i);

                     uploadedpics=photoListItem.getString("photo");
                     userphotoArrayList.add(uploadedpics);
                     Log.d("mylog", "i ="+i+" and photo =" + uploadedpics);
                  }


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


      return data;
  }


  protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

      super.onPostExecute(result);

      if (prDialog.isShowing())
          prDialog.dismiss();

  }

}

推荐答案

重写所有我的回答:

首先,让我们来看看的使用的AsyncTask ,这里是重要的功能:

Firstly , let's see the usage of AsyncTask, here is important functions:

/**
 * Override this method to perform a computation on a background thread. The
 * specified parameters are the parameters passed to {@link #execute}
 * by the caller of this task.
 *
 * This method can call {@link #publishProgress} to publish updates
 * on the UI thread.
 *
 * @param params The parameters of the task.
 *
 * @return A result, defined by the subclass of this task.
 *
 * @see #onPreExecute()
 * @see #onPostExecute
 * @see #publishProgress
 */
protected abstract Result doInBackground(Params... params);

/**
 * Runs on the UI thread before {@link #doInBackground}.
 *
 * @see #onPostExecute
 * @see #doInBackground
 */
protected void onPreExecute() {
}

/**
 * <p>Runs on the UI thread after {@link #doInBackground}. The
 * specified result is the value returned by {@link #doInBackground}.</p>
 * 
 * <p>This method won't be invoked if the task was cancelled.</p>
 *
 * @param result The result of the operation computed by {@link #doInBackground}.
 *
 * @see #onPreExecute
 * @see #doInBackground
 * @see #onCancelled(Object) 
 */
@SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}

现在,让我们来看看在的AsyncTask 你做了什么,的通知我有改变的模板的AsyncTask

Now , let's see what have you done in AsyncTask , Notice I have change the template of AsyncTask:

class AttemptLogin extends AsyncTask<String, String, int> {
    @Override
    protected void onPreExecute() {
        //Here you have show a dialog with loading message, that's great.
    }

    @Override
    protected int doInBackground(String...args) {
       //Here you send http request to delete data on server, and receive response from it.
       JSONObject json = jsonParser.makeHttpRequest (
             DELT_SETPRO_URL, "POST", params);
       System.out.println(params);
       //check your log for json response
       Log.d("Processing", json.toString());

       JSONObject jobj = new JSONObject(json.toString());
       final String msg = jobj.getString("msg");
       //That's all right so far , bug you haven't confirm whether the server have delete the data you want to .
       //So you should write some code to check this
       if(msg.equals("Succ")//Just for example
       {
           //Here you have check the data is already delete by server 
           //Now you can delete the data store in your code not the server
           return viewPager.getCurrentItem();//return the index of viewPager you want to delete to onPostExecute
       }
       else
       {
          //something wrong with server , so you shouldn't delete anything
          return -1; //Just return -1 let onPostExecute know no one need to be deleted.
       }
    }

    @Override
    protected void onPostExecute(int index) {
       //Here is in UI Thread
       if(index != -1) {
           userphotoArrayList.remove(index)//Delete the data with this index
           //Now your data have changed but the view haven't changed , you should call notifyDataSetChanged
           viewPager.getAdapter().notifyDataSetChanged();
       }
       else {
           //You should let User know he or she delete photo failed
           Toast.makeText(PhotoView.this, "Delete failed", Toash.LENGTH_SHORT).show();
       }

    }
}

和,不要不只是复制我的code,有很多假设。

And , don't not just copy my code , there is a lot of assumption。

这篇关于如何刷新视图寻呼机在Android的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆