简体   繁体   English

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

[英]How to delete a list item from listview in android eclipse by clicking a button

I need to delete a list item from listview on clicking a delete button in android eclipse. 我需要在单击android eclipse中的删除按钮时从listview中删除一个列表项。 The list values are populated from mysql database(JSON), so on deleting, I need to delete the same from database also. 列表值是从mysql数据库(JSON)填充的,因此在删除时,我还需要从数据库中删除相同的值。

Here is my main Activity; 这是我的主要活动; I need to delete a listitem from a listview on clicking a delete button on each item in the listview: 在列表视图中的每个项目上单击删除按钮时,我需要从列表视图中删除一个列表项:

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

In your listviews adapter's getView method you link to the button on the layout your inflating and just attach a setOnClickListener... to the button and have it remove that item from your list or array that your adapter uses and then notifyDataHasChanged. 在listviews适配器的getView方法中,您可以链接到布局上的按钮,然后将setOnClickListener ...附加到按钮上,然后将其从适配器使用的列表或数组中删除,然后notifyDataHasChanged。

Delete that item from items in that position. 从该位置的项目中删除该项目。

So 1. you want to delete the item from the ListView 2. you want to delete the item from the SQL DB. 所以1.您想从ListView删除项目。2.您想从SQL DB删除项目。

The first one is very easy, but you kind of need to know the underlining adapter and how it serves data to your ListView . 第一个非常简单,但是您需要了解下划线适配器及其如何将数据提供给ListView When you instantiate a BaseAdapter for the ListView you pass in a List or an array. 当实例化ListViewBaseAdapter ,您将传入List或数组。 This array will be the data your BaseAdapter serves to your ListView , each view in the listview will be showing an element from the array (done in getView() ). 此数组将是BaseAdapterListView提供的数据,listview中的每个视图将显示该数组中的一个元素(在getView() )。 If you dynamically delete one of those items, then adjust your array (or just use a List and it's .remove() , and finally notifyDataSetChanged(); your BaseAdapter will refresh your list without that View (or rather that View will be replaced with the new one). So for instance below I pass in a List<WeatherLocation> (WeatherLocation is a containing class that has weather stuff for a particular area (city, zipcode, degree"Biddeford", 04005, 72) to my BaseAdapter . 如果您动态删除这些项之一,则调整数组(或仅使用List ,它是.remove() ,最后是notifyDataSetChanged(); BaseAdapter将刷新列表而不显示该View(或者将View替换为因此,例如在下面的示例中,我将List<WeatherLocation> (WeatherLocation是一个包含类,其中包含特定区域(城市,邮政编码,度为“ Biddeford”,04005、72)的BaseAdapter )传递给我的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);

This is an example of a regular ListView setting an Adapter to a custom BaseAdapter . 这是常规ListView将Adapter设置为自定义BaseAdapter

The BaseAdapter is so simple, that really the only method you care about (majorly) is the getView() method. 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;
    }
}

In the onClick you would also remove the item from the SQL db. onClick您还将从SQL数据库中删除该项目。 I can show that too, but I feel you have some coding to do as it stands. 我也可以证明这一点,但我觉得您需要进行一些编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM