将json数据存储到SQLite时出错

时间:2014-12-26 07:26:36

标签: android mysql json sqlite

我正在创建注册表单,并在将数据存储到SQLite时收到错误。我的数据插入MYSql但不插入SQLite。在下面的代码中,您可以在doinbackground中看到函数数据将转到MYSql数据库,但之后它会生成错误而数据不会插入SQLite这是我的注册码。

 public class Register_Activity extends Activity {


/*
RadioGroup rg;
RadioButton rb;
   int id;*/

private RadioGroup radioSexGroup;
private RadioButton radioSexButton;



private ProgressDialog pDialog;


   TextView Fname,Lname,Address,Password,Phone,Email,Gender;
   String password,gender;
    Button bnt_Submit;
    EditText edt_email,edt_password,edt_fname,edt_phone,edt_address,edt_lastName;
    JSONObject json;


    JSONParser jsonParser = new JSONParser();



    //http://www.truzzinfotech.co.nz/admin/public/jsonregister
    private static final String KEY_SUCCESS = "success";


    //private static final String KEY_ID = "id";
    private static final String KEY_FIRSTNAME = "firstname";
    private static final String KEY_LASTNAME = "lastname";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_PHONE = "phone";
    //private static final String KEY_UID = "uid";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_ADDRESS = "address";
    private static final String KEY_GENDER = "gender";
    //private static final String KEY_CREATED_AT = "created_at";



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




    radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);

    bnt_Submit =(Button)findViewById(R.id.btnsubmit);
    edt_email = (EditText)findViewById(R.id.Edt_Email);
    edt_password = (EditText)findViewById(R.id.Edt_Password);
    edt_lastName = (EditText)findViewById(R.id.Edt_LastName);
    edt_fname  = (EditText)findViewById(R.id.Edt_Name);
    edt_phone = (EditText)findViewById(R.id.Edt_Phone);
    edt_address = (EditText)findViewById(R.id.Edt_Address);


    Fname  = (TextView)findViewById(R.id.fnameError);
    Lname  = (TextView)findViewById(R.id.lnameError);
    Email  = (TextView)findViewById(R.id.emailError);
     Phone  = (TextView)findViewById(R.id.phnError);
     Password  = (TextView)findViewById(R.id.passError);
     Address  = (TextView)findViewById(R.id.addError);
     Gender  = (TextView)findViewById(R.id.genderError);

    bnt_Submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {


            int selectedId = radioSexGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

            //Toast.makeText(getApplicationContext(),radioSexButton.getText(), Toast.LENGTH_SHORT).show();

            new RegisterUser().execute();

        }
    });
}
class RegisterUser extends AsyncTask<String, String, String> {



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

        pDialog = new ProgressDialog(Register_Activity.this);
        pDialog.setMessage("Registering...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

// TODO Auto-generated method stub


         String firstname =edt_fname.getText().toString();
         String email =edt_email.getText().toString();
         String phone =edt_phone.getText().toString();
         String address =edt_address.getText().toString();
         String lastname =edt_lastName.getText().toString();
                password =edt_password.getText().toString();
                gender= radioSexButton.getText().toString();
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser(firstname, lastname, password, email, phone, address, gender);

                Log.d("json ch aa gya", json.toString());



    // Log.d("param",params1.toString());


     try {
         Log.d("try ch aa gya", "try ch aa gya");
         if (json.getString(KEY_SUCCESS) != null) {
                String res = json.getString(KEY_SUCCESS); 
                if(Integer.parseInt(res) == 1){
                DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                JSONObject json_user = json.getJSONObject("detail");
                Log.d("json_users ch aa gya", json_user.toString());

                // Clear all previous data in database
                userFunction.logoutUser(getApplicationContext());


                db.addUser(json_user.getString(KEY_FIRSTNAME), json_user.getString(KEY_LASTNAME), json.getString(KEY_EMAIL), json_user.getString(KEY_PHONE), json_user.getString(KEY_ADDRESS), json_user.getString(KEY_GENDER), json_user.getString(KEY_PASSWORD));                     
                Log.d("db.adduser ch aa gya", db.toString());

                finish();

            } else {


            }
     }}catch (Exception e) {
                // TODO: handle exception
            }




    return null;
     }

            protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
                pDialog.dismiss();


                             try {
                            JSONObject c = json.getJSONObject("detail");
                            //   phone,email,pass,add,fnam,lnam,gen
                            JSONArray   phone = c.optJSONArray("phone");
                            JSONArray   email = c.optJSONArray("email");
                            JSONArray   pass = c.optJSONArray("password");
                            JSONArray   add = c.optJSONArray("address");
                            JSONArray   fnam = c.optJSONArray("firstname");
                            JSONArray   lnam = c.optJSONArray("lastname");
                            //JSONArray gen = c.optJSONArray("gender");


                            Log.v("Error", c.toString());       

                    if(fnam != null || edt_fname == null) {
                        Fname.setText(fnam.getString(0));
                        }
                    else{
                        Fname.setText("");
                    }
                    if(lnam != null || edt_lastName == null) {
                        Lname.setText(lnam.getString(0));
                        }
                    else{
                        Lname.setText("");
                    }
                    if(email != null || edt_email == null){
                        Email.setText(email.getString(0));
                        }
                    else{
                        Email.setText("");
                    }
                    if(phone != null || edt_phone == null){
                        Phone.setText(phone.getString(0));
                        }
                    else{
                        Phone.setText("");
                    }
                    if(pass != null || edt_password == null){
                        Password.setText(pass.getString(0));
                    }
                    else{
                        Password.setText("");
                    }
                    if(add != null || edt_address == null){
                        Address.setText(add.getString(0));
                    }
                    else{
                        Address.setText("");
                    }





                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }




        }




    }

}

这是我在下面的SQlite代码

公共类DatabaseHandler扩展了SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "restaurant_customer";

// Login table name
private static final String TABLE_LOGIN = "login";


// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FIRSTNAME = "firstname";
private static final String KEY_LASTNAME = "lastname";
private static final String KEY_EMAIL = "emails";
private static final String KEY_PHONE = "phone";
//private static final String KEY_UID = "uid";
private static final String KEY_PASSWORD = "password";
private static final String KEY_ADDRESS = "address";
private static final String KEY_GENDER = "gender";

//private static final String KEY_CREATED_AT = "created_at";

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

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_ID + " INTEGER PRIMARY KEY," 
            + KEY_FIRSTNAME + " TEXT,"
            + KEY_LASTNAME + " TEXT,"
            + KEY_PASSWORD + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE,"
            + KEY_PHONE + " INTEGER,"
            + KEY_ADDRESS + " TEXT,"
            + KEY_GENDER + " TEXT," + ")";
    db.execSQL(CREATE_LOGIN_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

    // Create tables again
    onCreate(db);
}

/**
 * Storing user details in database
 * */
public void addUser(String firstname, String lastname, String password, String emails, String phone, String address, String gender, String uid, String created_at) {

    Log.d("param","add user ch aa gya");
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_FIRSTNAME, firstname); // FIRST Name
    values.put(KEY_LASTNAME, lastname); 
    values.put(KEY_EMAIL, emails); // Email
    //values.put(KEY_UID, uid); // Uid
    values.put(KEY_PHONE, phone); // Phone
    values.put(KEY_ADDRESS, address); // Address
    values.put(KEY_GENDER, gender); // Gender
    values.put(KEY_PASSWORD, password); // Password
    Log.d("values",values.toString());
    //values.put(KEY_CREATED_AT, created_at); // Created At

    // Inserting Row
    db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection
}

/**
 * Getting user data from database
 * */
public HashMap<String, String> getUserDetails(){
    HashMap<String,String> user = new HashMap<String,String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        user.put("firstname", cursor.getString(1));
        user.put("lastname", cursor.getString(2));
        user.put("email", cursor.getString(3));
        //user.put("uid", cursor.getString(4));
        //user.put("created_at", cursor.getString(5));
        user.put("phone", cursor.getString(6));
        user.put("password", cursor.getString(7));
        user.put("address", cursor.getString(8));
        user.put("gender", cursor.getString(9));
        //user.put("phone", cursor.getString(10));
        Log.d("user",user.toString());
    }
    cursor.close();
    db.close();
    // return user
    return user;
}

