无法将数据永久存储在数据库中

时间:2017-12-02 22:25:55

标签: java android sqlite android-sqlite

我正在尝试将注册数据存储在数据库中。有两个表 - geregistry3和getypes2。插入通常在getypes2中工作。但是在将数据插入geregistry3时,如果我没有用db.close()关闭数据库,它或者不会被存储或者只存储一个元组(这也是暂时的,在重新启动该活动时会变回空)。任何日志和堆栈跟踪都不会显示异常或错误。

请帮忙!

GEDatabaseHandler.java

package com.example.akshayjk.attempt1.SQL;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GEDatabaseHandler extends SQLiteOpenHelper {

public GEDatabaseHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

private static final String datatbase="mydatabase.db";
private static final String table_name1="geregistry3";
private static final int database_version=1;

public static final String email="email_id";
public static final String group_name="group_name";
public static final String doe="doe";
public static final String timing="timing";
private static final String create_table1="CREATE TABLE " + table_name1 + "( " + email+" TEXT, "+group_name+" TEXT, "+doe+" NUMBER, "+timing+" TEXT "+ ");";

private static final String table_name2="getypes2";
public static final String group_name1="group_name";
public static final String timings="timing";
private static final String create_table2="CREATE TABLE "+ table_name2+"( "+group_name1+" TEXT, "+timings+" TEXT, "+ doe+" NUMBER );";

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(create_table2);
    db.execSQL(create_table1);
    fillGetypes(db);
}

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

    // Create tables again
    onCreate(db);

}

public void fillGetypes(SQLiteDatabase db){
    String[] types={"Bodypump", "Barre", "Cycle 45"};
    int[] times={1200,1230,1630,1700,1730,1745,1830,1900,1930};
    String[]day={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};

    ContentValues values = new ContentValues();
    values.put(group_name1,types[0]);
    values.put(timings,times[0]);
    values.put(doe,day[0]);
    db.insert(table_name2, null, values);


    values=new ContentValues();
    values.put(group_name1,types[0]);
    values.put(timings,times[4]);
    values.put(doe,day[0]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[0]);
    values.put(timings,times[3]);
    values.put(doe,day[1]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[0]);
    values.put(timings,times[4]);
    values.put(doe,day[2]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[0]);
    values.put(timings,times[8]);
    values.put(doe,day[3]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[0]);
    values.put(timings,times[0]);
    values.put(doe,day[4]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[0]);
    values.put(timings,times[2]);
    values.put(doe,day[4]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[1]);
    values.put(timings,times[0]);
    values.put(doe,day[0]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[1]);
    values.put(timings,times[3]);
    values.put(doe,day[1]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[1]);
    values.put(timings,times[6]);
    values.put(doe,day[3]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[1]);
    values.put(timings,times[5]);
    values.put(doe,day[4]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[2]);
    values.put(timings,times[4]);
    values.put(doe,day[0]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[2]);
    values.put(timings,times[6]);
    values.put(doe,day[0]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[2]);
    values.put(timings,times[0]);
    values.put(doe,day[1]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[2]);
    values.put(timings,times[6]);
    values.put(doe,day[1]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[2]);
    values.put(timings,times[3]);
    values.put(doe,day[2]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[2]);
    values.put(timings,times[2]);
    values.put(doe,day[3]);
    db.insert(table_name2, null, values);;

    values=new ContentValues();
    values.put(group_name1,types[2]);
    values.put(timings,times[0]);
    values.put(doe,day[4]);
    db.insert(table_name2, null, values);;
}

public void addRegister(GroupData groupData){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(email,groupData.getEmailId());
    values.put(group_name,groupData.getgroup());
    values.put(doe,groupData.getdOB());
    values.put(timing,groupData.gettiming());
    // Inserting Row
    try {
        db.execSQL("INSERT INTO "+table_name1+" VALUES(?,?,?,?)",new String[]{groupData.getEmailId(),groupData.getgroup(),groupData.getdOB(),String.valueOf(groupData.gettiming())});
        db.close(); // Closing database connection
    }catch (Exception e){
        e.printStackTrace();
    }
    /*
    */
}

public boolean isTableExists(){
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+table_name1+"'", null);
    if(cursor!=null) {
        if(cursor.getCount()>0) {
            cursor.close();
            return true;
        }
        cursor.close();
    }
    return false;
}

public List<GroupData> getAllRegister(){
    String[] columns = {
            "*"
    };
    SQLiteDatabase db = this.getReadableDatabase();

    List<GroupData> groupData=new ArrayList<>();
    // query user table with condition
    Cursor cursor = db.query(table_name1, //Table to query
            columns,                    //columns to return
            null,                  //columns for the WHERE clause
            null,              //The values for the WHERE clause
            null,                       //group the rows
            null,                      //filter by row groups
            null);                      //The sort order
    int cursorCount=0;
    if(cursor.moveToFirst()){
        do {
            GroupData user = new GroupData();
            user.setEmailId(cursor.getString(cursor.getColumnIndex(email)));
            user.setDoB(cursor.getString(cursor.getColumnIndex(doe)));
            user.settiming(Integer.parseInt(cursor.getString(cursor.getColumnIndex(timings))));
            user.setgroup(cursor.getString(cursor.getColumnIndex(group_name1)));
            // Adding user record to list
            groupData.add(user);
        } while (cursor.moveToNext());
    }
    if(cursor!=null && !cursor.isClosed()){
        cursorCount=cursor.getCount();
        cursor.close();
    }
    db.close();


    return groupData;
}

