向SQLite数据库添加更多内容

时间:2017-02-19 21:50:12

标签: java android sqlite datepicker spinner

让我们开始。

DatabaseHelper.java

   var elements = SVG.select('g#figure')
                .transform({rotate: 90});

AddActivity.java

package com.example.soultaker.overtimesregistrator;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "mylogs.db";
    public static final String TABLE_NAME = "mylogs_table";
    public static final String COL0 = "ID";
    public static final String COL1 = "DATE";
    public static final String COL2 = "HOURS";
    public static final String COL3 = "SHIFT";


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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME
                + "("
                + COL0 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COL1 + " TEXT, "
                + COL2 + " TEXT, "
                + COL3 + " TEXT, "
                + ")"
        );
    }
        @Override
        public void onUpgrade (SQLiteDatabase db,int oldVersion, int newVersion){
            db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
            onCreate(db);
        }

    public boolean addData(String date, String hours, String shift){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL1,date);
        contentValues.put(COL2,hours);
        contentValues.put(COL3, shift);

        long result  = db.insert(TABLE_NAME, null, contentValues);

        if(result == -1){
            return false;
        }else{
            return true;
        }
    }

    public Cursor showData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
        return data;
    }

    public boolean updateData(String id, String date, String hours, String shift){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL0,id);
        contentValues.put(COL1,date);
        contentValues.put(COL2,hours);
        contentValues.put(COL3,shift);
        db.update(TABLE_NAME, contentValues, "ID = ?", new String[] {id});
        return true;
    }
}

MainActivity.java

    import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class AddActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    DatabaseHelper mylogsDB;
    Button btn_save;
    EditText etHours;
    Spinner etShift;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        etHours = (EditText) findViewById(R.id.editText);
        etShift = (Spinner) findViewById(R.id.spinner);
        btn_save = (Button) findViewById(R.id.btn_save);
        mylogsDB = new DatabaseHelper(this);

        AddData();

        // Spinner click listener
        etShift.setOnItemSelectedListener(this);

        // Spinner Drop down elements
        List<String> categories = new ArrayList<>();
        categories.add("Πρωί");
        categories.add("Μεσημέρι");
        categories.add("Νύχτα");

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        etShift.setAdapter(dataAdapter);
    }

        public void onItemSelected (AdapterView <?> parent, View view,int position, long id) {
            // On selecting a spinner item
            String item = parent.getItemAtPosition(position).toString();

            // Showing selected spinner item
            Toast.makeText(parent.getContext(), "Έχετε επιλέξει: " + item, Toast.LENGTH_LONG).show();
    }


    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }

    public void AddData() {
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String hours = etHours.getText().toString();
                String shift = etShift.getSelectedItem().toString();

                boolean insertData = mylogsDB.addData(hours, shift);

                if (insertData == true) {
                    Toast.makeText(AddActivity.this, "Η αποθήκευση ολοκληρώθηκε επιτυχώς.", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(AddActivity.this, "Ώχ,Κάτι πήγε στραβά.", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

在MainActivity中,我在这些行中出现错误

package com.example.soultaker.overtimesregistrator;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    DatabaseHelper mylogsDB;
    Button btn_add, btn_view, btn_edit;
    EditText hours, etID;
    DatePicker date;
    Spinner shift;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_edit = (Button) findViewById(R.id.btn_edit);
        btn_view = (Button) findViewById(R.id.btn_view);
        date = (DatePicker) findViewById(R.id.datePicker);
        hours = (EditText) findViewById(R.id.editText);
        shift = (Spinner) findViewById(R.id.spinner);
        mylogsDB = new DatabaseHelper(this);

        UpdateData();

        btn_add.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
            }
        });

        btn_view.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, LogsView.class);
                startActivity(intent);
            }
        });
    }

        public void UpdateData(){
            btn_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int temp = etID.getText().toString().length();
                    if (temp > 0) {
                        boolean update = mylogsDB.updateData(etID.getText().toString(), date.getText().toString(),
                                hours.getText().toString(), shift.getText().toString());
                        if (update == true) {
                            Toast.makeText(MainActivity.this, "Successfully Updated Data!", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Something Went Wrong :(.", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "You Must Enter An ID to Update :(.", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    }
}

  

仅在日期,转移方法getText无法解析。

LogsView.java

boolean update = mylogsDB.updateData(etID.getText().toString(), date.getText().toString(),
                                hours.getText().toString(), shift.getText().toString());

知道为什么会出现这些错误吗?我现在太困惑了,找不到我错的地方。

我正在尝试添加package com.example.soultaker.overtimesregistrator; import android.database.Cursor; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class LogsView extends AppCompatActivity { DatabaseHelper mylogsDB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_logs_view); ListView listView = (ListView) findViewById(R.id.list_view); mylogsDB = new DatabaseHelper(this); //populate an ArrayList<String> from the database and then view it ArrayList<String> theList = new ArrayList<>(); Cursor data = mylogsDB.showData(); if(data.getCount() == 0){ Toast.makeText(this, "There are no contents in this list!",Toast.LENGTH_LONG).show(); }else{ while(data.moveToNext()){ theList.add(data.getString(1)); ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList); listView.setAdapter(listAdapter); } } } } DatePicker。但我还没有完成Spinner

1 个答案:

答案 0 :(得分:0)

  

在AddActivity中,我在这些行中收到错误

String date = date.getText().toString();
String hours = hours.getText().toString();
String shift = shift.getText().toString();
     

它说

     

变量日期,小时,班次可能尚未初始化。

我在这里看到很多错误:

  1. date.getText().toString();没有这样的归档变量date,因此date的错误无法解决! 此外,如果您错过了创建此变量date并且您将创建,那么您必须在此date中更改字符串变量String date的名称,因为您无法创建两个变量同名。

  2. 同样适用于String hoursEdittext hours,您再也无法创建两个名称相同的变量!

  3. 同样String shiftSpinner shift,您再也无法创建两个名称相同的变量!

  4. shiftSpinner,你想要将它当前选为String,但是这句话:

    shift.getText().toString();

    这是错误的,而是使用:

    shift.getSelectedItem().toString();

  5. <强> ====

      

    在MainActivity中,我在这些行中出现错误

    boolean update = mylogsDB.updateData(etID.getText().toString(), date.getText().toString(),hours.getText().toString(),shift.getText().toString());
    
         

         

    仅在日期,转移方法getText无法解析。

    我在这里看到更多错误!,让我们全部解压缩:

    变量etID已定义,但从未分配过!我希望这会给出一个空指针异常。

    再次shiftSpinner

    同样 dateDatePicker,要将其值作为字符串,请执行以下操作:

    Date dateObj = (Date) new Date (date.getYear(), date.getMonth(), date.getDayOfMonth());
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // you can change this format as you wish!
    String dateAsString = sdf.format(dateObj);