使用SharedPreferences将值插入SQLite时出错

时间:2015-11-18 10:23:21

标签: android sqlite

我是SharedPreferences和SQLite的新手。

我已经实现了参考在线示例的SharedPreferences。

当我调试期望配置文件时(我获得了配置文件的“默认”值),所有其他值都正确,因为我从设备插入了
但是当我按下按钮时,它会抛出一些错误。

我用Google搜索,但未按预期得到任何答案 请帮我理解我在哪里弄错了。

DBHandler类

  package com.example.app;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLData;

import android.R.raw;
import android.app.Activity;
import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.text.StaticLayout;
import android.util.Log;
import android.widget.Toast;

public class DBHandler extends SQLiteOpenHelper{


    public static int VERSION_NAME=1;
    public static String DATABASE_NAME="altaf";
    public static String TABLE_REGISTER="register";
    public static String PERSON_ID="_PersonId";
    public static String PERSON_FNAME="FirstName";
    public static String PERSON_EMAIL="EmaiId";
    public static String PERSON_PASSWORD="Password";
    public static String PERSON_PHOTO="Photo";
    public static String PERSON_GENDER="Gender";
    public static String PERSON_COUNTRY="Country";
    public static String PERSON_STATE="State";
    public static String PERSON_CITY="City";
    public static String PERSON_S_QUE="Squestion";
    public static String PERSON_DOB="dob";
    public static String PERSON_UNAME="Uname";



    Context context;

    public DBHandler(Context context) {
        super(context, DATABASE_NAME, null, VERSION_NAME);
        // TODO Auto-generated constructor stub


    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        try{
        String create_table="CREATE TABLE " + TABLE_REGISTER + "(" + PERSON_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + PERSON_FNAME + " TEXT NOT NULL," + PERSON_EMAIL + " TEXT NOT NULL," + PERSON_PASSWORD + " TEXT NOT NULL," + PERSON_PHOTO + " blob not null," + PERSON_GENDER + " TEXT NOT NULL," + PERSON_COUNTRY + " TEXT NOT NULL," + PERSON_STATE + " TEXT NOT NULL," + PERSON_CITY + " TEXT NOT NULL," + PERSON_S_QUE + " TEXT NOT NULL," + PERSON_DOB + " DATE," + PERSON_UNAME + " TEXT NOT NULL )";
        db.execSQL(create_table);
        }
        catch(Exception e)
        {
            Log.e("failed to create table", e.toString());

        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS"+TABLE_REGISTER);
        onCreate(db);
    }


    public void insert(String fname,String email,String pwd,String profile,String gender,String country,String state,String city,String sec_que,String dob,String uname) throws SQLException{

        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(PERSON_FNAME, fname);
        cv.put(PERSON_EMAIL, email);
        cv.put(PERSON_PASSWORD, pwd);
        cv.put(PERSON_PHOTO, profile);
        cv.put(PERSON_GENDER, gender);
        cv.put(PERSON_COUNTRY, country);
        cv.put(PERSON_STATE, state);
        cv.put(PERSON_CITY, city);
        cv.put(PERSON_COUNTRY, sec_que);
        cv.put(PERSON_STATE, dob);
        cv.put(PERSON_CITY, uname);
        db.insert(TABLE_REGISTER, null, cv);

        db.close();}
  

mainActivity类

    package com.example.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    EditText e_fname,e_pwd,e_email;
    Button b_register;
    final int one=1;
    public static String msg="success";
    public static String error="unsuccess";

    CheckBox c_agree,c_spwd;
    TextView t_tc;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        e_fname=(EditText)findViewById(R.id.r_e_fnm);
        e_pwd=(EditText)findViewById(R.id.r_e_pwd);
        e_email=(EditText)findViewById(R.id.r_e_email);
        b_register=(Button)findViewById(R.id.b_register);
        c_agree=(CheckBox)findViewById(R.id.r_ch_agree);
        c_spwd=(CheckBox)findViewById(R.id.r_ch_spwd);
        t_tc=(TextView)findViewById(R.id.r_t_tc);

        final DBHandler handler=new DBHandler(this);
        SQLiteDatabase db=handler.getWritableDatabase();
        SharedPreferences pref=getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
        final Editor editor=pref.edit();



        c_spwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(!isChecked)
                {
                    e_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }else
                {
                    e_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });


        b_register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String fname,pwd,email;
                fname=e_fname.getText().toString();
                email=e_email.getText().toString();
                pwd=e_pwd.getText().toString();

