如何通过单击按钮从android eclipse中的listview中删除列表项

时间:2015-08-02 18:52:06

标签: android listview button listitem

我需要在android eclipse中单击删除按钮从listview中删除列表项。列表值是从mysql数据库(JSON)填充的,所以在删除时,我还需要从数据库中删除它。

这是我的主要活动;我需要在列表视图中的每个项目上单击删除按钮时从列表视图中删除listitem:

    public class MainActivity extends Activity implements AsyncResponse2 {
        private ProgressDialog dialog;
        ListView l1;
         //for getting count
        TextView count;
        private static final String TAG_COUNT = "cnt";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE);    //to hide title bar   
            setContentView(R.layout.activity_main);  
            l1=(ListView)findViewById(R.id.listView1);
            /** Reference to the delete button of the layout main.xml */
            Button btnDel = (Button) findViewById(R.id.deleteid);
            initView();
            //str for getting count
            count=(TextView)findViewById(R.id.countid);
          //to display count while loading(so outside buttonclick)
             String key1 = "saasvaap123";
           String signupid1 = "8";
             String url2 = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
             //http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?key=saasvaap123&signup_id=8
             //put the below lines outside button onclick since we load the values into edittext when opening the app
           CustomHttpClient2 task2 = new CustomHttpClient2();
           task2.execute(url2,key1,signupid1);
           task2.delegate = MainActivity.this;
           //end
        }
     //str getting count
      //str customhttp2
           private class CustomHttpClient2 extends AsyncTask<String, String, String>{




        public AsyncResponse2 delegate=null;
        private String msg;




    @Override
    protected void onPostExecute(String result2) {
       // TODO Auto-generated method stub
       super.onPostExecute(result2);

       delegate.processFinish2(result2);

    }

    @Override
    protected void onPreExecute() {

       // TODO Auto-generated method stub
       super.onPreExecute();

    }



           @Override
           protected String doInBackground(String... params) {
               if(params == null) return null;

               // get url from params
               String url2 = params[0];
               String key1 = params[1];
               String signupid1 = params[2];

               ArrayList<NameValuePair> postParameters;


               postParameters = new ArrayList<NameValuePair>();

               postParameters.add(new BasicNameValuePair("key",key1));
               postParameters.add(new BasicNameValuePair("signup_id",signupid1));




               try {
                   // create http connection
                   HttpClient client = new DefaultHttpClient();
                   HttpPost httppost = new HttpPost(url2);
                   httppost.setEntity(new UrlEncodedFormEntity(postParameters));

                   // connect
                   HttpResponse response = client.execute(httppost);

                   // get response
                   HttpEntity entity = response.getEntity();

                   if(entity != null){
                       return EntityUtils.toString(entity);
                   }
                   else{
                       return "No string.";
                   }
                }
                catch(Exception e){
                    return "Network problem";
                }
           }




       }



           public void processFinish2 (String output2){

           Toast.makeText(MainActivity.this,output2, Toast.LENGTH_SHORT).show();




               try{   
                   //str
                  JSONObject jsonResponse = new JSONObject(output2);

                    JSONArray aJson = jsonResponse.getJSONArray("gen_off");

                    // create apps list


                    for(int i=0; i<aJson.length(); i++) {
                        JSONObject json = aJson.getJSONObject(i);
                   //end




                      //str

                        String strCount = json.getString(TAG_COUNT);

                        count.setText(strCount);//setting name to original name text
                      //end
                    }





                }catch (JSONException e) {
                    Toast.makeText(MainActivity.this,"Exception caught!", Toast.LENGTH_SHORT).show();
                }       

                  }

        //end getting count
        private void initView() {
            // show progress dialog
         //   dialog = ProgressDialog.show(this, "", "Loading...");
            String key="saasvaap123";
            String signup_id="8";
            String url = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
            FetchDataTask task = new FetchDataTask();
            task.execute(url,key,signup_id);
        }



        public class FetchDataTask extends AsyncTask<String, Void, String>{
           // private final FetchDataListener listener;
            private String msg;



            @Override
            protected String doInBackground(String... params) {
                if(params == null) return null;

                // get url from params
                String url = params[0];
                String key1 = params[1];
                String signupid1 = params[2]; 
                ArrayList<NameValuePair> postParameters;


                postParameters = new ArrayList<NameValuePair>();

                postParameters.add(new BasicNameValuePair("key",key1));
                postParameters.add(new BasicNameValuePair("signup_id",signupid1));


                 //str
                try {
                    // create http connection
                    HttpClient client = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(url);
                    httppost.setEntity(new UrlEncodedFormEntity(postParameters));

                    // connect
                    HttpResponse response = client.execute(httppost);

                    // get response
                    HttpEntity entity = response.getEntity();

                    if(entity != null){
                        return EntityUtils.toString(entity);
                    }
                    else{
                        return "No string.";
                    }
                 }
                 catch(Exception e){
                     return "Network problem";
                 }
            }
                //end


    //         
            @Override
            protected void onPostExecute(String sJson) {




                try {

                    JSONObject jsonResponse = new JSONObject(sJson);

                    JSONArray aJson = jsonResponse.getJSONArray("gen_off");
                   Toast.makeText(MainActivity.this, aJson.toString(),Toast.LENGTH_SHORT).show();

                    // create apps list
                    List<SavedOffers> apps = new ArrayList<SavedOffers>();

                    for(int i=0; i<aJson.length(); i++) {
                        JSONObject json = aJson.getJSONObject(i);
                        SavedOffers app = new SavedOffers();
                        app.setTitle(json.getString("title"));
                        app.setOriginalRate(json.getString("price"));
                        app.setOfferRate(json.getString("off_price"));  
                        app.setPercentage(json.getString("percent"));  
                        app.setSavings(json.getString("savings"));  
                        app.setUrl(json.getString("image")); 

                        // add the app to apps list
                        apps.add(app);


                    }

                    SavedOffersAdapter adapter = new SavedOffersAdapter(MainActivity.this, apps);
    //               set the adapter to list
                 l1.setAdapter(adapter);   
                  //for delete
      //   adapter.notifyDataSetChanged();
         /** Defining a click event listener for the button "Delete" */
         Button btnDel = (Button) findViewById(R.id.deleteid);

         OnClickListener listenerDel = new OnClickListener() {

             @Override
             public void onClick(View v) {
                 /** Getting the checked items from the listview */
                 SparseBooleanArray checkedItemPositions = l1.getCheckedItemPositions();
                 int itemCount = l1.getCount();

                 for(int i=itemCount-1; i >= 0; i--){
                     if(checkedItemPositions.get(i)){
                         adapter.remove(l1.get(i));
                     }
                 }
                 checkedItemPositions.clear();
                 adapter.notifyDataSetChanged();
             }
         };
         /** Setting the event listener for the delete button */
         btnDel.setOnClickListener(listenerDel);

         /** Setting the adapter to the ListView */
         l1.setAdapter(adapter);              //end delete
                    //notify the activity that fetch data has been complete
                  //  if(listener != null) listener.onFetchComplete(apps);
                } catch (JSONException e) {
    //                msg = "Invalid response";
    //                if(listener != null) listener.onFetchFailure(msg);
    //                return;


                }        
            }

            /**
             * This function will convert response stream into json string
             * @param is respons string
             * @return json string
             * @throws IOException
             */
            public String streamToString(final InputStream is) throws IOException{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder(); 
                String line = null;

                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } 
                catch (IOException e) {
                    throw e;
                } 
                finally {           
                    try {
                        is.close();
                    } 
                    catch (IOException e) {
                        throw e;
                    }
                }

                return sb.toString();
            }
        }
    }