public int checkcount(String exgroup, String Doe, int timing){
    String[] columns = {
            "*"
    };
    SQLiteDatabase db = this.getReadableDatabase();

    // selection criteria
    String selection =  group_name+ " = ? AND "+doe+" = ? AND " +timings+" = ?";

    // selection argument
    String[] selectionArgs = {exgroup,Doe, String.valueOf(timing)};

    // query user table with condition
    Cursor cursor = db.query(table_name1, //Table to query
            columns,                    //columns to return
            selection,                  //columns for the WHERE clause
            selectionArgs,              //The values for the WHERE clause
            null,                       //group the rows
            null,                      //filter by row groups
            null);                      //The sort order
    int cursorCount=0;
    if(cursor!=null && !cursor.isClosed()){
        cursorCount=cursor.getCount();
        cursor.close();
    }
    db.close();

    return cursorCount;
}

public int checkexists(String email, String exgroup, String Doe, int timing){
    String[] columns = {
            "*"
    };
    SQLiteDatabase db = this.getReadableDatabase();

    // selection criteria
    String selection =  this.email+" = ? AND "+group_name+ " = ? AND "+doe+" = ? AND " +timings+" = ?";

    // selection argument
    String[] selectionArgs = {email,exgroup,Doe, String.valueOf(timing)};

    // query user table with condition
    Cursor cursor = db.query(table_name1, //Table to query
            columns,                    //columns to return
            selection,                  //columns for the WHERE clause
            selectionArgs,              //The values for the WHERE clause
            null,                       //group the rows
            null,                      //filter by row groups
            null);                      //The sort order
    int cursorCount=0;
    if(cursor!=null && !cursor.isClosed()){
        cursorCount=cursor.getCount();
        cursor.close();
    }
    db.close();

    return cursorCount;
}

