2

当我经历了许多关于如何在我的应用程序中刷新我的列表视图但仍然无法做到这一点的问题时。

我可以使用的帖子中给出的建议数量,mylist.NotifydataSetCahnged()但我仍然无法解决在哪里应用它。因为我的适配器是在单独的活动中定义的。

我在列表项的每一行都有一个文本视图和一个加号按钮。

单击加号按钮时,我希望它在不刷新整个活动的情况下异步更新相应文本视图中的值。加号按钮单击事件在我的 baseadapter 类中单独声明。

我不知道如何更新我的列表视图,因为我在每次单击加号按钮时都调用意图来刷新我的列表视图。

帮帮我吧。

public class MyOrderList extends Activity {


    public Cursor food_items = null;
    private String item_name;
    private String item_descrp;
    private String item_price;
    private ArrayList<ItemDetails> image_details;

    private String item_id;
    private Cursor order_item;
    private Button order_btn;
    private Button cancel_btn;
    private SQLiteDatabase db;

    private AlertDialog mydialog;
    protected String table_no;
    protected String order_no;
    protected int quantity;
    protected int itemid;
    protected Cursor temp_item;
    public float Total = 0;
    private ListView lv1;
    public int bill_count = 100;
    private Cursor fav_item;
    private String table_name;
    private Calendar c;
    private TextView Title_txt;
    private String device_id;
    private String print_order_items = "";
    private String col_name;

    public static String APP_ID = "346381592110362"; // Replace your App ID

