SQlite数据库中的多个表(应用程序崩溃)

时间:2014-08-28 01:20:19

标签: android sqlite

当我是数据库SQLite中的单个表(用户)时,我的应用程序工作正常(用于存储已登录用户的信息)。现在我添加了一个与用户表相同的表名为taxi(在应用程序中我有两种类型的用户)。我试图更改数据库名称和版本,但是当我尝试注册/登录作为出租车时,服务器记录/找到出租车但随后应用程序崩溃。问题肯定在DatabaseHandler类和存储表的方式。下面我把主要活动的代码。

package com.example.heytaxi.library;




import java.util.HashMap;

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


public class DatabaseHandler extends SQLiteOpenHelper {


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

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

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

//Login table(taxi) name
private static final String TABLE_LOGIN_TAXI = "loginTaxi2";

// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";

//Login Table(taxi) Columns names

private static final String KEY_ID_TAXI = "id";
private static final String KEY_NAME_TAXI = "name";
private static final String KEY_EMAIL_TAXI = "email";
private static final String KEY_UID_TAXI = "uid";
private static final String KEY_CREATED_AT_TAXI = "created_at";

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

// Creating Tables


private static final String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
        + KEY_ID + " INTEGER PRIMARY KEY,"
        + KEY_NAME + " TEXT,"
        + KEY_EMAIL + " TEXT UNIQUE,"
        + KEY_UID + " TEXT,"
        + KEY_CREATED_AT + " TEXT" + ")";

private static final String CREATE_LOGIN_TAXI_TABLE = "CREATE TABLE " + TABLE_LOGIN_TAXI + "("
        + KEY_ID_TAXI + " INTEGER PRIMARY KEY,"
        + KEY_NAME_TAXI + " TEXT,"
        + KEY_EMAIL_TAXI + " TEXT UNIQUE,"
        + KEY_UID_TAXI + " TEXT,"
        + KEY_CREATED_AT_TAXI + " TEXT" + ")";

@Override
public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_LOGIN_TABLE);
        db.execSQL(CREATE_LOGIN_TAXI_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);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN_TAXI);
    // Create tables again
    onCreate(db);
}

/**
 * Storing user details in database
 * */
public void addUser(String name, String email, String uid, String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, name); // Name
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_UID, uid); // Email
    values.put(KEY_CREATED_AT, created_at); // Created At

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


/**
 * Storing taxi details in database
 * */
public void addTaxi(String name, String email, String uid, String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME_TAXI, name); // Name
    values.put(KEY_EMAIL_TAXI, email); // Email
    values.put(KEY_UID_TAXI, uid); // Email
    values.put(KEY_CREATED_AT_TAXI, created_at); // Created At

    // Inserting Row
    db.insert(TABLE_LOGIN_TAXI, 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("name", cursor.getString(1));
        user.put("email", cursor.getString(2));
        user.put("uid", cursor.getString(3));
        user.put("created_at", cursor.getString(4));
    }
    cursor.close();
    db.close();
    // return user
    return user;
}



/**
 * Getting taxi data from database
 * */
public HashMap<String, String> getTaxiDetails(){
    HashMap<String,String> taxi = new HashMap<String,String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN_TAXI;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        taxi.put("name", cursor.getString(1));
        taxi.put("email", cursor.getString(2));
        taxi.put("uid", cursor.getString(3));
        taxi.put("created_at", cursor.getString(4));
    }
    cursor.close();
    db.close();
    // return taxi
    return taxi;
}

