通过android编辑mysql


edit mysql via android

我希望有人能帮助我解决我的问题:我想在mysql中删除一个条目!到目前为止,它是有效的!唯一的问题是:它会立即从服务器中删除,但不会在应用程序中删除!如果刷新列表视图,它仍然在那里(但不在服务器上)。几分钟后,它也从listView中消失了。但是我如何编辑这个活动,该条目也立即在应用程序中删除?(我从教程中复制了这段代码,因为我不太熟悉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;
        }
}

首先,将适配器从SimpleAdapter更改为ArrayAdapter

类似:

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

并设置为:

setListAdapter(adapter);

然后,当您想要删除您的行时,尝试从ArrayAdapter中使用remove()。比如:

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();

或者你可以基于BaseAdapter编写你自己的适配器来保存你的数据,在里面你可以实现你自己的remove方法。这个问题,这个答案和这个教程将讨论如何做到这一点。

EDIT:当然,这一切都取决于你想要你的ListView看起来像什么,以及你想要显示什么数据。


第二次编辑: TL;DR:简短而简单的答案…在删除服务器上的数据后,调用这一行:new LoadAllProducts().execute();重新加载数据。