    public Facebook facebook;
    public AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    public SharedPreferences mPrefs;
    private AlertDialog noItemalert;
    private Dialog checkOut;
    private Cursor mac;
    private String Main_table = "T1";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_myorder_view);
        db = openOrCreateDatabase("restaurant", MODE_WORLD_READABLE, null);
        c = Calendar.getInstance();

        // ----initilaizee facebook objects-
        facebook = new Facebook(APP_ID);

        mAsyncRunner = new AsyncFacebookRunner(facebook);
        SessionStore.restore(facebook, this);

        SessionEvents.addAuthListener(new SampleAuthListener());
        SessionEvents.addLogoutListener(new SampleLogoutListener());
        table_name = getIntent().getStringExtra("table_name");
        // WifiManager wifiManager = (WifiManager)
        // getSystemService(Context.WIFI_SERVICE);
        // WifiInfo wInfo = wifiManager.getConnectionInfo();
        // String macAddress = wInfo.getMacAddress();
        //
        // Log.d("IMEI no.", macAddress);
        // mac = db.rawQuery("select * from imei_tbl where imei_code='"
        // + macAddress + "'", null);
        // mac.moveToFirst();
        // if (mac != null)
        // Main_table = mac.getString(1);

        lv1 = (ListView) findViewById(R.id.myorder_lv);
        Title_txt = (TextView) findViewById(R.id.myorder_total);
        Title_txt.setText("Total :" + Total);

        order_btn = (Button) findViewById(R.id.myorder_btn);
        cancel_btn = (Button) findViewById(R.id.myorder_backbtn);

        cancel_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyOrderList.this,
                        FoodCategoryTabs.class);
                Bundle extras = new Bundle();
                extras.putString("category_id", "food_category");
                extras.putString("category_name", "food_category_id");
                intent.putExtras(extras);
                startActivity(intent);

            }
        });

        // ----------------on order click--------------
        order_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int flagx = 0;
                if (food_items.getCount() != 0)
                    showpopup();
                else
                    checkOutPopUp(flagx);

            }

        });

    }

    protected void showpopup() {
        final int flag = 1;

        mydialog = new AlertDialog.Builder(this)
                .setTitle("My Order Alert")
                .setMessage(
                        "Thank you Dear Customer, Your Order will processed soon Would you like to proceed further...")
                .setPositiveButton("Ok", new AlertDialog.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                        continueFunction();
                        checkOutPopUp(flag);
                    }
                })
                .setNeutralButton("Discard", new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        mydialog.dismiss();

                    }
                })

                .create();
        mydialog.show();
    }

    protected void checkOutPopUp(final int flag_value) {
        checkOut = new AlertDialog.Builder(MyOrderList.this)
                .setTitle("CheckOut Alert !")
                .setMessage(
                        "Would you like to continue to add items or checkout..")
                .setPositiveButton("Continue",
                        new AlertDialog.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {

                                Intent intent = new Intent(MyOrderList.this,
                                        FoodCategoryTabs.class);
                                Bundle extras = new Bundle();
                                extras.putString("category_id", "food_category");
                                extras.putString("category_name",
                                        "food_category_id");
                                intent.putExtras(extras);
                                startActivity(intent);

                            }

                        })
                .setNegativeButton("Checkout",
                        new AlertDialog.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                if (flag_value != 0) {
                                    Toast.makeText(getApplicationContext(),
                                            "checkout click", Toast.LENGTH_LONG)
                                            .show();
                                    DBConnection dbConnection = new DBConnection(

                                    getApplicationContext());
                                    try {

                                        dbConnection.createSocket();
                                        dbConnection.dataOutputStream
                                                .writeUTF("3");
                                    } catch (Exception e) {

                                    }

                                    db.delete(table_name, "order_id=100", null);

                                    Cursor fav_cursor = db.rawQuery(
                                            "select * from temp_favourite_tbl",
                                            null);
                                    fav_cursor.moveToFirst();
                                    int length = fav_cursor.getCount();
                                    try {
                                        dbConnection.dataOutputStream
                                                .write(length);
                                    } catch (IOException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    if (fav_cursor != null) {
                                        do {
                                            try {
                                                String query = "insert into favourite_tbl values('";
                                                query = query
                                                        + fav_cursor
                                                                .getString(0)
                                                        + "','"
                                                        + fav_cursor
                                                                .getString(1)
                                                        + "')";
                                                dbConnection.dataOutputStream
                                                        .writeUTF(query);
                                            } catch (Exception e) {

                                            }

                                        } while (fav_cursor.moveToNext());
                                    }
                                    db.execSQL("DROP TABLE IF EXISTS temp_favourite_tbl");
                                    db.execSQL("create table if not exists temp_favourite_tbl(item_id varchar2,user_id varchar2,primary key(item_id))");
                                }
                                if (HeaderFooterActivity.facebook != null) {
                                    if (HeaderFooterActivity.facebook
                                            .isSessionValid()) {
                                        ContentValues cv = new ContentValues();
                                        cv.put("login_txt", "Login");
                                        cv.put("username", "");
                                        cv.put("user_id", "");
                                        db.update("login_tbl", cv, null, null);

                                        HeaderFooterActivity.mAsyncRunner
                                                .logout(getApplicationContext(),
                                                        new LogoutRequestListener());

                                    }
                                } else {

                                    Log.d("logout me exeption", "");
                                }

                                Intent intent = new Intent(MyOrderList.this,
                                        GridViewMenu.class);

                                startActivity(intent);

                            }
                        })

                .create();
        checkOut.show();

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        table_name = getIntent().getStringExtra("table_name");
        getFoodItems(table_name);
        // calculateOrder();
        final ListView lv1 = (ListView) findViewById(R.id.myorder_lv);
        MyOrderAdapter ad = new MyOrderAdapter(this, image_details, table_name);
        ad.notifyDataSetChanged();
        lv1.setAdapter(ad);
    }

    public void continueFunction() {
        try {
            Cursor customer_order = db.rawQuery(
                    "select bill_no from auto_bill", null);
            customer_order.moveToFirst();

            String bill_no = Main_table + customer_order.getCount();
            DBConnection dbConnection = new DBConnection(
                    getApplicationContext());
            dbConnection.createSocket();

            dbConnection.dataOutputStream.writeUTF("2");

            dbConnection.dataOutputStream
                    .writeUTF("insert into auto_bill(bill_no) values('"
                            + bill_no + "')");
            db.execSQL("insert into auto_bill(bill_no) values('" + bill_no
                    + "')");

            System.out.println("passed");

            dbConnection.dataOutputStream
                    .writeUTF("insert into CUSTOMER_BILL(table_no,bill_no,status,price,day,month,year) values('"
                            + Main_table
                            + "','"
                            + bill_no
                            + "','UNPAID',"
                            + Total
                            + ",'"
                            + c.get(Calendar.DAY_OF_MONTH)
                            + "','"
                            + (c.get(Calendar.MONTH) + 1)
                            + "','"
                            + c.get(Calendar.YEAR) + "')");
            Log.d("Month", "" + c.get(Calendar.MONTH));
            ArrayList<String> specialReq = new ArrayList<String>();
            ArrayList<String> quantityList = new ArrayList<String>();
            ArrayList<String> itemNameList = new ArrayList<String>();
            String tempItemId = null;
            Cursor cursor_order = db
                    .rawQuery(
                            "select item.Item_name, order_tbl.special_request,order_tbl.quantity from item, order_tbl where order_tbl.item_id=item.item_code",
                            null);
            cursor_order.moveToFirst();
            if (cursor_order != null) {
                do {

                    itemNameList.add(cursor_order.getString(0));
                    quantityList.add(cursor_order.getInt(2) + "");

                    specialReq.add(cursor_order.getString(1));
                } while (cursor_order.moveToNext());
                dbConnection.dataOutputStream.write(itemNameList.size());
                for (int l = 0; l < itemNameList.size(); l++) {
                    dbConnection.dataOutputStream.writeUTF(Main_table);
                    dbConnection.dataOutputStream.writeUTF(itemNameList.get(l));
                    dbConnection.dataOutputStream.writeUTF(specialReq.get(l));
                    dbConnection.dataOutputStream.writeUTF(quantityList.get(l));
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("EDC", "" + e);
        }

        db.delete(table_name, col_name + " = '" + order_no + "'", null);

    }

    public void getFoodItems(String tableName) {

        food_items = db.rawQuery("select * from " + tableName, null);
        food_items.moveToFirst();
        image_details = getFavResults();
        if (food_items.getCount() != 0) {
            Log.d("count khali nahi h", "bilkl nai h");

            calculateOrder();

        }

    }

    public void calculateOrder() {
        Cursor order;

        Cursor customer_order;
        String bill_no;

        int count;
        Cursor favourite_cursor;

        try {
            DBConnection dbcon = new DBConnection(getApplicationContext());
            db = dbcon.getConnection();
            food_items.moveToFirst();

            col_name = food_items.getColumnName(0);
            Log.d("----------------col_name", col_name);

            if (food_items != null) {
                food_items.moveToFirst();
                Log.d("----------------col_name", "" + food_items.getCount());
                order_no = food_items.getString(0);

                do {
                    order = db.rawQuery(
                            "select item_price,item_name from item where item_code='"
                                    + food_items.getString(1) + "'", null);
                    order.moveToFirst();
                    quantity = food_items.getInt(3);
                    Total += quantity * order.getInt(0);
                    Title_txt.setText("Total :" + Total);
                    Log.d("-------to", "" + Total);
                } while (food_items.moveToNext());
            }

        } catch (Exception e) {
            Log.d("dialog error", e.toString());
        }

    }

    private ArrayList<ItemDetails> getFavResults() {
        ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();

        try {
            if (food_items != null) {
                Log.d("order_tbl ID", "" + food_items.getString(1));
                do {
                    fav_item = db.rawQuery(
                            "select * from item where item_code='"
                                    + food_items.getString(1) + "'", null);
                    fav_item.moveToFirst();
                    item_id = fav_item.getString(1);
                    item_name = fav_item.getString(0);
                    item_descrp = fav_item.getString(2);
                    item_price = fav_item.getString(17);
                    ItemDetails item_details = new ItemDetails();
                    item_details.setName(item_name);
                    item_details.setItem_id(item_id);
                    item_details.setItemDescription(item_descrp);
                    item_details.setPrice(item_price);
                    item_details.setImage(fav_item.getBlob(10));
                    item_details.setcount(food_items.getInt(3));
                    results.add(item_details);
                } while (food_items.moveToNext());

            }
        } catch (Exception e) {
            Log.d("Coooooool Errorrrrrrrrrrrr", e.toString());
        }
        db.close();
        return results;
    }





//-----and myOrderAdapter class----------------------------


public class MyOrderAdapter extends BaseAdapter {

    @Override
    public void notifyDataSetChanged() {
        // TODO Auto-generated method stub
        super.notifyDataSetChanged();
    }

    private static ArrayList<ItemDetails> itemDetailsrrayList;

    private Integer[] imgid = { R.drawable.coffee, R.drawable.coffee,
            R.drawable.coffee, R.drawable.coffee, R.drawable.coffee,
            R.drawable.coffee };

    private LayoutInflater l_Inflater;

    private Context context;

    private String table_name;

    public MyOrderAdapter(Context context, ArrayList<ItemDetails> results,
            String table_name) {
        itemDetailsrrayList = results;
        l_Inflater = LayoutInflater.from(context);
        this.context = context;
        this.table_name = table_name;

    }


    public int getCount() {
        return itemDetailsrrayList.size();
    }

    public Object getItem(int position) {
        return itemDetailsrrayList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();
        if (convertView == null) {
            convertView = l_Inflater.inflate(R.layout.layout_myorder, parent,
                    false);

            holder.txt_itemName = (TextView) convertView
                    .findViewById(R.id.myorder_titletag);

            holder.txt_itemPrice = (TextView) convertView
                    .findViewById(R.id.myorder_price);
            holder.txt_itemQuantity = (TextView) convertView
                    .findViewById(R.id.myorder_quantity);
            holder.itemImage = (ImageView) convertView
                    .findViewById(R.id.myorder_food_img);
            holder.plusBtn = (ImageButton) convertView
                    .findViewById(R.id.myorder_plus_btn);
            holder.minusBtn = (ImageButton) convertView
                    .findViewById(R.id.myorder_minus_btn);
            holder.removeBtn = (Button) convertView
                    .findViewById(R.id.myorder_remove_btn);
            holder.edittext = (TextView) convertView
                    .findViewById(R.id.myorder_edit_txt);

            holder.plusBtn.setOnClickListener(new View.OnClickListener() {

                private SQLiteDatabase db;
                private ItemDetails item_list;
                private ContentValues cv;
                int count = 1;

                @Override
                public void onClick(View v) {
                    item_list = itemDetailsrrayList.get((Integer) v.getTag());
                    count = item_list.getcount();
                    count++;

                    try {
                        DBConnection dbcon = new DBConnection(context);
                        db = dbcon.getConnection();
                        cv = new ContentValues();
                        cv.put("quantity", count);
                        db.update(table_name, cv,
                                "item_id='" + item_list.getItem_id() + "'",
                                null);
                        Intent intent = new Intent(context
                                .getApplicationContext(), MyOrderList.class);
                        intent.putExtra("table_name", table_name);
                        context.startActivity(intent);
                    } catch (Exception e) {
                        Log.d("Count", "" + e);
                    }

                }
            });

            holder.minusBtn.setOnClickListener(new View.OnClickListener() {

                private SQLiteDatabase db;
                private ItemDetails item_list;
                private ContentValues cv;
                int count;

                @Override
                public void onClick(View v) {

                    item_list = itemDetailsrrayList.get((Integer) v.getTag());
                    count = item_list.getcount();

                    if (count > 1)
                        count--;
                    else
                        count = 1;

                    try {
                        DBConnection dbcon = new DBConnection(context);
                        db = dbcon.getConnection();
                        cv = new ContentValues();
                        cv.put("quantity", count);
                        db.update(table_name, cv,
                                "item_id='" + item_list.getItem_id() + "'",
                                null);
                        Intent intent = new Intent(context
                                .getApplicationContext(), MyOrderList.class);
                        intent.putExtra("table_name", table_name);
                        context.startActivity(intent);

                    } catch (Exception e) {
                        Log.d("Count", "" + e);
                    }

                }
            });

            holder.removeBtn.setOnClickListener(new View.OnClickListener() {

                private SQLiteDatabase db;

                private ItemDetails item_list;
                private ContentValues cv;

                @Override
                public void onClick(View v) {

                    try {
                        item_list = itemDetailsrrayList.get((Integer) v
                                .getTag());

                        DBConnection dbcon = new DBConnection(context);
                        db = dbcon.getConnection();

                        db.delete(table_name,
                                "item_id='" + item_list.getItem_id() + "'",
                                null);
                        db.close();

                        Intent intent = new Intent(context
                                .getApplicationContext(), MyOrderList.class);
                        intent.putExtra("table_name", table_name);
                        context.startActivity(intent);

                    } catch (Exception e) {
                        Log.d("errorrrrrr", e.toString());
                    }

                }
            });

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txt_itemName
                .setText(itemDetailsrrayList.get(position).getName());
        holder.txt_itemQuantity.setText("Quantity");

        holder.txt_itemPrice.setText("Rs :"
                + itemDetailsrrayList.get(position).getPrice());
        holder.itemImage.setImageBitmap(itemDetailsrrayList.get(position)
                .getImage());

        holder.edittext.setText(Integer.toString(itemDetailsrrayList.get(
                position).getcount()));

        holder.plusBtn.setTag(position);
        holder.minusBtn.setTag(position);

        holder.removeBtn.setText("Remove");
        holder.removeBtn.setTag(position);

        return convertView;
    }

    public class ViewHolder {

        public TextView edittext;
        public TextView txt_itemQuantity;
        public ImageButton minusBtn;
        public ImageButton plusBtn;
        public Button removeBtn;

        TextView txt_itemName;
        TextView txt_itemDescription;
        TextView txt_itemPrice;
        ImageView itemImage;

        public ViewHolder() {
            // TODO Auto-generated constructor stub
        }

    }
}
4

2 回答 2

0

我已经这样做了几次,在一个单独的类中定义我的适配器并刷新它的数据。不确定这是否是正确的方式,但至少它对我来说就像一种魅力。

我正在做的事情是清除我用来填充列表视图的所有 ArrayList,而不是添加所有新项目并设置adapter.notifySetDataChanged();到我的适配器。

这是一个示例:

如果我在 onCreate 中像这样填充我的列表视图,例如:

ArrayList<String> ids = new ArrayList<String>();
ids.add("one");
ids.add("two");
ids.add("three");

ListView lview = (ListView) findViewById(R.id.mylist);
CustomAdapter adapter = new CustomAdapter(ids);
lview.setAdapter(adapter);

例如,如果我想在按钮单击或任何其他事件上更新我的列表视图,我只需这样做:

   ids.clear();
   ids.add("four");
   ids.add("five");
   ids.add("six");

   adapter.notifySetDataChanged();

瞧!:)

于 2012-09-04T06:57:06.747 回答
0

每当您想更新列表视图网格视图时, 您必须创建一个带有更新数组的新适配器。

listView.setAdapter(new adapter());
listView.invalidateViews();
于 2015-12-29T16:12:09.990 回答