0

I hope someone can help me with my problem: I want to delete a entry in mysql! It works so far! The only problem is: it is deleted immediately from the server, but not in the app! if i refresh the list view, it is still there (but not on the server). After a few minutes it is also gone from the listView. But how can i edit this activity that the entry is also deleted in the app immediately? (I copied this code from a tutorial because i'm not very familiar with programming android)

package info.androidhive.loginandregistration;

import java.util.ArrayList;
...
import android.widget.TextView;

public class AlleTischeActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://***/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_TISCHE = "tische";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "tischnummer";

    // products JSONArray
    JSONArray tische = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alle_tische);

        SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new LoadAllProducts().execute();
            }

        });
        // Hashmap for ListView
        new LoadAllProducts().execute();
        productsList = new ArrayList<HashMap<String, String>>();
        // Loading products in Background Thread

        // Get listview
        ListView lv = getListView();


        // on selecting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                 //getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.id)).getText().toString();

                 //Starting new intent
                Intent in = new Intent(getApplicationContext(), EditTischActivity.class);
                 //sending pid to next activity
                in.putExtra(TAG_ID, pid);

                // starting new activity and expecting some response back
               startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            new LoadAllProducts().execute();
        }

    }


    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
          //This is the constructor you should add over here
          public LoadAllProducts(){
          productsList = new ArrayList<HashMap<String, String>>();
    }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AlleTischeActivity.this);
            pDialog.setMessage("Lade offene Tische. Bitte warten...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = JSONParser.makeHttpRequest(url_all_products, "GET", params);


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

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    tische = json.getJSONArray(TAG_TISCHE);

                    // looping through All Products
                    for (int i = 0; i < tische.length(); i++) {
                        JSONObject c = tische.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            TischActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(i);

                }
            } 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
            runOnUiThread(new Runnable() {
                public void run() {
                    /*** Updating parsed JSON data into ListView ***/
                    ListAdapter adapter = new SimpleAdapter(
                            AlleTischeActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_ID,
                                    TAG_NAME},
                            new int[] { R.id.id, R.id.tischnummer, R.id.biernummer });
                    // updating listview
                    setListAdapter(adapter);

                }
            });

        }


    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.allmenu, menu);
        return true;
    }

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.refresh_table:
            new LoadAllProducts().execute();
          break;
        //case R.id.menuitem2:
          //Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT)
              //.show();
          //break;

        default:
          break;
        }

        return true;
        }
}

1 Answers1

1

First of all, change your adapter from SimpleAdapter to ArrayAdapter.

Something like:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(AlleTischeActivity.this, android.R.layout.simple_list_item_1, yourDataArray);

And set it like:

setListAdapter(adapter);

Then, when you want to remove your row, try to use remove() from the ArrayAdapter. Something like:

ArrayAdapter<String> myAdapter = (ArrayAdapter<String>)getListView().getAdapter();
myAdapter.remove(myAdapter.getItem(position)); // Where position is the position of the row you want to delete, you can get it through the "onClickListener()".
myAdapter.notifyDataSetChanged();

Or you could write your own adapter based on BaseAdapter to hold your data, and inside it you could implement your own remove method. This question, this answer and this tutorial covers how to do that.

EDIT: Of course, it all depends on how you want your ListView to look like and what data you want to display.


Second edit: TL;DR: Short and simple answer... After you delete your data on the server, call this line: new LoadAllProducts().execute(); to reload the data.

Community
  • 1
  • 1
Mauker
  • 11,237
  • 7
  • 58
  • 76