将id分配给listView中的新项

时间:2017-01-06 08:22:56

标签: android sqlite listview

这是我的活动,其中包含listView和操作栏图标。

enter image description here

每次应用运行时,都会通过此方法将SQLite数据加载到listView

 public void retrieveList(String name) {
        database = mdb.getReadableDatabase();
        Cursor cursor = database.rawQuery("SELECT * FROM " + MyDatabaseHelper.TABLE__TASK + " WHERE Name = ? ", new String[]{name}, null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                int iD = cursor.getInt(cursor.getColumnIndex("ID"));
                String month = cursor.getString(cursor.getColumnIndex("Month"));
                double budget = cursor.getDouble(cursor.getColumnIndex("Budget"));
                double totalUsed = cursor.getDouble(cursor.getColumnIndex("Total_Used"));
                if (adapter != null) {
                    adapter.add(iD, month, budget, totalUsed);
                    listview.setAdapter(adapter);
                }
            }
        }
    }

操作栏图标(笔)将打开一个新对话框。点击保存按钮后,它会将新项目添加到listView

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.action_add_task:
                mClickedPosition = -1;
                final AlertDialog.Builder builder = new AlertDialog.Builder(AddMonthlyExpenses.this);
                View promptView = getLayoutInflater().inflate(R.layout.dialog_in_addmonthlyexpenses, null);
                save = (Button) promptView.findViewById(R.id.okBtn);
                month = (EditText) promptView.findViewById(R.id.month);
                budget = (EditText) promptView.findViewById(R.id.budget);
                alert = builder.create();
                alert.setTitle("Add Month ");
                alert.setView(promptView);
                alert.show();

                month.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        showDialog(DATE_DIALOG_ID);
                    }
                });

                save.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        String month1 = month.getText().toString();
                        double budget1 = Double.parseDouble(budget.getText().toString());

                        if ((month1.trim().equals("")) || (String.valueOf(budget1).trim().equals(""))) {
                            Toast.makeText(getApplicationContext(), " Not Completed", Toast.LENGTH_SHORT).show();
                        } else {
                                adapter.add(id,month1, budget1);
                                Toast.makeText(getApplication(),id+"",Toast.LENGTH_SHORT).show(); // display 0
                                insert(name, month1, budget1);
                                listview.setAdapter(adapter);
                                alert.dismiss();
                                //retrieveList(String name)
                            }
                        }
                    }
                });

                break;

ExpensesAdapter

 public class ExpensesAdapter extends BaseAdapter {

    private static ArrayList<List> search;
    private LayoutInflater mInflater;
    ListView listview;
    Context context;
    double used = 0;

    public ExpensesAdapter(Context context, ArrayList<List> searchList, ListView listview) {
        this.search=searchList;
        this.listview=listview;
        mInflater = LayoutInflater.from(context);
        this.context= context;
    }

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

    public List getItem(int position) {
        return search.get(position);
    }

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

    public void removeItem(int position) {
        search.remove(position);
        this.notifyDataSetChanged();
    }

    public void add(int id,String month,double budget,double used)
    {
        List obj = new List(id,month,budget,used);
        this.used=used;
        obj.setID(id);
        obj.setMonthYear("   " + month);
        obj.setBudget(budget);
        obj.setUsed(used);
        search.add(obj);
        this. notifyDataSetChanged();
    }

    public void add(int id,String month, double budget)
    {
        List obj = new List(id,month,budget);
        obj.setMonthYear("   " + month);
        obj.setID(id);
        obj.setBudget(budget);
        search.add(obj);
        this. notifyDataSetChanged();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder =null;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.expenses_adapter, null);
            holder= new ViewHolder();
            holder.monthAndYear = (TextView) convertView.findViewById(R.id.monthAndYear);
            holder.budget = (TextView) convertView.findViewById(R.id.budget);
            holder.amount=(TextView)convertView.findViewById(R.id.amount);
            holder.progressBar=(ProgressBar)convertView.findViewById(R.id.downloadProgressBar);
            holder.balance=(TextView)convertView.findViewById(R.id.balance);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.monthAndYear.setText(search.get(position).getMonthAndYear());
        holder.budget.setText("RM" + "" + search.get(position).getBudget());
        holder.amount.setText("RM" + "" + search.get(position).getUsed());
        holder.progressBar.setProgress((int) search.get(position).getUsed());
        holder.progressBar.setMax((int) search.get(position).getBudget());
        double a = search.get(position).getBudget();
        double b = search.get(position).getUsed();
        holder.balance.setText("RM"+""+String.format("%.2f", a-b));
        return convertView;
    }

    static class ViewHolder {
        TextView monthAndYear, budget,amount,balance;
        ProgressBar progressBar;
    }
}

在listView中添加新项目并按下它后,我得到id= 0。如果我退出应用并再次单击,则只显示新ID。有没有办法让新ID分配到新的列表项而不是退出应用程序或在retrieveList之后调用alert.dismiss();方法?

3 个答案:

答案 0 :(得分:0)

在你的适配器中你没有将id设置为obj

public void add(int id,String month,double budget,double used)
{
    List obj = new List(id,month,budget,used);
    this.used=used;
    obj.setMonthYear("   " + month);
    obj.setBudget(budget);
    obj.setUsed(used);
   //Add this line your adapter
    obj.setID(id);
    search.add(obj);
    this. notifyDataSetChanged();
}

public void add(int id,String month, double budget)
{
    List obj = new List(id,month,budget);
    obj.setMonthYear("   " + month);
    obj.setBudget(budget);
    //Add this line your adapter
    obj.setID(id);
    search.add(obj);
    this. notifyDataSetChanged();
}

答案 1 :(得分:0)

您的getItemId()始终返回0.要匹配getItem()尝试返回类似的内容:

public long getItemId(int position) {
   List l = getItem(positon);
   return l.getId();
}

当然,您的列表必须有getId(),并返回long

答案 2 :(得分:0)

我用这个方法解决了

insert(name, month1, budget1);更改为long id= insert(name, month1, budget1);以获取最新ID。然后修改代码到

  save.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        String month1 = month.getText().toString();
                        double budget1 = Double.parseDouble(budget.getText().toString());

                        if ((month1.trim().equals("")) || (String.valueOf(budget1).trim().equals(""))) {
                            Toast.makeText(getApplicationContext(), " Not Completed", Toast.LENGTH_SHORT).show();
                        } else {
                                long id=insert(name, month1, budget1);
                                adapter.add(id,month1, budget1);
                                listview.setAdapter(adapter);
                                alert.dismiss();
                                check();
                            }
                        }
                    }
                });