Android设置并从列表中获取值并保存到db sqlite

时间:2016-08-24 09:38:31

标签: android

您好我想知道如何从列表视图中的文本字段中保存值并将它们独立保存到myDb。

我有两个表父母和子女,需要将数据保存到。

listview布局有一个textview和edittext字段,其中textview字段是从数据库填充的数据,edittext应该使用textview值id将数据保存到数据库,但在另一个表中。

Screenshot of UI

我想保存父表上屏幕中的其他字段并将listview数据保存在子表中...应该具有父表的表ID,textview项的值id和设置的数量

这是我的主要

public class ProducedMilk extends AppCompatActivity implements View.OnClickListener {
private DatePickerDialog dateto;
EditText txtdate,txtsoldamt;
TextView tvtotalproduced;
Button btnsubmit;
ArrayList<Milk> milkList;
private SimpleDateFormat dateFormatter;
private ListView cowlist;
private SimpleCursorAdapter dataAdapter;
DatabaseHelper db;

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.activity_produced_milk);
    Toolbar toolbar = (Toolbar) findViewById (R.id.toolbar);
    setSupportActionBar (toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled (true);
    toolbar.setNavigationOnClickListener (new View.OnClickListener () {
        @Override
        public void onClick (View v) {
            onBackPressed ();
            Intent intent = new Intent (ProducedMilk.this, MainActivity.class);
            startActivity (intent);
        }
    });

    dateFormatter = new SimpleDateFormat ("dd/MM/yyyy", Locale.US);
    findViewsById ();
    setDateTimeField ();

    // get Database Handler
    db = new DatabaseHelper (getApplicationContext());

    //Generate ListView from Database
    displayListView ();

    tvtotalproduced=(TextView)findViewById (R.id.totalamt);
    txtsoldamt=(EditText)findViewById(R.id.cbeamt);
    cowlist = (ListView) findViewById (R.id.lvadd);
    btnsubmit=(Button)findViewById (R.id.submitmilk);
    btnsubmit.setOnClickListener (this);
}

private void displayListView () {
    Cursor cursor = db.fetchInMilkCows ();
    // The desired columns to be bound
    String[] columns = new String[]{
            DatabaseHelper.KEY_NAME
    };
    // the XML defined views which the data will be bound to
    int[] to = new int[]
            {
                    R.id.cownamelv
            };
    // create the adapter using the cursor pointing to the desired data
    //as well as the layout information
    dataAdapter = new SimpleCursorAdapter (this, R.layout.milkproductlv, cursor, columns, to, 0);
    cowlist = (ListView) findViewById (R.id.lvadd);
    // Assign adapter to ListView
    cowlist.setAdapter (dataAdapter);

}

private void findViewsById () {
    txtdate=(EditText)findViewById(R.id.dateproduc);
    txtdate.setInputType (InputType.TYPE_NULL);
    txtdate.requestFocus ();
}

private void setDateTimeField () {
    txtdate.setOnClickListener (this);
    Calendar newCalendar = Calendar.getInstance ();
    dateto = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener () {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            txtdate.setText(dateFormatter.format(newDate.getTime()));
        }
    },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}

@Override
public void onClick (View v) {
    if(v == txtdate) {
        dateto.show();
    }
    switch (v.getId ()) {
        case R.id.submitmilk:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Do you want to save these details ?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            String date_produced = txtdate.getText ().toString ();
                            String quantity = txtsoldamt.getText ().toString ();
                            // check if any of the fields are vaccant
                            if (date_produced.equals ("")) {
                                Toast.makeText (getApplicationContext (), "Field(s) Vaccant", Toast.LENGTH_LONG).show ();
                                Intent refresh = new Intent (getApplicationContext (), ProducedMilk.class);
                                startActivity (refresh);
                            } else {
                                // Save the Data in Database
                                milkList = new ArrayList<Milk>();
                                for(int i = 0; i < cowlist.getAdapter().getCount(); i++) {
                                     new Milk (cowlist.getAdapter ().getItem (i));
                                }
                                db.createMilkProduction (date_produced);
                                db.createSale (date_produced,quantity);
                                Toast.makeText (getApplicationContext (), "Submitted Successfully ", Toast.LENGTH_LONG).show ();
                                Intent refresh = new Intent (getApplicationContext (), ProducedMilk.class);
                                startActivity (refresh);
                            }
                            finish();
                        }
                    })
                    .setNegativeButton("Back", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //  Action for 'NO' Button
                            dialog.cancel();
                        }
                    });
            //Creating dialog box
            AlertDialog alert = builder.create();
            //Setting the title manually
            alert.setTitle ("Produced Milk");
            alert.show ();
    }
}

}