/**
 * 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;
}

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

    // return row count
    return rowCount;
}

/**
 * Re create 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.delete(TABLE_LOGIN_TAXI, null, null);
    db.close();
}

}

DashBoardActivity,这是主要的启动器活动。

package com.example.heytaxi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.heytaxi.library.UserFunctions;
import com.example.heytaxi.library.TaxiFunctions;

public class DashboardActivity extends Activity {
    UserFunctions userFunctions;
    TaxiFunctions taxiFunctions;
    Button btnLogout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * Dashboard Screen for the application
         * */       
        // Check login status in database
        taxiFunctions = new TaxiFunctions();
        userFunctions = new UserFunctions();
        /*if(userFunctions.isUserLoggedIn(getApplicationContext())){
       // user already logged in show databoard
            setContentView(R.layout.dashboard);
            btnLogout = (Button) findViewById(R.id.btnLogout);

            btnLogout.setOnClickListener(new View.OnClickListener() {

                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    userFunctions.logoutUser(getApplicationContext());
                    Intent login = new Intent(getApplicationContext(), LoginActivity.class);
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    // Closing dashboard screen
                    finish();
                }
            });

        }
        else*/ 
             if(taxiFunctions.isTaxiLoggedIn(getApplicationContext())){
                   // taxi already logged in show dashboard
                        setContentView(R.layout.dashboardtaxi);
                      //  btnLogout = (Button) findViewById(R.id.btnLogout);

                      /*  btnLogout.setOnClickListener(new View.OnClickListener() {

                            public void onClick(View arg0) {
                                // TODO Auto-generated method stub
                                taxiFunctions.logoutTaxi(getApplicationContext());
                                Intent loginTaxi = new Intent(getApplicationContext(), LoginTaxiActivity.class);
                                loginTaxi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(loginTaxi);
                                // Closing dashboard screen
                                finish();
                            }
                        });*/

        }

        else{
            // user is not logged in show main screen
            Intent sceltaIniziale = new Intent(getApplicationContext(), SceltaIniziale.class);
            sceltaIniziale.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(sceltaIniziale);
            // Closing dashboard screen
            finish();
        }        
    }
}

TaxiFunctions:

package com.example.heytaxi.library;



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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;

public class TaxiFunctions {

    private JSONParser jsonParser;

    // Testing in localhost using wamp or xampp 
    // use http://10.0.2.2/ to connect to your localhost ie http://localhost/
    private static String loginURL = "http://android_login_taxi_api/";
    private static String registerURL ="http://android_login_taxi_api/";

    private static String login_tag = "login";
    private static String register_tag = "register";

    // constructor
    public TaxiFunctions(){
        jsonParser = new JSONParser();
    }

    /**
     * function make Login Request
     * @param email
     * @param password
     * */
    public JSONObject loginTaxi(String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", login_tag));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }

    /**
     * function make Login Request
     * @param name
     * @param email
     * @param password
     * */
    public JSONObject registerTaxi(String name, String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));

        // getting JSON Object
        JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
        // return json
        return json;
    }

    /**
     * Function get Login status
     * */
    public boolean isTaxiLoggedIn(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        int count = db.getRowCountTaxi();
        if(count > 0){
            // taxi logged in
            return true;
        }
        return false;
    }

    /**
     * Function to logout taxi
     * Reset Database
     * */
    public boolean logoutTaxi(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        db.resetTables();
        return true;
    }

注册活动(注册和登录非常相似,我只把注册表放在这里):

package com.example.heytaxi;


import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.heytaxi.library.DatabaseHandler;
import com.example.heytaxi.library.UserFunctions;

public class RegisterActivity extends Activity {

    private AsyncRegister mAuthTask = null;

