如何使列表视图可点击并从 mysql 数据库中删除数据


package com.yiqiexample.cc;    
import java.util.ArrayList;    
import java.util.HashMap;    
import org.json.JSONArray;    
import org.json.JSONException;    
import org.json.JSONObject;    
import android.app.Activity;    
import android.app.ListActivity;    
import android.app.ProgressDialog;    
import android.content.Intent;    
import android.os.AsyncTask;    
import android.os.Bundle;    
import android.view.View;    
import android.view.View.OnClickListener;    
import android.widget.AdapterView;    
import android.widget.Button;    
import android.widget.CheckBox;
import android.widget.EditText;    
import android.widget.ListAdapter;    
import android.widget.ListView;    
import android.widget.SimpleAdapter;    
//import android.widget.ImageView;    
import android.widget.TextView;    
import android.widget.Toast;    
import android.widget.AdapterView.OnItemClickListener;    
public class Food extends ListActivity 
    implements OnClickListener {
    // Progress Dialog
        private ProgressDialog pDialog;
    //testing on Emulator:
     private static final String READ_COMMENTS_URL = "http://10.0.2.2/pbda2/foodordered.php";
    // my ip add 192.168.43.176
     //private CheckBox chkFood, chkDrinks, chkServices;
      //private Button btnDisplay, chkClear, deliever, chkClearFood, fooddeliever, drinksdeliever, servicesdeliever, chkClearDrinks, chkClearServices;
      //private TextView clearThis,orderdisplay, clearThisFood, foodorderdisplay, drinksorderdisplay, servicesorderdisplay, clearThisDrinks, clearThisServices;
      private static final String TAG_SUCCESS = "success";
      private static final String TAG_POSTS = "posts";
        private static final String TAG_SEATNUMBER = "seatnumber";
        private static final String TAG_FOODORDERED = "foodordered";
        //it's important to note that the message is both in the parent branch of 
        //our JSON tree that displays a "Post Available" or a "No Post Available" message,
        //and there is also a message for each individual post, listed under the "posts"
        //category, that displays what the user typed as their message.
      //An array of all of our comments
        private JSONArray mComments = null;
        //manages all of our comments in a list.
        private ArrayList<HashMap<String, String>> mCommentList;      
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.food);

        View v = findViewById(R.id.backmain);
        //set event listener
            v.setOnClickListener(this);
            View z = findViewById(R.id.drinksbtn);
            //set event listener
                z.setOnClickListener(this);
                View x = findViewById(R.id.servicebtn);
                //set event listener
                    x.setOnClickListener(this);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        //loading the comments via AsyncTask
        new LoadComments().execute();
    }

    /**
     * Retrieves recent post data from the server.
     */
    public void updateJSONdata() {
        // Instantiate the arraylist to contain all the JSON data.
        // we are going to use a bunch of key-value pairs, referring
        // to the json element name, and the content, for example,
        // message it the tag, and "I'm awesome" as the content..
        mCommentList = new ArrayList<HashMap<String, String>>();
        // Bro, it's time to power up the J parser 
        JSONParser jParser = new JSONParser();
        // Feed the beast our comments url, and it spits us
        //back a JSON object.  Boo-yeah Jerome.
        JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
        //when parsing JSON stuff, we should probably
        //try to catch any exceptions:
        try {
            //I know I said we would check if "Posts were Avail." (success==1)
            //before we tried to read the individual posts, but I lied...
            //mComments will tell us how many "posts" or comments are
            //available
            mComments = json.getJSONArray(TAG_POSTS);
            // looping through all posts according to the json object returned
            for (int i = 0; i < mComments.length(); i++) {
                JSONObject c = mComments.getJSONObject(i);
                //gets the content of each tag
                String seatnumber = c.getString(TAG_SEATNUMBER);
                String foodordered = c.getString(TAG_FOODORDERED);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(TAG_SEATNUMBER, seatnumber);
                map.put(TAG_FOODORDERED, foodordered);

                // adding HashList to ArrayList
                mCommentList.add(map);
                //annndddd, our JSON data is up to date same with our array list
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }




    @Override
            public void onClick(View arg0) {
        if(arg0.getId() == R.id.backmain){
            //define a new Intent for the second Activity
            Intent intent = new Intent(this,MainActivity.class);
            //start the second Activity
            this.startActivity(intent);
            }
        if(arg0.getId() == R.id.drinksbtn){
            //define a new Intent for the second Activity
            Intent intent = new Intent(this,Drinks.class);
            //start the second Activity
            this.startActivity(intent);
            }
        if(arg0.getId() == R.id.servicebtn){
            //define a new Intent for the second Activity
            Intent intent = new Intent(this,Services.class);
            //start the second Activity
            this.startActivity(intent);
            }

    }
    /**
     * Inserts the parsed data into the listview.
     */
    private void updateList() {
        // For a ListActivity we need to set the List Adapter, and in order to do
        //that, we need to create a ListAdapter.  This SimpleAdapter,
        //will utilize our updated Hashmapped ArrayList, 
        //use our single_post xml template for each item in our list,
        //and place the appropriate info from the list to the
        //correct GUI id.  Order is important here.
        ListAdapter adapter = new SimpleAdapter(this, mCommentList,
                R.layout.single_comment, new String[] { TAG_SEATNUMBER, TAG_FOODORDERED
                //TAG_DRINKSORDERED, TAG_SERVICES
                         }, new int[] { R.id.seatnumber, R.id.orders
                //R.id.drinkstv, R.id.servicestv,

         });

        // I shouldn't have to comment on this one:
        setListAdapter(adapter);
        // Optional: when the user clicks a list item we 
        //could do something.  However, we will choose
        //to do nothing...
        ListView lv = getListView();    
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // This method is triggered if an item is click within our
                // list. For our example we won't be using this, but
                // it is useful to know in real life applications.
                //new!
            // selected item 
                String product = ((TextView) view).getText().toString();
                // Launching new Activity on selecting single List Item
                Intent i = new Intent(getApplicationContext(), SingleListItem.class);
                // sending data to new activity
                i.putExtra("product", product);
                startActivity(i);
                //end new lines!!


            }
        });
    }   


    public class LoadComments extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Food.this);
            pDialog.setMessage("Loading orders...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected Boolean doInBackground(Void... arg0) {
            //we will develop this method in version 2
            updateJSONdata();
            return null;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
          //we will develop this method in version 2
            updateList();
        }
    }
}

