2016-12-02 8 views
0

Я получил данные от ответа json и показал его в listView. Когда я удаляю элемент в listView, он успешно удаляется, но listView не обновляется.Как обновить список в фрагменте, заполненном ArrayAdapter

Я использую ArrayAdapter вместо BaseAdapter. CustomList.java

public class CustomList extends ArrayAdapter<String> { 

    ImageButton imgdelete; 
    private String[] clientid; 
    private String[] mobile; 
    private String[] grand; 
    private String[] billid; 
    View listViewItem; 
    TextView textViewname; 


    private Activity context; 

    public CustomList(Activity context, String[] clientid, String[] mobile, String[] grand, String[] billid) { 
     super(context, R.layout.activity_listview, clientid); 
     this.context = context; 
     this.clientid = clientid; 
     this.mobile = mobile; 
     this.grand = grand; 
     this.billid = billid; 
    } 


    @Override 
    public View getView(final int position, final View convertView, ViewGroup parent) { 
     final LayoutInflater inflater = context.getLayoutInflater(); 
     listViewItem = inflater.inflate(R.layout.activity_listview, null, true); 
     textViewname = (TextView) listViewItem.findViewById(R.id.viewClientMobile); 
     TextView textViewmobile = (TextView) listViewItem.findViewById(R.id.viewClientName); 
     TextView textViewgrand = (TextView) listViewItem.findViewById(R.id.viewCompnayName); 
     TextView textViewbillid = (TextView) listViewItem.findViewById(R.id.viewCompanyEmail); 
     ImageButton imgedit = (ImageButton)listViewItem.findViewById(R.id.imgeditbtn); 
     imgdelete = (ImageButton)listViewItem.findViewById(R.id.imgdeletebtn); 
     textViewname.setText(clientid[position]); 
     textViewmobile.setText(mobile[position]); 
     textViewgrand.setText(grand[position]); 
     textViewbillid.setText(billid[position]); 

     imgdelete.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       new AlertDialog.Builder(context) 
         .setTitle("Delete entry") 
         .setMessage("Are you sure you want to delete this entry?") 
         .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int which) { 
           // continue with delete 
           DeleteClient_api(); 



          } 
         }) 
         .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int which) { 
           // do nothing 
          } 
         }) 
         .setIcon(android.R.drawable.ic_dialog_alert) 
         .show(); 


       notifyDataSetChanged(); 
      } 
     }); 

     return listViewItem; 

    } 
    protected void DeleteClient_api() { 
     final StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://befoodie.co/billingsystem/client_api.php", 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         // Toast.makeText(getContext(), response, Toast.LENGTH_LONG).show(); 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show(); 
        } 
       }) { 
      @Override 
      protected Map<String, String> getParams() { 
       Map<String, String> params = new HashMap<String, String>(); 
       // final String session = ActivityLogin.MostSecureRandom.nextSessionId(); 
       params.put("Action", "RemoveClient"); 
       params.put("ClientID",textViewname.getText().toString()); 

       return params; 
      } 

     }; 

     RequestQueue requestQueue = Volley.newRequestQueue(getContext()); 
     requestQueue.add(stringRequest); 



    } 
} 

ViewAllClient.java

public class ViewAllClient extends Fragment { 

    private ListView listView; 


    //create Array of product Details 

    public ViewAllClient() { 
     // Required empty public constructor 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

    } 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.activity_view_all_client, container, false); 


     // listView = (ListView) rootView.findViewById(R.id.listviewclient); 
     listView = (ListView) rootView.findViewById(R.id.listviewclient); 
     View_api(); 
       return rootView; 
    } 
    protected void View_api(){ 
     final StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://befoodie.co/billingsystem/client_api.php", 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
        showJSON(response); //Toast.makeText(getActivity(), response, Toast.LENGTH_LONG).show(); 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show(); 
        } 
       }) { 
      @Override 
      protected Map<String, String> getParams() { 
       Map<String, String> params = new HashMap<String, String>(); 
       // final String session = ActivityLogin.MostSecureRandom.nextSessionId(); 
       params.put("Action", "ViewClients"); 
       return params; 
      } 

     }; 

     RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); 
     requestQueue.add(stringRequest); 



    } 

    protected void showJSON(String json){ 
     ParseJSON pj = new ParseJSON(json); 
     pj.parseJSON(); 

     final CustomList cl = new CustomList(getActivity(), ParseJSON.CLIENTID,ParseJSON.mobile,ParseJSON.grand, ParseJSON.billid); 
     listView.setAdapter(cl); 


     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 


      } 
     }); 


    } 

} 

ParseJSON.java

public class ParseJSON { 


    public static String[] CLIENTID; 
    public static String[] mobile; 
    public static String[] grand; 
    public static String[] billid; 



    public static final String JSON_ARRAY = "ClientDetails"; 
    public static final String KEY_ID = "ClientID"; 
    public static final String KEY_MOBILE = "ClientName"; 
    public static final String KEY_GRAND = "EmailID"; 
    public static final String KEY_BILL = "StartingCommunicationDate"; 



    private JSONArray users = null; 

    private String json; 

    public ParseJSON(String json){ 
     this.json = json; 
    } 

    protected void parseJSON(){ 


     JSONObject jsonObject=null; 
     try { 
      jsonObject = new JSONObject(json); 
      users = jsonObject.getJSONArray(JSON_ARRAY); 

      CLIENTID = new String[users.length()]; 
      mobile = new String[users.length()]; 
      grand = new String[users.length()]; 
      billid = new String[users.length()]; 

      for(int i=0;i<users.length();i++){ 
       JSONObject jo = users.getJSONObject(i); 
       CLIENTID[i] = jo.getString(KEY_ID); 
       mobile[i] = jo.getString(KEY_MOBILE); 
       grand[i] = jo.getString(KEY_GRAND); 
       billid[i] = jo.getString(KEY_BILL); 


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

Первый, может я предлагаю использовать RecyclerView вместо ListView. Во-вторых, вы можете уведомить свой адаптер о любых изменениях, просто вызовите adapter.notifyDataSetChanged(); после изменения. –

+0

поделитесь своим кодом. – EKN

ответ

0

Вызов adapter.notifyDataSetChanged() вашего объекта адаптера, как только вы изменили данные в этом адаптере. ;

Примечание: Для ArrayAdapter, notifyDataSetChanged работает только если вы используете add(), insert(), remove() и clear() на адаптере.

0

Try ниже кода,

YourAdapter adapter = new YourAdapter(context, ListDataHeader, ListDataChild, data); 
adapter.notifyDataSetChanged(); 
0

Привет @Dipu Сначала вы должны удалить элемент из локального jsonresponse (который заполняемый список) .Посль, что вы должны уведомить об этом адаптере, что данные были changed.If вы удалили изнутри адаптер, просто напишите notifyDataSetChanged(); после удаления элемента. При удалении из класса, то вы должны просто написать

adapter.notifyDataSetChanged(); 

Я надеюсь, что это помогает

+0

Я пробовал это, но он не работает. Я положил это в свой адаптер. –

0
// in ViewAllClient fragment 

    public void delete(int position){ 
     adapter.notifyItemChanged(position);//-- only update the required row 
    // notifyDataSetChanged for full listview 

}

// in adapter 
ViewAllClient viewAllClient =new ViewAllClient(); 
viewAllClient .delete(position); 
+0

Я делаю этот код, но его не работает. :-( –

+0

попробуйте адаптер.notifydatasetchanged там в классе фрагментов –

 Смежные вопросы

  • Нет связанных вопросов^_^