                if(fname.equals("")|| email.equals("")||pwd.equals(""))
                {
                    e_fname.setError("field is required");
                    e_pwd.setError("field is required");
                    e_email.setError("field is required");
                }
                else
                {
                    String PERSON_FNAME="FirstName";
                    String PERSON_EMAIL="EmaiId";
                    String PERSON_PASSWORD="Password";



                    editor.putString(PERSON_FNAME, fname);
                    editor.putString(PERSON_EMAIL, email);
                    editor.putString(PERSON_PASSWORD, pwd);
                    editor.apply();

                Toast.makeText(getApplication(), fname+ "  "  + "Is Redirecting", Toast.LENGTH_SHORT).show();
                Intent i=new Intent(MainActivity.this,reg1.class);
                startActivity(i);
                }
            }
        });
    }

reg1 class

package com.example.app;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;



    public class reg1 extends

     Activity{

        public static String GEENDER="gender";
        public static String imgDecodableString="imgDecodableStringr";
        //public static String GEENDER="gender";
        public static int RESULT_LOAD_IMG = 1;
        Intent data ;
        ImageView imageView;
        Button register1;

        Uri selectedImage ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.reg_1);
        imageView=(ImageView)findViewById(R.id.img_select);
        register1=(Button)findViewById(R.id.b_r1_add);


        SharedPreferences sp1=getApplication().getSharedPreferences("pref", MODE_PRIVATE);
        final Editor editor=sp1.edit();
        imageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                loadimagefrmgallery(v);

            }
        });

        final RadioButton female=(RadioButton)findViewById(R.id.imageView1);
        final RadioButton male=(RadioButton)findViewById(R.id.imageView2);
        male.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub


                if(male.isChecked())
                {
                    male.setChecked(true);
                    GEENDER="male";
                    female.setChecked(false);
                }

            }
        });
        female.setOnCheckedChangeListener(new  OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub

                if(female.isChecked())
                {
                    female.setChecked(true);
                    GEENDER="female";
                    male.setChecked(false);
                }
            }
        });



        register1.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("static-access")
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                DBHandler handler=new DBHandler(getApplicationContext());
                SQLiteDatabase db=handler.getWritableDatabase();
                Bitmap bitmap=BitmapFactory.decodeFile(imgDecodableString);
                // convert bitmap to byte
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte imageInByte[] = stream.toByteArray();

                String image = null;
                try {
                    image = new String(imageInByte, "UTF");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }



                String PERSON_PHOTO="Photo";
                String PERSON_GENDER="Gender";


                editor.putString(PERSON_PHOTO, image);
                editor.putString(PERSON_GENDER, GEENDER);
                editor.apply();
                Toast.makeText(getApplicationContext(),  "moving", Toast.LENGTH_SHORT).show();
                Intent i=new Intent(reg1.this,reg2.class);
                startActivity(i);

            }
        });


    }

reg2 class

    package com.example.app;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class reg2 extends Activity{

    Spinner s_con,s_stat,s_ct;
    Button register2;
    public static String country1,state1,city1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.reg_2);

        s_con=(Spinner)findViewById(R.id.r_spin_con);
        s_stat=(Spinner)findViewById(R.id.r_spin_stat);
        s_ct=(Spinner)findViewById(R.id.r_spin_ct);
        register2=(Button)findViewById(R.id.b_r2_add);

        SharedPreferences sp2=getApplication().getSharedPreferences("pref", MODE_PRIVATE);
        final Editor editor=sp2.edit();


        ArrayList<String>a=new ArrayList<String>();
        ArrayList<String>a1=new ArrayList<String>();
        ArrayList<String>a2=new ArrayList<String>();
        a.add("India");
        a.add("England");
        a.add("USA");
        a.add("Pakistan");
        a1.add("Panjab");
        a1.add("gujarat");
        a1.add("Berkshire");
        a2.add("surat");
        a2.add("great manchester");
        a2.add("london");


        final ArrayAdapter<String>adapter1=new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,a1);
        final ArrayAdapter<String>adapter2=new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,a2);
        final ArrayAdapter<String>adapter=new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,a);
        s_con.setAdapter(adapter);
        s_stat.setAdapter(adapter1);
        s_ct.setAdapter(adapter2);

        s_con.setOnItemSelectedListener(new  OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub


                country1=parent.getItemAtPosition(position).toString();
                Toast.makeText(getApplicationContext(), country1, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });

        s_stat.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                state1=parent.getItemAtPosition(position).toString();
                Toast.makeText(getApplicationContext(), state1, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });
        s_ct.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub

                 city1=parent.getItemAtPosition(position).toString();
                 Toast.makeText(getApplicationContext(), city1, Toast.LENGTH_SHORT).show();

            }


            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });







        register2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                DBHandler handler=new DBHandler(getApplicationContext());
                SQLiteDatabase db=handler.getWritableDatabase();



                String PERSON_COUNTRY="Country";
                String PERSON_STATE="State";
                String PERSON_CITY="City";


                editor.putString(PERSON_COUNTRY, country1);
                editor.putString(PERSON_STATE, state1 );
                editor.putString(PERSON_CITY, city1 );
                editor.apply();

                Toast.makeText(getApplicationContext(), "moving", Toast.LENGTH_SHORT).show();
                Intent i=new Intent(reg2.this,reg3.class);
                startActivity(i);

            }
        });

}}