/**
 * Getting user login status
 * return true if rows are there in table
 * */
public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int rowCount = cursor.getCount();
    db.close();
    cursor.close();

    // return row count
    return rowCount;
}

/**
 * Re crate database
 * Delete all tables and create them again
 * */
public void resetTables(){
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_LOGIN, null, null);
    db.close();
}

public void addUser(String string, String string2, String string3,
        String string4, String string5, String string6, String string7) {
    // TODO Auto-generated method stub

}

}

Logcat错误

12-26 13:05:00.386: D/dalvikvm(671): GC_FOR_ALLOC freed 104K, 4% free 11838K/12231K, paused 46ms, 

total 67ms
12-26 13:05:00.396: I/dalvikvm-heap(671): Grow heap (frag case) to 11.857MB for 279056-byte allocation
12-26 13:05:00.516: D/dalvikvm(671): GC_FOR_ALLOC freed 7K, 4% free 12103K/12551K, paused 104ms, total 104ms
12-26 13:05:00.686: D/jayant(671): jayant
12-26 13:05:00.686: D/param(671): [firstname=tom, lastname=johnson, password=tomcatvideo, email=tom@gmail.com, phone=987654321, address=demo, gender=Male]
12-26 13:05:03.437: I/Choreographer(671): Skipped 44 frames!  The application may be doing too much work on its main thread.
12-26 13:05:06.406: E/JSON(671): {"detail":{"firstname":"tom","lastname":"johnson","gender":"Male","phone":"987654321","address":"demo"},"success":1}
12-26 13:05:06.646: D/getJSONFromUrl(671): {"success":1,"detail":{"gender":"Male","lastname":"johnson","phone":"987654321","firstname":"tom","address":"demo"}}
12-26 13:05:06.836: D/json ch aa gya(671): {"success":1,"detail":{"gender":"Male","lastname":"johnson","phone":"987654321","firstname":"tom","address":"demo"}}
12-26 13:05:06.836: D/try ch aa gya(671): try ch aa gya
12-26 13:05:06.985: D/json_users ch aa gya(671): {"gender":"Male","lastname":"johnson","phone":"987654321","firstname":"tom","address":"demo"}
12-26 13:05:08.096: D/AndroidRuntime(671): Shutting down VM
12-26 13:05:08.096: W/dalvikvm(671): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
12-26 13:05:08.275: E/AndroidRuntime(671): FATAL EXCEPTION: main
12-26 13:05:08.275: E/AndroidRuntime(671): java.lang.NullPointerException
12-26 13:05:08.275: E/AndroidRuntime(671):  at app.restaurant.Register_Activity$RegisterUser.onPostExecute(Register_Activity.java:209)
12-26 13:05:08.275: E/AndroidRuntime(671):  at app.restaurant.Register_Activity$RegisterUser.onPostExecute(Register_Activity.java:1)
12-26 13:05:08.275: E/AndroidRuntime(671):  at android.os.AsyncTask.finish(AsyncTask.java:631)
12-26 13:05:08.275: E/AndroidRuntime(671):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-26 13:05:08.275: E/AndroidRuntime(671):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
12-26 13:05:08.275: E/AndroidRuntime(671):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 13:05:08.275: E/AndroidRuntime(671):  at android.os.Looper.loop(Looper.java:137)
12-26 13:05:08.275: E/AndroidRuntime(671):  at android.app.ActivityThread.main(ActivityThread.java:4745)
12-26 13:05:08.275: E/AndroidRuntime(671):  at java.lang.reflect.Method.invokeNative(Native Method)
12-26 13:05:08.275: E/AndroidRuntime(671):  at java.lang.reflect.Method.invoke(Method.java:511)
12-26 13:05:08.275: E/AndroidRuntime(671):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-26 13:05:08.275: E/AndroidRuntime(671):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-26 13:05:08.275: E/AndroidRuntime(671):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

private static final String DATABASE_NAME =&#34; restaurant.db&#34 ;;

答案 1 :(得分:0)

json中的onPostExecute()变量为空。您在doInBackground()分配了该名称的本地变量,以及您从未分配给Register_Activity中该名称的其他类级别变量。

通常,像这样的NPE相对容易弄清楚,例如在调试器中单步执行时。