Android设置并从列表中获取值并保存到数据库sqlite

问题描述:

嗨,我想知道如何我可以保存从列表视图中的文本字段的值,并将它们独立保存到myDb。Android设置并从列表中获取值并保存到数据库sqlite

我有两个表父母和孩子的数据需要保存到。

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

Screenshot of UI

我想保存等领域,在对父表中的画面并保存在子表...应该具备哪些父表ID列表视图数据,和值id TextView的的项目和金额正在设置。

这是我的主要

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

@ UmarAta我只是显示的信息,并想知道如何保存文本字段的值。这是如何提取文本视图项目 public cursor fetchInMilkCows(){ \t \t String im =“In Milk”; \t \t String query =“SELECT _id,name FROM cows WHERE category ='”+ im +“'”; \t \t SQLiteDatabase db = this.getReadableDatabase(); \t \t游标cursor = db。rawQuery(查询,NULL); \t \t if(cursor!= null){ \t \t \t cursor.moveToFirst(); \t \t} \t \t return cursor; \t} –

+0

在UI IM发布完整的代码,请 –

声明此为全球

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; 

然后提取采用了这个位置从光标数据,把这个代码的警报内

​​
+0

Im有点钝这个更详细的答案将帮助很多 –

+0

你问题是解决 –

+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(); 
    }