reg3 class

    package com.example.app;

import java.io.IOException;
import java.util.ArrayList;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class reg3 extends Activity {

    Spinner s_sq;
    EditText dob,unm;
    Button register3;
    public static String PREF="pref";
    public static String def_val="default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reg_3);

        s_sq=(Spinner)findViewById(R.id.r_spin_sq);
        dob=(EditText) findViewById(R.id.r_e_dob);
        unm=(EditText) findViewById(R.id.editText1);
        register3=(Button)findViewById(R.id.b_add3);
        ArrayList<String>a=new ArrayList<String>();
        final ArrayAdapter<String>adapter=new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,a);
        a.add("when were you born?");
        a.add("what is your nick name?");
        a.add("what is your childhood name");
        a.add("what city your parents were met");
        a.add("what is your city name");
        s_sq.setAdapter(adapter);

        final SharedPreferences pref=getApplication().getSharedPreferences(PREF, MODE_PRIVATE);
        final SharedPreferences pref1=getApplication().getSharedPreferences(PREF, MODE_PRIVATE);
        final SharedPreferences pref2=getApplication().getSharedPreferences(PREF, MODE_PRIVATE);


        register3.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("static-access")
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                DBHandler handler=new DBHandler(getApplicationContext());
                SQLiteDatabase db=handler.getWritableDatabase();
                String dob1=dob.getText().toString();
                String uname=unm.getText().toString();
                String sec_que=s_sq.getSelectedItem().toString();

                String PERSON_FNAME="FirstName";
                String PERSON_EMAIL="EmaiId";
                String PERSON_PASSWORD="Password";
                String PERSON_PHOTO="Photo";
                String PERSON_GENDER="Gender";
                String PERSON_COUNTRY="Country";
                String PERSON_STATE="State";
                String PERSON_CITY="City";


                String fname=pref.getString(PERSON_FNAME, def_val);
                String email=pref.getString(PERSON_EMAIL, def_val);
                String pwd=pref.getString(PERSON_PASSWORD, def_val);
                String profile=pref1.getString(PERSON_PHOTO, def_val);
                String gender=pref1.getString(PERSON_GENDER, def_val);
                String country=pref2.getString(PERSON_COUNTRY, def_val);
                String state=pref2.getString(PERSON_STATE, def_val);
                String city=pref2.getString(PERSON_CITY, def_val);

                handler.insert(fname, email, pwd, profile, gender, country, state, city, sec_que, dob1, uname);


                Intent i=new Intent(reg3.this,home.class);
                startActivity(i);

                Toast.makeText(getApplicationContext(),"Registered", Toast.LENGTH_LONG).show();
            }
        });

    }

}

logcat的

11-18 02:09:55.846: E/SQLiteDatabase(23920): Error inserting EmaiId=a State=1/1/1992 Gender=male Password=a FirstName=a Country=what is your childhood name Photo=default City=altu
11-18 02:09:55.846: E/SQLiteDatabase(23920): android.database.sqlite.SQLiteConstraintException: register.Squestion may not be NULL (code 19)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at com.example.app.DBHandler.insert(DBHandler.java:94)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at com.example.app.reg3$1.onClick(reg3.java:84)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.view.View.performClick(View.java:4084)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.view.View$PerformClick.run(View.java:16966)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.os.Handler.handleCallback(Handler.java:615)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.os.Looper.loop(Looper.java:137)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at android.app.ActivityThread.main(ActivityThread.java:4745)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at java.lang.reflect.Method.invokeNative(Native Method)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at java.lang.reflect.Method.invoke(Method.java:511)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-18 02:09:55.846: E/SQLiteDatabase(23920):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

TABLE_REGISTER一样,PERSON_S_QUE也可以使用TEXT NOT NULL属性,但在表格中插入数据时,不会在PERSON_S_QUE中添加ContentValues列值。

在插入方法中添加以下内容:

cv.put(PERSON_S_QUE, sec_que);