这是我的处理程序

public class DatabaseHelper extends SQLiteOpenHelper {

    // Logcat tag
    private static final String LOG = "DatabaseHelper";

    // Database Version
    private static final int DATABASE_VERSION = 3;
    // Database Name
    private static final String DATABASE_NAME = "farmers";
    // Table Names
    private static final String TABLE_USER = "users";
    private static final String TABLE_COW = "cows";
    private static final String TABLE_MILK = "milk";
    private static final String TABLE_SALES= "sales";
    // Common column names
    public static final String KEY_CREATED_AT = "created_at";
    public static final String KEY_ID = "_id";
    // user Table - column names
    public static final String  KEY_USERNAME= "username";
    public static final String  KEY_CODE = "farmerscode";
    public static final String  KEY_PASSWORD = "password";
    // cows Table - column names
    public static final String  KEY_NAME = "name";
    public static final String  KEY_AGE = "age";
    public static final String  KEY_BREED = "breed";
    //public static final String  KEY_COLOR = "color";
    public static final String  KEY_CATEGORY = "category";

    // milk Table - column names
    public static final String KEY_DATE_PRODUCED = "date_produced";
    public static final String KEY_COW = "cow_id";
    public static final String KEY_QTY= "quantity";

    // sales Table - column names
    public static final String KEY_DPRODUCED = "date_produced";
    public static final String KEY_QTY_SOLD = "total_sold";

    // Table Create Statements

    // user table create statement
    private static final String CREATE_TABLE_USER = "CREATE TABLE "
        + TABLE_USER+ "("
        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_USERNAME + " VARCHAR,"+ KEY_CODE + " VARCHAR,"       
        + KEY_PASSWORD + " VARCHAR," + KEY_CREATED_AT + " DATETIME" + ")";

        // cows table create statement
        private static final String CREATE_TABLE_COW = "CREATE TABLE "
        + TABLE_COW + "("
        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"+KEY_AGE+ "          NUMERIC,"
        + KEY_BREED + " TEXT,"+ KEY_CATEGORY + " TEXT, "+ KEY_CREATED_AT + "   DATETIME" + ")";


     // milk table create statement
     private static final String CREATE_TABLE_MILK = "CREATE TABLE "
        + TABLE_MILK+ "("
        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE_PRODUCED + " DATETIME," + KEY_COW + " INTEGER,"+ KEY_QTY + " NUMERIC,"
         + KEY_CREATED_AT + " DATETIME" + " FOREIGN KEY ("+KEY_COW+") REFERENCES "+TABLE_COW+"("+KEY_ID+"));";

// sales table create statement
private static final String CREATE_TABLE_SALES = "CREATE TABLE "
        + TABLE_SALES+ "("
        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_DPRODUCED + " DATETIME," + KEY_QTY_SOLD + " NUMERIC,"+ KEY_CREATED_AT + " DATETIME," + ")";

public DatabaseHelper(Context context) {
    super (context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    // creating required tables
    db.execSQL (CREATE_TABLE_USER);
    db.execSQL (CREATE_TABLE_COW);
    db.execSQL (CREATE_TABLE_MILK);
    db.execSQL (CREATE_TABLE_SALES);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // on upgrade drop older tables
    db.execSQL ("DROP TABLE IF EXISTS " + TABLE_USER);
    db.execSQL ("DROP TABLE IF EXISTS " + TABLE_COW);
    db.execSQL ("DROP TABLE IF EXISTS " + TABLE_MILK);
    db.execSQL ("DROP TABLE IF EXISTS " + TABLE_SALES);

    // create new tables
    onCreate (db);
}

// ------------------------ "USER" table methods ----------------//

/**
 * Creating a Farmer
 */
public long createUser (String username, String farmerscode, String password) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues initialValues = new ContentValues ();
    initialValues.put(KEY_USERNAME, username);
    initialValues.put(KEY_CODE, farmerscode);
    initialValues.put(KEY_PASSWORD, password);
    initialValues.put(KEY_CREATED_AT, getDateTime());

    return db.insert(TABLE_USER, null, initialValues);
}

/**
 * getting user count
 */
public int getuserCount() {
    String countQuery = "SELECT  * FROM " + TABLE_USER;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}

/**
 * getting single user
 */
public String getSinlgeEntry(String username) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query("users", null, " username=?",
            new String[] { username }, null, null, null);
    if (cursor.getCount() < 1) {
        cursor.close();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String password = cursor.getString(cursor.getColumnIndex("password"));
    cursor.close();
    return password;
}

public String getUsername() throws SQLException {
    String username = "";
    Cursor cursor = this.getReadableDatabase().query(
            TABLE_USER, new String[] { KEY_USERNAME },
            null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            username = cursor.getString(0);
        } while (cursor.moveToNext());
    }
    cursor.close();