    Button btnRegister;
    Button btnLinkToLogin;
    EditText inputFullName;
    EditText inputEmail;
    EditText inputPassword;
    TextView registerErrorMsg;

    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        // Importing all assets like buttons, text fields
        inputFullName = (EditText) findViewById(R.id.registerName);
        inputEmail = (EditText) findViewById(R.id.registerEmail);
        inputPassword = (EditText) findViewById(R.id.registerPassword);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);



        inputPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
               if (id == R.id.login || id == EditorInfo.IME_NULL) {
                  attemptLogin();
                  return true;
               }
               return false;
            }
         });



        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {         
            public void onClick(View view) {
                /*String name = inputFullName.getText().toString();
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                AsyncRegister registerTask=new AsyncRegister();
                registerTask.execute(name,email,password);
                */
                    attemptLogin();
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                // Close Registration View
                finish();
            }
        });
    }



    public void attemptLogin() {
       // Prova a fare il login solo se non si sta già provando
          if (mAuthTask != null) {
             return;
          }

          // Reset errors.
          inputEmail.setError(null);
          inputPassword.setError(null);

          // Mettiamoci i valori che ci sono nelle view
          String mEmail = inputEmail.getText().toString();
          String mPassword = inputPassword.getText().toString();
          String mName= inputFullName.getText().toString();

          boolean cancel = false;
          View focusView = null;

      // Nome vuoto o minore di 4 caratteri?
          if (TextUtils.isEmpty(mName)) {
             inputFullName.setError(getString(R.string.error_field_required));
             focusView = inputFullName;
             cancel = true;
          } else if (mName.length() < 4) {
             inputFullName.setError(getString(R.string.error_invalid_name));
             focusView = inputFullName;
             cancel = true;
          }

          // Password vuota o minore di 4 caratteri?
          if (TextUtils.isEmpty(mPassword)) {
             inputPassword.setError(getString(R.string.error_field_required));
             focusView = inputPassword;
             cancel = true;
          } else if (mPassword.length() < 4) {
             inputPassword.setError(getString(R.string.error_invalid_password));
             focusView = inputPassword;
             cancel = true;
          }

          // E' un indirizzo email?
          if (TextUtils.isEmpty(mEmail)) {
             inputEmail.setError(getString(R.string.error_field_required));
             focusView = inputEmail;
             cancel = true;
          } else if (!mEmail.contains("@")) {
             inputEmail.setError(getString(R.string.error_invalid_email));
             focusView = inputEmail;
             cancel = true;
          }

          // Se cancel è vero, quindi se è stato settato prima come true, ritorna al login.
          if (cancel) {
             focusView.requestFocus();
          } else {


             // Mostra un progress e fa partire un task in background per l'autenticazione
            /* mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
             showProgress(true);
             mAuthTask = new UserLoginTask();
             mAuthTask.execute((Void) null);
            */ 
             AsyncRegister registerTask=new AsyncRegister();
             registerTask.execute(mName,mEmail,mPassword);
          }
       }


    private class AsyncRegister extends AsyncTask<String, Void, JSONObject>{

        protected JSONObject doInBackground(String...params){

            UserFunctions userFunction=new UserFunctions();
            JSONObject json=userFunction.registerUser(params[0], params[1], params[2]);
            return json;
        }

        protected void onPostExecute(JSONObject json){

            // check for login response
            try {
                if (json!=null && json.getString(KEY_SUCCESS) != null) {
                    registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS); 
                    if(Integer.parseInt(res) == 1){
                        // user successfully registred
                        // Store user details in SQLite Database
                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        // Clear all previous data in database
                        UserFunctions userFunction=new UserFunctions();
                        userFunction.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
                        // Launch Dashboard Screen
                        Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                        // Close all views before launching Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        // Close Registration Screen
                        finish();
                    }else{
                        String err=json.getString(KEY_ERROR_MSG);
                        // Error in registration
                        //registerErrorMsg.setText(err);
                        LayoutInflater inflater = getLayoutInflater();
                        View layout = inflater.inflate(R.layout.toast_layout,
                                                    (ViewGroup) findViewById(R.id.toast_layout_root));

                        TextView text = (TextView) layout.findViewById(R.id.text);
                        text.setText(err);

                        Toast toast = new Toast(getApplicationContext());
                        //toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                        toast.setDuration(Toast.LENGTH_LONG);
                        toast.setView(layout);
                        toast.show();
                    }
                }else{ 
                        //registerErrorMsg.setText("A Error occured in registration(Server Error)");
                    LayoutInflater inflater = getLayoutInflater();
                 View layout = inflater.inflate(R.layout.toast_layout,
                                                (ViewGroup) findViewById(R.id.toast_layout_root));

                 TextView text = (TextView) layout.findViewById(R.id.text);
                 text.setText("Check your internet connection");

                 Toast toast = new Toast(getApplicationContext());
                 //toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                 toast.setDuration(Toast.LENGTH_LONG);
                 toast.setView(layout);
                 toast.show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



        }


    }

0 个答案:

没有答案