从CustomListAdapter类刷新列表行,该类扩展了BaseAdapter

时间:2016-05-07 06:53:00

标签: android listview

我有一个listview,其中有一个按钮,在单击按钮(来自CustomListAdapter类)的特定行上,它将值插入数据库并显示该特定行的值。它插入值但不显示值或不刷新。 所以我使用了这段代码

    public class CustomListAdapter2 extends BaseAdapter  {
    List<HashMap<String, Object>> models,mList; 

    Context context;
    LayoutInflater inflater;

   URL urll;
   HttpURLConnection connection;

  InputStream input;

  ViewHolder viewHolder;
//UI for Locations
ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2,emasr,cn;
ArrayList<String> listItems;
ListView lv;
public int count1 = 0;
 ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
int position2;
 String id,emm;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email,session_ph,session_type,session_loc,connter;
ArrayList<HashMap<String, Object>> usersList,usersList1;
JSONParser jParser = new JSONParser();
int i ;

Parcelable state;

JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
private String imagePath = IP+"/upload/";
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
private static String url_all_properties5 = IP+"/social/get_all_agen_like.php";
private static String url_all_properties1 = IP+"/social/get_lik_coun.php";
private static String url_all_properties6 = IP+"/social/get_all_agen_like3.php";
private static String url_all_properties7 = IP+"/social/get_all_dele_like.php";
private static String url_all_properties8 = IP+"/social/get_all_dele_uplike.php";
private static String url_all_propertiesdel = IP+"/social/getdelete_all_agent.php";
  boolean isSelected;
  int a,a1,b,b1;

    //private static final String TAG_SUCCESS1 = "mass";
    private static final String TAG_USER = "users";

    private static final String TAG_PRO = "properties";
    //private static final String TAG_PRO1 = "properties1";
    // products JSONArray
    JSONArray users = null;
    //JSONArray users1 = null;
     View view;

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
 SharedPreferences sPref;
// int position;


public CustomListAdapter2(Context context, List<HashMap<String, Object>> models) {
    this.context = context;
    this. models = models;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.counters = new int[30];
    mList = models;
    //this.session_email = sPref.getString("SESSION_UID","");

}

public class ViewHolder {

       public TextView countt,idas5,emasr,cn,idas;

      // public String id,emm;

       public  ImageView like,image,imageViewOne;
       public ImageView share,share2;



    }

public void clear(){
    if(models!=null)
        models.clear();
}

@Override
public int getCount() {
    return models.size();
}

public HashMap<String, Object> getItem(int position) {
    return models.get(position);

}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return position;
} 

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return 1;
}