single_item.java

package com.yiqiexample.cc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.single_list_item_view);
        TextView txtProduct = (TextView) findViewById(R.id.product_label);
        Intent i = getIntent();
        // getting attached intent data
        String product = i.getStringExtra("product");
        // displaying selected product name
        txtProduct.setText(product);
    }
}

single_list_item_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView android:id="@+id/product_label"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="25dip"
            android:textStyle="bold"
            android:padding="10dip"
            android:textColor="#ffffff"/>    
</LinearLayout>

食物.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android1:id="@+id/bg2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android1:background="#E0FFFF" >
    <Button
        android1:id="@+id/btnDelete"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content"
        android1:layout_alignParentBottom="true"
        android1:layout_alignParentRight="true"
        android1:text="@string/delete" />
    <Button
        android:id="@+id/servicebtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="358dp"
        android:layout_toRightOf="@+id/foodbutton"
        android:text="SERVICES" />
    <Button
        android1:id="@+id/drinksbtn"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content"
        android1:layout_alignParentBottom="true"
        android1:layout_marginBottom="23dp"
        android1:layout_marginRight="24dp"
        android1:text="DRINKS ORDERS" />
    <LinearLayout
        android:id="@+id/top_layover"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal" >
        <TextView
            android1:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/foodtitle"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/top_layover"
        android1:layout_alignBottom="@+id/servicesdelivered"
        android:background="#fff"
        android:divider="@android:color/transparent"
        android:scrollbars="none"
        android1:clickable="true" />
    <LinearLayout
        android:id="@+id/bottom_layover"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:orientation="horizontal"
        android:weightSum="2" >
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >
            <Button
                android1:id="@+id/backmain"
                android1:layout_width="wrap_content"
                android1:layout_height="wrap_content"
                android1:text="@string/backtomain" />
        </LinearLayout>
    </LinearLayout>
    <Button
        android1:id="@+id/servicesdelivered"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content"
        android1:layout_above="@+id/drinksbtn"
        android1:layout_alignParentLeft="true"
        android1:layout_marginLeft="111dp"
        android1:text="@string/servicesdelivered"
        android1:visibility="invisible" />
</RelativeLayout>

当我尝试单击列表视图时,它似乎是一个错误 -

打开跟踪文件时出错:没有此类文件或目录 (2)

我需要帮助使列表视图可单击,它将进入一个页面,我可以在其中删除特定数据。

 define Listview and Myadapter,DatabaseConnection class  globaly 
 adapter
private ListView listview;
private Myadapter adapter;
private DatabaseConnection databaseconnection;
and in oncreate

   listview = (ListView) findViewById(R.id.list);
   databaseconnection=new DatabaseConnection(this);
   adapter=new Myadapter(this,list);         //  list means pass record as list and create 
    custom adapter thats best way

    listview.setAdapter(adapter);
   listview.setOnItemClickListener(new OnItemClickListener()
   {
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
    { 
      //do something here like-

       here get the id of record from list using listview position and 
        detete record from database using dis id
      databaseconnection.open();            //create the database object first
      deleteRecord(int id);             //pass id for delete that record
      databaseconnection.close();

    }
 });

在代码中,您仍然不使用列表视图。首先全局定义它,例如

private ListView mList;

然后在 onCreate() 中初始化,如下所示:

   mList = (ListView) findViewById(R.id.list);
   mList.setAdapter(your_adapter) //this adapter contains the mCommentList arraylist
   mList.setOnItemClickListener(new OnItemClickListener()
   {
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
    { 
      //do something here
    }
 });

如果使用适配器类在自定义布局中设置值,那就太好了。检查此示例

谢谢

相关内容

  • 没有找到相关文章

最新更新