Listview empty after insert a field in db?

感情迁移 提交于 2019-12-25 05:15:12

问题


I was looking for an example/tutorial to insert datas in a sqlLite db and display the datas in a listview. Well this is a good example: http://androidsolution4u.blogspot.it/2013/09/android-populate-listview-from-sqlite.html And it works. I implemented the code in mine and works. The problem is that if i want insert another one filed nothing appears in the listview and the activity is empty.I added a field called address as string like the others and in every part of code i added what is need copying from the others (of course changing the names). But when i try to add the item not appears. Of course i update the xml files with new field. I can't write the whole code because it's too much. But if someone can help me to find a way out i'll write the part of code required. Thanks EDIT: the code is equal at the example but with the field i need to add.

The DisplayActivity

public class DisplayActivity extends Activity {

    private DbHelper mHelper;
    private SQLiteDatabase dataBase;

    private ArrayList<String> userId = new ArrayList<String>();
    private ArrayList<String> user_fName = new ArrayList<String>();
    private ArrayList<String> user_lName = new ArrayList<String>();
    private ArrayList<String> user_address = new ArrayList<String>();

    private ListView userList;
    private AlertDialog.Builder build;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_activity);

        userList = (ListView) findViewById(R.id.List);

        mHelper = new DbHelper(this);

        //add new record
        findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), AddActivity.class);
                i.putExtra("update", false);
                startActivity(i);

            }
        });

        //click to update data
        userList.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                Intent i = new Intent(getApplicationContext(), AddActivity.class);
                i.putExtra("Fname", user_fName.get(arg2));
                i.putExtra("Lname", user_lName.get(arg2));
                i.putExtra("address", user_address.get(arg2));
                i.putExtra("ID", userId.get(arg2));
                i.putExtra("update", true);
                startActivity(i);

            }
        });

        //long click to delete data
        userList.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {

                build = new AlertDialog.Builder(DisplayActivity.this);
                build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2) + " " + user_address(arg2));
                build.setMessage("Do you want to delete ?");
                build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {

                                Toast.makeText( getApplicationContext(),
                                        user_fName.get(arg2) + " "
                                                + user_lName.get(arg2)
                                                + user_address.get(arg2)
                                                + " is deleted.", 3000).show();

                                dataBase.delete(
                                        DbHelper.TABLE_NAME,
                                        DbHelper.KEY_ID + "="
                                                + userId.get(arg2), null);
                                displayData();
                                dialog.cancel();
                            }
                        });

                build.setNegativeButton("No", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                            }
                        });
                AlertDialog alert = build.create();
                alert.show();

                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        displayData();
        super.onResume();
    }

    /**
     * displays data from SQLite
     */
    private void displayData() {
        dataBase = mHelper.getWritableDatabase();
        Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);

        userId.clear();
        user_fName.clear();
        user_lName.clear();
        user_address.clear();
        if (mCursor.moveToFirst()) {
            do {
                userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
                user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
                user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

            } while (mCursor.moveToNext());
        }
        DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName, user_address);
        userList.setAdapter(disadpt);
        mCursor.close();
    } 

}

The DisplayAdapter

public class DisplayAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> id;
    private ArrayList<String> firstName;
    private ArrayList<String> lastName;
    private ArrayList<String> address;


    public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> address) {
        this.mContext = c;

        this.id = id;
        this.firstName = fname;
        this.lastName = lname;
        this.address = address;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return id.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.listcell, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
            mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
            mHolder.txt_address = (TextView) child.findViewById(R.id.txt_address);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_id.setText(id.get(pos));
        mHolder.txt_fName.setText(firstName.get(pos));
        mHolder.txt_lName.setText(lastName.get(pos));
        mHolder.txt_address.setText(address.get(pos));

        return child;
    }

    public class Holder {
        TextView txt_id;
        TextView txt_fName;
        TextView txt_lName;
        TextView txt_address;
    }

}

The DbHelper

public class DbHelper extends SQLiteOpenHelper {
    static String DATABASE_NAME="userdata";
    public static final String TABLE_NAME="user";
    public static final String KEY_FNAME="fname";
    public static final String KEY_LNAME="lname";
    public static final String KEY_ID="id";
    public static final String KEY_ADDRESS="address";
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_ADDRESS+" TEXT)";
        db.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);

    }

}

And the AddActivity

public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,edit_address;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,address;
private boolean isUpdate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_activity);

        btn_save=(Button)findViewById(R.id.save_btn);
        edit_first=(EditText)findViewById(R.id.frst_editTxt);
        edit_last=(EditText)findViewById(R.id.last_editTxt);
        edit_address=(EditText)findViewById(R.id.address_editTxt);

       isUpdate=getIntent().getExtras().getBoolean("update");
        if(isUpdate)
        {
            id=getIntent().getExtras().getString("ID");
            fname=getIntent().getExtras().getString("Fname");
            lname=getIntent().getExtras().getString("Lname");
            address=getIntent().getExtras().getString("address");
            edit_first.setText(fname);
            edit_last.setText(lname);
            edit_address.setText(address);

        }

         btn_save.setOnClickListener(this);

         mHelper=new DbHelper(this);

    }

    // saveButton click event 
    public void onClick(View v) {
        fname=edit_first.getText().toString().trim();
        lname=edit_last.getText().toString().trim();
        address=edit_address.getText().toString().trim();
        if(fname.length()>0 && lname.length()>0 && address.length()>0)
        {
            saveData();
        }
        else
        {
            AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
            alertBuilder.setTitle("Invalid Data");
            alertBuilder.setMessage("Please, Enter valid data");
            alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                       dialog.cancel();

                }
            });
            alertBuilder.create().show();
        }

    }

    /**
     * save data into SQLite
     */
    private void saveData(){
        dataBase=mHelper.getWritableDatabase();
        ContentValues values=new ContentValues();

        values.put(DbHelper.KEY_FNAME,fname);
        values.put(DbHelper.KEY_LNAME,lname );
        values.put(DbHelper.KEY_ADDRESS,address );

        System.out.println("");
        if(isUpdate)
        {    
            //update database with new data 
            dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
        }
        else
        {
            //insert data into database
            dataBase.insert(DbHelper.TABLE_NAME, null, values);
        }
        //close database
        dataBase.close();
        finish();


    }

}

That's all. I can't find the problem. Helps?


回答1:


Forgotten in displayData() user_address.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ADDRESS)));



来源:https://stackoverflow.com/questions/19315767/listview-empty-after-insert-a-field-in-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!