2015-08-02 4 views
0

Мне нужно удалить элемент списка из списка при нажатии кнопки удаления в android eclipse. Значения в списке заполняются из базы данных mysql (JSON), поэтому при удалении я также должен удалить их из базы данных.Как удалить элемент списка из списка в андроидном затмении, нажав кнопку

Это моя основная деятельность; Мне нужно удалить ListItem из ListView на нажатие кнопки удаления по каждому пункту в 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; 
    } 
+0

Вы должны позвонить http-методу, чтобы удалить этот реестр на сервере –

+0

@ Rodrigo Henriques: Но как я могу удалить его в listview в android eclipse..может ли вы предоставить пример кода – Adarsh

+0

, вы имеете в виду уведомление о своем списке, что этот элемент больше не существует –

ответ

0

В методе GetView вашего ListViews адаптера вы ссылаетесь на кнопку на макет вашего Раздувание и просто прикрепить setOnClickListener. .. на кнопку и удалить этот элемент из списка или массива, который использует ваш адаптер, а затем notifyDataHasChanged.

Удалить этот предмет из предметов в этом положении.

Итак, 1. вы хотите удалить элемент из ListView 2. вы хотите удалить элемент из базы данных SQL.

Первый из них очень прост, но вам нужно знать адаптер подчеркивания и то, как он служит данным для вашего ListView. Когда вы создаете BaseAdapter для ListView, вы передаете List или массив. Этот массив будет данными, которые ваш BaseAdapter служит для вашего ListView, каждый вид в представлении списка будет отображать элемент из массива (сделано в getView()). Если вы динамически удаляете один из этих элементов, то настройте свой массив (или просто используйте List и это .remove(), и, наконец, notifyDataSetChanged(); ваш BaseAdapter обновит ваш список без этого представления (или, скорее, этот вид будет заменен новым). например, ниже я прохожу в List<WeatherLocation> (WeatherLocation является содержащий класс, который имеет материал о погоде для определенной области (город, почтовый индекс, степень «Биддефорд», 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. Я тоже могу это показать, но я чувствую, что у вас есть какое-то кодирование, которое нужно делать.

+0

извините, я did'nt получаю вас .. вы можете отправить мне это изменение? – Adarsh