// this is my adapter class ,  I think change is only needed in main activity
// , I need to delete a specific list item from listview on clicking the delete button
public class SavedOffersAdapter extends ArrayAdapter<SavedOffers>{
    private List<SavedOffers> items;
    Bitmap bitmap;
    ImageView image;
    public SavedOffersAdapter(Context context, List<SavedOffers> items) {
        super(context, R.layout.app_custom_list, items);
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }
    private class ViewHolder {
        //TextView laptopTxt;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    //   ViewHolder holder;//added
        View v = convertView;

        if(v == null) {
            LayoutInflater li = LayoutInflater.from(getContext());
            v = li.inflate(R.layout.app_custom_list, null);           
        }

        SavedOffers app = items.get(position);

        if(app != null) {

            TextView productName = (TextView)v.findViewById(R.id.nameid);
            TextView originalRate = (TextView)v.findViewById(R.id.originalid);
            originalRate.setPaintFlags(originalRate.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            TextView offerRate = (TextView)v.findViewById(R.id.offerid);
            TextView percentage = (TextView)v.findViewById(R.id.discountid);
            TextView savings = (TextView)v.findViewById(R.id.savingsid);
            image =(ImageView)v.findViewById(R.id.prctimgid);

            if(productName != null) productName.setText(app.getTitle());
            if(originalRate != null) originalRate.setText(app.getOriginalRate()); 
            if(offerRate != null) offerRate.setText(app. getOfferRate());
            if(percentage != null) percentage.setText(app. getPercentage());
            if(savings != null) savings.setText(app. getSavings());

            if(image!=null){

                new DownloadImageTask(image).execute(app.getUrl());

        }




        }

        return v;
    }

1 个答案:

答案 0 :(得分:0)

在listviews适配器的getView方法中,您链接到布局上的按钮,只需将setOnClickListener ...附加到该按钮,然后将其从您的适配器使用的列表或数组中删除。然后notifyDataHasChanged。

从该位置的项目中删除该项目。

所以1.你要删除ListView中的项目    2.您要从SQL DB中删除该项目。

第一个非常简单,但您需要知道下划线适配器以及它如何为ListView提供数据。当您为BaseAdapter或数组传递ListView实例化List时。此数组将是BaseAdapterListView提供的数据,listview中的每个视图都会显示数组中的元素(在getView()中完成)。如果您动态删除其中一个项目,请调整您的数组(或者只使用List及其.remove(),最后notifyDataSetChanged();您的BaseAdapter将会刷新没有那个View的列表(或者更确切地说,View将被替换为新的。)因此,例如下面我传入List<WeatherLocation>(WeatherLocation是一个包含特定区域的天气内容的类(城市,邮编) ,程度&#34; Biddeford&#34;,04005,72)到我的BaseAdapter

// Instantiate ListView
ListView lvLocations = (ListView) findViewById(R.id.lvLocations);
// Instantiate our BaseAdapter (pass in the List<WeatherLocation>)
WeatherLocationAdapter mWeatherLocationAdapter = new WeatherLocationAdapter(savedList, this, R.layout.view_weather_location);
lvLocations.setAdapter(mWeatherLocationAdapter);

这是常规ListView将适配器设置为自定义BaseAdapter的示例。

BaseAdapter非常简单,真正唯一关心的方法(主要是)getView()方法。

R.layout.view_weather_location is just a `LinearLayout` I made, it has 3 TextViews in it that I tie (show) my data with, by attaching data to those TextViews in the `getView()` method of the `BaseAdapter`. You would put a `Button there and tie it to what you want (to delete the data item)`.

public class WeatherLocationAdapter extends BaseAdapter{
private List <WeatherLocation> mLocations;
private Context mContext;
private int rowForLocationToInflate;
private LayoutInflater inflater;

public WeatherLocationAdapter(List<WeatherLocation> mLocations, Context mContext, int rowForLocationToInflate) {
    this.mLocations = mLocations;
    this.mContext = mContext;
    this.rowForLocationToInflate = rowForLocationToInflate;
    inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}
//TODO just built up layout now must tie to it.


private void addLocation(WeatherLocation newLocation){
    mLocations.add(newLocation);
    //TODO maybe invalidate after adding new item.

}

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

@Override
public WeatherLocation getItem(int position) {
    return mLocations.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //TODO build a viewholder

    View rowView = inflater.inflate(rowForLocationToInflate, parent, false);

    TextView tvZipcode = (TextView) rowView.findViewById(R.id.tvZipCode);
    TextView tvCity = (TextView) rowView.findViewById(R.id.tvCity);
    TextView tvTemp = (TextView) rowView.findViewById(R.id.tvDegree);

    tvZipcode.setText(mLocations.get(position).getZipcode());
    tvCity.setText(mLocations.get(position).getCity());
    tvTemp.setText(String.valueOf(mLocations.get(position).getTemperature()));


// If you had a Button in your LinearLayout you were attaching to you that you wanted to delete that view/item with, it would look something like this in my case.
Button bDel = (Button) row.findViewById(R.id.bDel);

    bDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLocations.remove(position);
            }
        });

        return rowView;
    }
}

onClick中,您还将从SQL db中删除该项。我也可以证明这一点,但我觉得你有一些编码可以做到。