@Override
public View getView( final int position, final View convertView,  ViewGroup parent) {
        //  view = null;
      view = convertView;

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

          sPref= context.getSharedPreferences("REAL", Context.MODE_PRIVATE);



        session_email = sPref.getString("SESSION_UID","");
        session_ph = sPref.getString("SESSION_PH","");
        session_type = sPref.getString("SESSION_TYPE", "");
        session_loc = sPref.getString("SESSION_LOC", "");



      ConnectionDetector cd = new ConnectionDetector(context);

        Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false



        if (isInternetPresent) {
            // Internet Connection is Present
            // make HTTP requests
         // Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show();

     //     new LoadAllProducts().execute(); 

        } else if (!isInternetPresent) {
            // Internet connection is not present
            // Ask user to connect to Internet
        //  Toast.makeText(getActivity(), "Please Check your Internet connection", Toast.LENGTH_LONG).show();
          removeItemFromList1();

        }


       // lv=(ListView)view.findViewById(R.id.list);
        pos = getItemViewType(position);
      //  long posn = getItemId(position);
     // final int paps= (int)posn ;
        if (view == null) {
            viewHolder = new ViewHolder();
            view = inflater.inflate(R.layout.fragment_home2, parent, false);
            //your code

            cn = (TextView) view.findViewById(R.id.count);
            viewHolder.image = (ImageView) view.findViewById(R.id.feedImage1);

            //add below code after (end of) your code
            viewHolder.idas5 = (TextView) view.findViewById(R.id.hpid);
            viewHolder. emasr= (TextView) view.findViewById(R.id.ema);
            viewHolder.like=(ImageView)view.findViewById(R.id.likem);

            viewHolder.share=(ImageView)view.findViewById(R.id.sharemsp);
            viewHolder.share2=(ImageView)view.findViewById(R.id.plu);

            viewHolder.cn = (TextView) view.findViewById(R.id.count);
            viewHolder.imageViewOne = (ImageView) view.findViewById(R.id.feedImage1);



            viewHolder.imageViewOne.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                     int position = (Integer) v.getTag();
                     HashMap<String, Object> item = models.get(position);

                    // viewHolder.idas = (TextView) view.findViewById(R.id.hpid);
                     idas.setText((CharSequence) item.get("UIDAS"));

                    // pacm= viewHolder.idas.getText().toString();

                     pacm= idas.getText().toString();

                    // pacm = ((TextView) v.findViewById(R.id.hpid)).getText().toString();



                        Intent intent=new Intent(context, Profile1.class);
                        intent.putExtra("ACAM",pacm);
                        context.startActivity(intent);
                        //((Activity) context).finish();

                     //notifyDataSetChanged(); 
                }


            });  



            viewHolder.imageViewOne.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    // TODO Auto-generated method stub
                    int position = (Integer) v.getTag();
                 HashMap<String, Object> item = models.get(position);
                      idas.setText((CharSequence) item.get("UIDAS"));
                      pacm= idas.getText().toString();
                      removeItemFromList();
                      return true;
                }
            });
















           // viewHolder.share.setOnItemClickListener(this);


            viewHolder.like.setBackgroundResource(R.drawable.like1);

            viewHolder.like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (Integer) v.getTag();
                   // viewHolder.countt = (TextView) v.findViewById(R.id.count);
                    HashMap<String, Object> item = models.get(position);

                    viewHolder.idas5.setText((CharSequence) item.get("UIDAS"));

                    // id=(String) viewHolder.idas5.getText();
                     viewHolder.emasr.setText((CharSequence) item.get("EMAILM"));

                        id=(String) viewHolder.idas5.getText();

                        emm=(String) viewHolder.emasr.getText();






                         new LoadAllProducts().execute(); 


                          new LoadAllProducts22().execute(); 


                          notifyDataSetChanged();







                }
            });
            view.setTag(viewHolder);

        } else {
           viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.imageViewOne.setTag(position);  
        viewHolder.like.setTag(position);  
         viewHolder.share.setTag(position);
         viewHolder.share2.setTag(position);
         viewHolder.cn.setTag(position);  




     final HashMap<String, Object> item = getItem(position);




     pic = (ImageView) view.findViewById(R.id.profilePic);
     name = (TextView) view.findViewById(R.id.name);
     idas = (TextView) view.findViewById(R.id.hpid);

     idas2 = (TextView) view.findViewById(R.id.hpid2);
     timestamp = (TextView) view.findViewById(R.id.timestamp);

    // Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/NotoSansMalayalam-Regular.ttf");

     msg = (TextView) view.findViewById(R.id.txtStatusMsg);

   //  msg.setTypeface(tf);

     url = (TextView) view.findViewById(R.id.txtUrl);
     image = (ImageView) view.findViewById(R.id.feedImage1);



     idas.setText((CharSequence) item.get("UIDAS"));

    cn.setText((CharSequence) item.get("COUN"));
    // listItems.add(idas.getText().toString());
     name.setText((CharSequence) item.get("NAME"));
     timestamp.setText((CharSequence) item.get("TIME"));
     msg.setText((CharSequence) item.get("MSG"));
     url.setText((CharSequence) item.get("URL"));








        Picasso.with(context)
        //.load("PIC")
     .load((String)item.get("PIC"))
        .placeholder(R.drawable.profile_dummy)
        //.error(R.drawable.ic_whats_hot)
        .resize(50, 50)
//          .centerCrop()
       // .fit()
        .into(pic);



        /*Display display = getActivity().getWindowManager().getDefaultDisplay(); 
        Point size = new Point();
        display.getSize(size); 
        int width = size.x;*/



     Picasso.with(context)
     .load((String)item.get("IMAGE"))

    //.load("IMAGE")
    // .placeholder(R.drawable.ic_pages)
     //.error(R.drawable.ic_home)
 // .resize(1000,b1)
   // .onlyScaleDown()
    //.centerCrop()
 // .fit().centerInside()
     .into(image);









     return view;
}