public List<GroupData> retTypes(String exgroup){
    Date now=new Date();
    int i;
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("EEEE");
    String daynow=simpleDateFormat.format(now);
    String[] day={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    for(i=0;i<day.length;i++){
        if(day[i].equals(daynow))
            break;
    }
    simpleDateFormat=new SimpleDateFormat("HH:mm");
    Calendar calendar=Calendar.getInstance();
    String time=simpleDateFormat.format(calendar.getTime());
    String nowtime=time.replace(":","");
    int timeNow= Integer.parseInt(nowtime);
    nowtime="0"+new Integer(timeNow).toString();
    String[] columns = {
            "*"
    };
    List<GroupData> groupDataList=new ArrayList<GroupData>();
    SQLiteDatabase db = this.getReadableDatabase();
    // selection criteria
    String selection =  group_name1+" = ? AND " +doe+" IN (?,?,?)";
    // selection argument
    String[] selectionArgs = {exgroup,day[i%7],day[(i+1)%7],day[(i+2)%7]};

    // query user table with condition
    Cursor cursor = db.query(table_name2, //Table to query
            columns,                    //columns to return
            selection,                  //columns for the WHERE clause
            selectionArgs,              //The values for the WHERE clause
            null,                       //group the rows
            null,                      //filter by row groups
            null);                      //The sort order
    int cursorCount = cursor.getCount();

    if (cursor.moveToFirst()) {
        do {
            GroupData user = new GroupData();
            user.setgroup(cursor.getString(cursor.getColumnIndex(group_name1)));
            user.settiming(Integer.parseInt(cursor.getString(cursor.getColumnIndex(timing))));
            user.setDoB(cursor.getString(cursor.getColumnIndex(doe)));
            // Adding user record to list
            groupDataList.add(user);
        } while (cursor.moveToNext());
    }
    if(cursor!=null && !cursor.isClosed())
        cursor.close();
    db.close();
    return groupDataList;
}

public List<GroupData> retTypes(String exgroup, String chosenDay){
    Date now=new Date();
    int i;
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("EEEE");
    String daynow=simpleDateFormat.format(now);
    String[] day={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    for(i=0;i<day.length;i++){
        if(day[i].equals(daynow))
            break;
    }
    simpleDateFormat=new SimpleDateFormat("HH:mm");
    Calendar calendar=Calendar.getInstance();
    String time=simpleDateFormat.format(calendar.getTime());
    String nowtime=time.replace(":","");
    int timeNow= Integer.parseInt(nowtime);
    nowtime=new Integer(timeNow+1000).toString();
    String[] columns = {
            "*"
    };
    List<GroupData> groupDataList=new ArrayList<GroupData>();
    SQLiteDatabase db = this.getReadableDatabase();
    // selection criteria
    String selection =  group_name1+" = ? AND " +doe+" = ?";
    // selection argument
    String[] selectionArgs = {exgroup,chosenDay};

    // query user table with condition
    Cursor cursor = db.query(table_name2, //Table to query
            columns,                    //columns to return
            selection,                  //columns for the WHERE clause
            selectionArgs,              //The values for the WHERE clause
            null,                       //group the rows
            null,                      //filter by row groups
            null);                      //The sort order
    int cursorCount = cursor.getCount();

    if (cursor.moveToFirst()) {
        do {
            GroupData user = new GroupData();
            user.setgroup(cursor.getString(cursor.getColumnIndex(group_name1)));
            user.settiming(Integer.parseInt(cursor.getString(cursor.getColumnIndex(timing))));
            user.setDoB(cursor.getString(cursor.getColumnIndex(doe)));
            // Adding user record to list
            groupDataList.add(user);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return groupDataList;
}

}

GE_Form.java

package com.example.akshayjk.attempt1.HFW_Activities;

public class GE_Form extends AppCompatActivity{

public static GEDatabaseHandler gdb;
public List<GroupData> groupData=new ArrayList<GroupData>();
public Spinner spTypes,spDays,spTimings;
public Button button;

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(GE_Form.this, HFW.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
    finish();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_geform);
    Bundle bundle = getIntent().getExtras();
    final String email = bundle.getString("email");
    button = findViewById(R.id.button_registerge);

    gdb = new GEDatabaseHandler(GE_Form.this, null, null, 4);
    String[] types = {"Bodypump", "Barre", "Cycle 45"};
    String[] days;
    String[] timings;
    ArrayAdapter<String> adapter1;
    final ArrayList<String> s1 = new ArrayList<>();
    final ArrayList<String> s2 = new ArrayList<String>();
    final String[] s3;
    final String[] s4;
    spTypes = findViewById(R.id.ge_sp1);
    adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
    spTypes.setAdapter(adapter1);
    spDays = findViewById(R.id.ge_sp2);
    spTimings = findViewById(R.id.ge_sp3);
    final TextView textView = findViewById(R.id.test2);
    spTypes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            final String group = spTypes.getSelectedItem().toString().trim();
            groupData = gdb.retTypes(group);
            s1.clear();
            for (GroupData g : groupData) {
                s1.add(g.getdOB());
                textView.append(g.getdOB() + " " + g.getgroup() + " " + g.gettiming() + "\n");

            }
            Set<String> hs = new HashSet<>();
            hs.addAll(s1);
            s1.clear();
            s1.addAll(hs);
            ArrayAdapter<String> adapter2;
            adapter2 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, s1);
            adapter2.notifyDataSetChanged();
            spDays.setAdapter(adapter2);
            spDays.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String days = spDays.getSelectedItem().toString().trim();
                    s2.clear();
                    groupData = gdb.retTypes(group, days);
                    for (GroupData g : groupData) {
                        s2.add(String.valueOf(g.gettiming()));
                    }
                    Set<String> hs = new HashSet<>();
                    hs.addAll(s2);
                    s2.clear();
                    s2.addAll(hs);
                    ArrayAdapter<String> adapter3;
                    adapter3 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, s2);
                    adapter3.notifyDataSetChanged();
                    spTimings.setAdapter(adapter3);

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });


            if (groupData.isEmpty()) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                Calendar calendar = Calendar.getInstance();
                String time = simpleDateFormat.format(calendar.getTime());
                String nowtime = time.replace(":", "");
                int timeNow = Integer.parseInt(nowtime);
                nowtime = "0" + new Integer(timeNow).toString();

                Toast.makeText(getApplicationContext(), nowtime, Toast.LENGTH_LONG).show();
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String edex = spTypes.getSelectedItem().toString().trim();
            String eddoe = spDays.getSelectedItem().toString().trim();
            int edtime = Integer.parseInt(spTimings.getSelectedItem().toString().trim());
            GroupData gd = new GroupData();
            if (gdb.checkexists(email, edex, eddoe, edtime) != 0) {
                Toast.makeText(getApplicationContext(), "Already Registered", Toast.LENGTH_LONG).show();
            } else {
                if (gdb.checkcount(edex, eddoe, edtime) < 5) {
                    gd.setEmailId(email);
                    gd.setDoB(eddoe);
                    gd.setgroup(edex);
                    gd.settiming(edtime);
                    gdb.addRegister(gd);
                    textView.setText("");
                }
                    List<GroupData> groupData1 = gdb.getAllRegister();
                    if (groupData1.isEmpty())
                        textView.append("Not writing into table");
                    for (GroupData d : groupData1) {
                        textView.append("\n" + d.getEmailId() + " " + d.getgroup() + " " + d.getdOB() + " " + d.gettiming());
                    }
                        if (gdb.isTableExists()) {
                            textView.append("Exists");
                        } else
                            textView.append("Does not exist");
            }
        }
    });

}

}

1 个答案:

答案 0 :(得分:1)

如果查看文档,您会发现将null作为数据库名称传递,会创建一个内存数据库,这意味着它不会被持久化。 Here

因此,在创建GEDatabaseHandler时尝试传递任何数据库名称(只是任何字符串)。

之后检查您的数据是否保持正确。