    return username;
}
/**
 * getting user
 */
public Cursor fetchUser() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor mCursor = db.query (TABLE_USER, new String[]{KEY_ID,
                    KEY_USERNAME, KEY_CODE},
            null, null, null, null, null);

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

public Cursor fetch() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor resultSet = db.rawQuery ("Select * from users", null);
resultSet.moveToFirst ();
return resultSet;


public long createCow (String name, String age, String breed, String category) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_AGE, age);
    initialValues.put(KEY_BREED, breed);
    //initialValues.put(KEY_COLOR, color);
    initialValues.put(KEY_CATEGORY, category);
    initialValues.put(KEY_CREATED_AT, getDateTime());

    return db.insert(TABLE_COW, null, initialValues);
}

/**
 * getting all cows
 */
public Cursor fetchInMilkCows() {
    String im ="In Milk";
    String query = "SELECT _id,name FROM cows WHERE category ='"+im+"'";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor  cursor = db.rawQuery(query,null);

    if (cursor != null) {
        cursor.moveToFirst();
    }
    return cursor;
}
public Cursor fetchAllCows() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor mCursor = db.query (TABLE_COW, new String[]{KEY_ID,
                    KEY_NAME, KEY_AGE, KEY_BREED, KEY_CATEGORY},
            null, null, null, null, null);

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

public Cursor getCowsData(int _id){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery( "select * from cows where _id="+_id+"", null );
    return res;
}
/**
 * getting cow count
 */
public int getCowsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_COW;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}

public int getCowsMilkCount() {
    String im ="In Milk";
    String countQuery = "SELECT * FROM cows WHERE category ='"+im+"'";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}


public boolean updateCow (Integer _id, String name, String age, String breed,String category) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEY_NAME, name);
    contentValues.put(KEY_AGE, age);
    contentValues.put(KEY_BREED, breed);
    //contentValues.put(KEY_COLOR, color);
    contentValues.put(KEY_CATEGORY, category);
    contentValues.put(KEY_CREATED_AT, getDateTime());

    db.update("cows", contentValues, "_id = ? ", new String[] { Integer.toString(_id) } );
    return true;
}


public ArrayList getAllCows() {
    ArrayList array_list = new ArrayList ();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery( "select * from cows", null );
    res.moveToFirst();
    while(res.isAfterLast() == false){
        array_list.add(res.getString(res.getColumnIndex(KEY_NAME)));
        res.moveToNext();
    } return array_list;
}


public Integer deleteCow (Integer _id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete("cows", "_id = ? ", new String[] {
            Integer.toString(_id) });
}

/**
 * delete all cows
 */
public int deleteAllCows(){
    SQLiteDatabase db = this.getReadableDatabase();
    return db.delete(TABLE_COW, null, null);

}

public long createMilkProduction (String date_produced,Integer cow,String qty_produced) {

    SQLiteDatabase db = this.getReadableDatabase();

    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_DATE_PRODUCED, date_produced);
    initialValues.put(KEY_COW,cow);
    initialValues.put(KEY_QTY,qty_produced);
    initialValues.put(KEY_CREATED_AT, getDateTime());

    return db.insert(TABLE_MILK, null, initialValues);
}
/**
 * getting MilkProduction count
 */
public int getMilkcount() {
    String countQuery = "SELECT  * FROM " + TABLE_MILK;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);

    int count = cursor.getCount();
    cursor.close();

    // return count
    return count;
}

public long createSale (String date_produced, String quantity) {
    SQLiteDatabase db = this.getWritableDatabase ();

    ContentValues initialValues = new ContentValues();
    initialValues.put (KEY_DPRODUCED,date_produced);
    initialValues.put(KEY_QTY_SOLD, quantity);
    initialValues.put(KEY_CREATED_AT, getDateTime());

    return db.insert(TABLE_SALES, null, initialValues);
}

public int getSalesDetcount() {
    String countQuery = "SELECT  * FROM " + TABLE_SALES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);

    int count = cursor.getCount();
    cursor.close();

    // return count
    return count;
}

// closing database
public void closeDB() {
    SQLiteDatabase db = this.getReadableDatabase ();
    if (db != null && db.isOpen())
        db.close();
}

private String getDateTime() {
    SimpleDateFormat dateFormat = new SimpleDateFormat (
            "yyyy-MM-dd HH:mm:ss", Locale.getDefault ());
    Date date = new Date ();
    return dateFormat.format(date);
}

}

