如何通过Android应用程序从在线数据库中删除项目?

时间:2014-08-07 13:18:08

标签: android

我最近开始开发Android,而且我很难解决一件可能比我想象的更简单的事情。

我正在创建一个与在线数据库通信的CRUD应用程序,我可以读取和输入数据,遗憾的是,我无法删除并修改列表。

要管理使用JSON的数据,我添加的列表中的行由三个字段组成:animal_id,animal_name,animal_type。

我读过的活动数据以及我希望通过以下代码实现通过监听器修改和删除方法的活动数据:

import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log; 
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ListAnimalActivity extends ListActivity  {

    ArrayList<HashMap<String,?>> animalList;
    JSONParser jParser = new JSONParser();
    JSONArray animals = null;
    Button button_add;

    private static String url_read = "http://example.com/list_animals.php";
    private static String url_delete = "http://example.com/delete_animal.php";
    private static final String TAG_SUCCESS = "success";

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

    public void onResume(){
        super.onResume();
        load_ListAnimalActivity();
    }

    private void load_ListAnimalActivity(){
        setContentView(R.layout.activity_list_animal);
        animalList = new ArrayList<HashMap<String,?>>();
        new Read_Object().execute();

        final ListView listView = (ListView)findViewById(android.R.id.list);

        final ListAdapter adapter = new SimpleAdapter(
                 ListAnimalActivity.this, animalList,
                 R.layout.row_list, new String[] { "animal_id",
                 "animal_name","animal_type"},
                 new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                AlertDialog.Builder adb = new AlertDialog.Builder(ListAnimalActivity.this);
                adb.setTitle("Attenzione!");
                adb.setMessage("Vuoi eliminare l\'elemento \"" + animalList.get(position)+ "\" ?");
                final int posizione = position;
                adb.setNegativeButton("Annulla",new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {}
                });
                adb.setPositiveButton("Elimina", new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        new Delete_Object().execute();
                    }
                });
                adb.show();
            }
        });

        button_add = (Button)findViewById(R.id.button_add);
        button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ListAnimalActivity.this,CRUDAnimalActivity.class));
            }
        });
    }

    class Read_Object extends AsyncTask<String, String, String> {

        private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressMessage.setMessage("Loading ...");
            progressMessage.setIndeterminate(false);
            progressMessage.setCancelable(false);
            progressMessage.show();
        }

        protected String doInBackground(String... args) {
            List params = new ArrayList();
            JSONObject json = jParser.makeHttpRequest(url_read, "POST", params);

            try{
                Log.d("Animals: ", json.toString());
            } catch (NullPointerException e){
                e.printStackTrace();
            }

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    animals = json.getJSONArray("animals");
                    for (int i = 0; i < animals.length(); i++) {
                        JSONObject c = animals.getJSONObject(i);
                        String id = c.getString("animal_id");
                        String name = c.getString("animal_name");
                        String type = c.getString("animal_type");
                        HashMap map = new HashMap();
                        map.put("animal_id", id);
                        map.put("animal_name", name);
                        map.put("animal_type", type);
                        animalList.add(map);
                    }
                }       
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (NullPointerException e){
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String file_url) {
            progressMessage.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                    ListAdapter adapter = new SimpleAdapter(
                        ListAnimalActivity.this, animalList,
                        R.layout.row_list, new String[] { "animal_id",
                        "animal_name","animal_type"},
                        new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
                    setListAdapter(adapter);
                }
            });

        }

    }

    class Delete_Object extends AsyncTask<String, String, String>{

        private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressMessage.setMessage("Deleting ...");
            progressMessage.setIndeterminate(false);
            progressMessage.setCancelable(false);
            progressMessage.show();
        }

        protected String doInBackground(String... args) {
            /*
              Code to delete
            */
            return null;
        }

        protected void onPostExecute(String file_url){

        }
    }
}

当我点击列表Item时,监听器会以这种格式显示对象:     {animal_type = firstType,animal_name = firstName,animal_id = 1}

所以我的问题是: 如何从数组animalList&gt;中仅收集animal_id? ?

3 个答案:

答案 0 :(得分:1)

您的animalList是一个以HashMaps为元素的数组列表,因此当您调用animalList.get(position)时,它将返回一个HashMap。要检索animal_id,只需使用:

(animalList.get(position)).get(animal_id).toString();

答案 1 :(得分:0)

你必须为动物创建一个Modelclass / Pojo类(私有变量和getter和setter),

ArrayList<AnimalModel> animalsArrayList = new ArrayList<AnimalModel>();

将Animals对象/数据添加到animalsArrayList和listview.setAdapter(animalsArrayList);

然后

  listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub

            Object object = speakerListView.getItemAtPosition(position);
            AnimalModel animals_data = (AnimalModel)  object;

             id = animals_data.getAnimal_id()

    // call delete Async with thid Id

        }
    });

答案 2 :(得分:0)

你的代码看起来很混乱。如果我是你,我会创建一个自定义适配器,扩展基本适配器并将参数作为参数,或者在构造函数中传递的列表或列表。在那里你可以有不同的听众。此外,如果您想通知活动,您可以享受&#34;豪华&#34;将接口作为参数传递,并在发生更改时通知活动。
关于json部分,我将创建两个新类,一个是接收任务并进一步处理它们的线程管理器,另一个是你进行http调用和json解析的类。 我做了一个类似的应用程序,它接收来自星云界面的数据并将它们显示给用户。