如何在android中刷新视图寻呼机?

时间:2014-12-26 10:56:38

标签: android android-viewpager

我在我的视图寻呼机中有一些图像,我从删除按钮中删除图像,但删除图像后我想刷新视图寻呼机,并希望在我的应用程序中显示剩余图像可以任何一个是什么错误?

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();

  }

}

enter image description here enter image description here enter image description here

3 个答案:

答案 0 :(得分:0)

重写我的所有答案:

首先,让我们看看AsyncTask的用法,这里有重要的功能:

/**
 * 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的模板:

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

    }
}

并且,不要只是复制我的代码,有很多假设。

答案 1 :(得分:0)

或者..你可以刷新你的活动..

试试这个 点击刷新按钮

finish();
startActivity(getIntent());

答案 2 :(得分:0)

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

    @Override
    public void onClick(View v) {
       userphotoArrayList.remove(viewPager.getCurrentItem())
       adapter.notifyDataSetChanged();

    }
});

以及适配器:

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}
相关问题