提交按钮

     switch (v.getId ()) {
        case R.id.submitmilk:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Do you want to save these details ?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            String date_produced = txtdate.getText ().toString ();
                            String quantity = txtsoldamt.getText ().toString ();


                           }
                            View v;
                            ArrayList<String> cowmilkamt = new ArrayList<>();
                            for (int i = 0; i < cowlist.getCount(); i++) {
                                cowlist.getAdapter ().getView (i, null, null);
                                v = cowlist.getChildAt(i);
                                //txtcowamt = (EditText) findViewById (i);
                                txtcowamt = (EditText) v.findViewById (R.id.cowmilkamt);
                                cowmilkamt.add (txtcowamt.getText ().toString ());
                            }

                            String cow=cursor.getString(cursor.getColumnIndex("_id"));
                            String qty_produced=txtcowamt.getText ().toString ();
                            // check if any of the fields are vaccant
                            if (date_produced.equals ("")||qty_produced.equals ("")) {
                                Toast.makeText (getApplicationContext (), "Field(s) Vaccant", Toast.LENGTH_LONG).show ();
                                Intent refresh = new Intent (getApplicationContext (), ProducedMilk.class);
                                startActivity (refresh);
                            } else {
                                db.createMilkProduction (date_produced, Integer.valueOf (cow), qty_produced);
                                db.createSale (date_produced,quantity);
                                Toast.makeText (getApplicationContext (), "Submitted Successfully ", Toast.LENGTH_LONG).show ();
                                Intent refresh = new Intent (getApplicationContext (), ProducedMilk.class);
                                startActivity (refresh);
                            }
                            finish();
                        }
                    })
                    .setNegativeButton("Back", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //  Action for 'NO' Button
                            dialog.cancel();
                        }
                    });
            //Creating dialog box
            AlertDialog alert = builder.create();
            //Setting the title manually
            alert.setTitle ("Produced Milk");
            alert.show ();
    }

任何帮助都会非常有帮助。 感谢。

2 个答案:

答案 0 :(得分:0)

将此声明为全局

Cursor cursor;

然后在

中使用它
private void displayListView () {
 cursor = db.fetchInMilkCows ();

然后像这样设置一个listonitemclick监听器

     cowlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

list_Position=position;

        }}

还声明list_position字段

int list_Position;

然后使用此位置从光标获取数据,将此代码放入警报

  cursor.move(list_Position);
String id=cursor.getString(cursor.getColumnIndex("_id"));
String name=cursor.getString(cursor.getColumnIndex("name"));

答案 1 :(得分:0)

所以我是我的最终工作代码

 switch (v.getId ()) {
        case R.id.submitmilk:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Do you want to save these details ?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            String date_produced = txtdate.getText ().toString ();
                            String quantity = txtsoldamt.getText ().toString ();

                            int count = cowlist.getAdapter().getCount();
                            for (int i = 0; i < count; i++) {
                                LinearLayout itemLayout = (LinearLayout) cowlist.getChildAt (i);
                                // Find by under LinearLayout
                                TextView txtid = (TextView)itemLayout.findViewById(R.id.cowidamt);
                                EditText txtInput = (EditText) itemLayout.findViewById (R.id.cowmilkamt);

                               // String cow = cursor.getString (cursor.getColumnIndex ("_id"));
                                String cow = txtid.getText().toString();
                                String qty_produced = txtInput.getText ().toString ();

                                // check if any of the fields are vaccant
                                if (date_produced.equals ("")||qty_produced.equals ("")) {
                                    Toast.makeText (getApplicationContext (), "Field(s) Vaccant", Toast.LENGTH_LONG).show ();
                                    Intent refresh = new Intent (getApplicationContext (), ProducedMilk.class);
                                    startActivity (refresh);
                                } else {
                                    db.createMilkProduction (date_produced, Integer.valueOf (cow), qty_produced);
                                    db.createSale (date_produced,quantity);
                                    Toast.makeText (getApplicationContext (), "Submitted Successfully ", Toast.LENGTH_LONG).show ();
                                    Intent refresh = new Intent (getApplicationContext (), ProducedMilk.class);
                                    startActivity (refresh);
                                }
                                finish();
                            }

                        }
                    })
                    .setNegativeButton("Back", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //  Action for 'NO' Button
                            dialog.cancel();
                        }
                    });
            //Creating dialog box
            AlertDialog alert = builder.create();
            //Setting the title manually
            alert.setTitle ("Produced Milk");
            alert.show ();
    }