protected ContentResolver getContentResolver() {
    // TODO Auto-generated method stub
    return null;
}


static boolean isAirplaneModeOn(Context context) {
      ContentResolver contentResolver = context.getContentResolver();
      return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;
    }













public void removeItemFromList() {


    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    alertDialog.setTitle("Delete");
    alertDialog.setMessage("Do you want delete this item?");

    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

             new CreateNewUser().execute();       

        }
    });

    alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "NO", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
             dialog.dismiss();
        }
    });


    alertDialog.show();

}

//这是点击工作的类,我想刷新值

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



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

        /*pDialog = new ProgressDialog(context);
        pDialog.setMessage("Loading.. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
        */


        /*Runnable progressRunnable = new Runnable() {

            @Override
            public void run() {
                pDialog.cancel();
            }
        };

        Handler pdCanceller = new Handler();
        pdCanceller.postDelayed(progressRunnable, 3000);*/

    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
      //  session_email = sPref.getString("SESSION_UID","");

        usersList = new ArrayList<HashMap<String, Object>>();
        //usersList1 = new ArrayList<HashMap<String, Object>>();

    //  cn = (TextView) view.findViewById(R.id.count);

        // id=(String) viewHolder.idas5.getText();

        ((Activity) context).runOnUiThread(new Runnable() {
             @Override
             public void run() {

            try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();



            params.add(new BasicNameValuePair("email", session_email));
            params.add(new BasicNameValuePair("loc", "liked"));
            params.add(new BasicNameValuePair("con", "1"));
            params.add(new BasicNameValuePair("idtes", id));
            params.add(new BasicNameValuePair("emas", emm));


            JSONObject json = jParser.makeHttpRequest(url_all_properties5, "GET", params);

             if (json != null) {

            // Check your log cat for JSON reponse
            Log.d("All start: ", json.toString());
            // Checking for SUCCESS TAG

            int success = json.getInt(TAG_SUCCESS);



            if (success== 1) {



                Log.d("Inside success...", json.toString());
                connter = json.getString("loca");


                //cn.setText(connter);

                Intent intent = ((Activity) context).getIntent();
                 //  state = ((Dialog) mList).onSaveInstanceState();
                 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                 sPref.edit().putString("SESSION_UID", session_email).commit();
                    sPref.edit().putString("SESSION_TYPE", session_type).commit();
                    sPref.edit().putString("SESSION_PH", session_ph).commit();
                    sPref.edit().putString("SESSION_LOC", session_loc).commit();
                    ((Activity) context).finish();
                    ((Activity) context).overridePendingTransition(0, 0);
                    ((Activity) context).startActivity(intent);
                 ((Activity) context).overridePendingTransition(0, 0);




                  notifyDataSetChanged(); // Create this function in your adapter class




                /* if(state != null) {

                        // lv.requestFocus();
                     mList.((Activity) context).onRestoreInstanceState(state);

                    }
*/

                //Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();



            } 

            else if (success== 5){
                // no products found


                Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();


            }


             } else {

                 removeItemFromList1();

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

             }
        }); 


        return null;
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        //pDialog.dismiss();
        // updating UI from Background Thread


        //pDialog.dismiss();

    }





}

但这正在重新加载整个活动。我只是想刷新那一行。我知道有可能使用listview.notifyDataSetChanged()进行刷新;或者通过刷新处理程序但这只能从主类中工作,而不是通过扩展基类适配器的Customlist适配器类,并且如果可能的话,我想保留列表位置,就像我们在主活动中使用listview.onRestoreInstanceState(state)一样

0 个答案:

没有答案