哪部分数据导致崩溃?

时间:2015-03-30 13:58:58

标签: java android database sqlite adapter

这是我的错误:

03-30 21:34:59.928: E/AndroidRuntime(13901): FATAL EXCEPTION: main
03-30 21:34:59.928: E/AndroidRuntime(13901): Process: com.fcsit.leazy, PID: 13901
03-30 21:34:59.928: E/AndroidRuntime(13901): android.database.sqlite.SQLiteException: near "TABLE": syntax error (code 1): , while compiling: CREATE TABLE TABLE DATA (ID integer primary key autoincrement,USERNAME text,PASSWORD text,WEIGHT integer,HEIGHT integer,AGE integer,GENDER integer,CALORIES integer,CALORIES_BURNED integer,CALORIES_PEDO integer );
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1806)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1737)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at com.fcsit.leazy.DataBaseHelper.onCreate(DataBaseHelper.java:20)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at com.fcsit.leazy.LoginDataBaseAdapter.open(LoginDataBaseAdapter.java:42)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at com.fcsit.leazy.HomeFragment.onCreateView(HomeFragment.java:28)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:814)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.view.Choreographer.doCallbacks(Choreographer.java:614)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.view.Choreographer.doFrame(Choreographer.java:583)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:800)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.os.Handler.handleCallback(Handler.java:733)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.os.Handler.dispatchMessage(Handler.java:95)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.os.Looper.loop(Looper.java:146)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at android.app.ActivityThread.main(ActivityThread.java:5602)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at java.lang.reflect.Method.invokeNative(Native Method)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at java.lang.reflect.Method.invoke(Method.java:515)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
03-30 21:34:59.928: E/AndroidRuntime(13901):    at dalvik.system.NativeStart.main(Native Method)

我的代码如下: DatabseHelper.java

package com.fcsit.leazy;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper
{
    public DataBaseHelper(Context context, String name,CursorFactory factory, int version) 
    {
               super(context, name, factory, version);
    }
    // Called when no database exists in disk and the helper class needs
    // to create a new one.
    @Override
    public void onCreate(SQLiteDatabase _db) 
    {
            _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);

    }
    // Called when there is a database version mismatch meaning that the version
    // of the database on disk needs to be upgraded to the current version.
    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
    {
            // Log the version upgrade.
            Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");


            // Upgrade the existing database to conform to the new version. Multiple
            // previous versions can be handled by comparing _oldVersion and _newVersion
            // values.
            // The simplest case is to drop the old table and create a new one.
            _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
            // Create a new one.
            onCreate(_db);
    }


}

LoginDataBaseAdapter.java

package com.fcsit.leazy;

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

public class LoginDataBaseAdapter {
    static final String DATABASE_NAME = "leazy.db";
    static final int DATABASE_VERSION = 1;
    public static final int NAME_COLUMN = 1;
    // TODO: Create public field for each column in your table.
    // SQL Statement to create a new database.
    static final String DATABASE_CREATE = "CREATE TABLE " + "TABLE DATA" + " ("
            + "ID" + " integer primary key autoincrement,"
            + "USERNAME" +" text,"
            + "PASSWORD" +" text,"
            + "WEIGHT" + " integer,"
            + "HEIGHT" + " integer,"
            + "AGE" + " integer,"
            + "GENDER" + " integer,"
            + "CALORIES" + " integer,"
            + "CALORIES_BURNED" + " integer,"
            + "CALORIES_PEDO" + " integer"
            + " );";

    // Variable to hold the database instance
    public SQLiteDatabase db;
    // Context of the application using the database.
    private final Context context;
    // Database open/upgrade helper
    private DataBaseHelper dbHelper;

    public LoginDataBaseAdapter(Context _context) {
        context = _context;
        dbHelper = new DataBaseHelper(context, DATABASE_NAME, null,
                DATABASE_VERSION);
    }

    public LoginDataBaseAdapter open() throws SQLException {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        db.close();
    }

    public SQLiteDatabase getDatabaseInstance() {
        return db;
    }


    public void insertEntry(Data data){
        ContentValues newValues= new ContentValues();
        newValues.put("USERNAME", data.getUsername());
        newValues.put("PASSWORD", data.getPassword());
        newValues.put("AGE", data.getAge());
        newValues.put("GENDER", data.getGender());
        newValues.put("WEIGHT", data.getWeight());
        newValues.put("HEIGHT", data.getHeight());
        newValues.put("CALORIES", data.getCalories());
        newValues.put("CALORIES_BURNED", data.getCalories_burned());
        newValues.put("CALORIES_PEDO", data.getCalories_pedo());

        db.insert("TABLE DATA", null, newValues);
    }



    public int deleteEntry(Data data) {
        // String id=String.valueOf(ID);
        String where = "USERNAME=?";
        int numberOFEntriesDeleted = db.delete("TABLE DATA", where,
                new String[] { data.getUsername() });
        // Toast.makeText(context,
        // "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted,
        // Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }

     public String getSinlgeEntry(String userName)
     {
     Cursor cursor=db.query("TABLE DATA", null, " USERNAME=?", new String[]{userName},
     null, null, null);
     if(cursor.getCount()<1) // UserName Not Exist
     {
     cursor.close();
     return "NOT EXIST";
     }
     cursor.moveToFirst();
     String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
     cursor.close();
     return password;
     }

    public void updateEntry(Data data) {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("USERNAME", data.getUsername());
        updatedValues.put("PASSWORD", data.getPassword());

        String where = "USERNAME = ?";
        db.update("TABLE DATA", updatedValues, where, new String[] { data.getUsername() });
    }
}

HomeFragment.java

package com.fcsit.leazy;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class HomeFragment extends Fragment {

    Button btnSignIn, btnSignUp;
    LoginDataBaseAdapter loginDataBaseAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.main, container, false);

        // create a instance of SQLite Database
        loginDataBaseAdapter = new LoginDataBaseAdapter(getActivity());
        loginDataBaseAdapter = loginDataBaseAdapter.open();

        // Get The Reference Of Buttons
        btnSignIn = (Button) v.findViewById(R.id.buttonSignIN);
        btnSignUp = (Button) v.findViewById(R.id.buttonSignUP);

        btnSignIn.setOnClickListener(onClickListener);
        btnSignUp.setOnClickListener(onClickListener);

        return v;

        // btnSignUp.setOnClickListener(new View.OnClickListener() {
        // public void onClick(View v) {
        // // TODO Auto-generated method stub
        //
        // // / Create Intent for SignUpActivity and Start The Activity
        // Intent intentSignUP = new Intent(getActivity(),
        // SignUpFragment.class);
        // startActivity(intentSignUP);
        // }
        // });

    }

    final OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v == btnSignUp) {
                // / Create Intent for SignUpActivity and Start The Activity
                Intent intentSignUP = new Intent(getActivity(),
                        SignUpActivity.class);
                startActivity(intentSignUP);

            } 
            else if (v == btnSignIn) {
                final Dialog dialog = new Dialog(getActivity());
                dialog.setContentView(R.layout.login);
                dialog.setTitle("Login");

                // get the References of views
                final EditText editTextUserName = (EditText) dialog
                        .findViewById(R.id.editTextUserNameToLogin);
                final EditText editTextPassword = (EditText) dialog
                        .findViewById(R.id.editTextPasswordToLogin);

                Button btnSignIn = (Button) dialog
                        .findViewById(R.id.buttonSignIn);

                // Set On ClickListener
                btnSignIn.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        // get The User name and Password
                        String userName = editTextUserName.getText().toString();
                        String password = editTextPassword.getText().toString();

                        // fetch the Password form database for respective user
                        // nameS



                        Data data = new Data();
                        String storedPassword = loginDataBaseAdapter
                                .getSinlgeEntry(data.getUsername());

                        // check if the Stored password matches with Password
                        // entered by
                        // user
                        if (password.equals(storedPassword)) {
                            Toast.makeText(getActivity(),
                                    "Congrats: Login Successful",
                                    Toast.LENGTH_LONG).show();
                            dialog.dismiss();

                            Intent intent = new Intent(getActivity(),
                                    SelectionActivity.class);
                            startActivity(intent);
                        } else {
                            Toast.makeText(getActivity(),
                                    "User Name or Password does not match",
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });

                dialog.show();

            }

        }
    };
}

SignUpFragment.java

package com.fcsit.leazy;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class SignUpFragment extends Fragment {
    EditText editTextUserName, editTextPassword, editTextConfirmPassword,
            editTextWeight, editTextHeight, editTextAge;
    Button btnCreateAccount;
    RadioButton radioBtnMale, radioBtnFemale;

    LoginDataBaseAdapter loginDataBaseAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.signup, container, false);

//       ActionBar actionBar = getSupportActionBar();
//       actionBar.setDisplayHomeAsUpEnabled(true);

        // get Instance of Database Adapter
        loginDataBaseAdapter = new LoginDataBaseAdapter(getActivity());
        loginDataBaseAdapter = loginDataBaseAdapter.open();

        // Get References of Views
        editTextUserName = (EditText) v.findViewById(R.id.edittext_username);
//      if (condition) {
//          
//      }
        editTextPassword = (EditText) v.findViewById(R.id.edittext_password);
        editTextConfirmPassword = (EditText) v
                .findViewById(R.id.edittext_confirm_password);
        editTextWeight = (EditText) v.findViewById(R.id.edittext_weight);
        editTextHeight = (EditText) v.findViewById(R.id.edittext_height);
        editTextAge = (EditText) v.findViewById(R.id.edittext_age);
        radioBtnMale = (RadioButton) v.findViewById(R.id.radio_male);
        radioBtnFemale = (RadioButton) v.findViewById(R.id.radio_female);

        btnCreateAccount = (Button) v.findViewById(R.id.button_create_account);
        btnCreateAccount.setOnClickListener(new View.OnClickListener() {

            public void onRadioButtonClicked(View view) {
                // Is the button now checked?
                boolean checked = ((RadioButton) view).isChecked();

                // Check which radio button was clicked
                switch (view.getId()) {
                case R.id.radio_male:
                    if (checked)
                        // Pirates are the best
                        break;
                case R.id.radio_female:
                    if (checked)
                        // Ninjas rule
                        break;
                }
            }

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

                String userName = editTextUserName.getText().toString();
                String password = editTextPassword.getText().toString();
                String confirmPassword = editTextConfirmPassword.getText()
                        .toString();
                String age = editTextAge.getText().toString();
                String weight = editTextWeight.getText().toString();
                String height = editTextHeight.getText().toString();



                isAllFieldsValid();

                // check if any of the fields are vacant
                if (userName.equals("") || password.equals("")
                        || age.equals("") || confirmPassword.equals("")
                        || weight.equals("") || height.equals("")) {
//                  Toast.makeText(getActivity(), "Field Vaccant",
//                          Toast.LENGTH_LONG).show();
                    return;
                }
                // check if both password matches
                if (!password.equals(confirmPassword)) {
                    Toast.makeText(getActivity(), "Password does not match",
                            Toast.LENGTH_LONG).show();
                    return;

                } else {
                    // Save the Data in Database
                    Data suData= new Data();
                    suData.setUsername(userName);
                    suData.setPassword(password);



                    loginDataBaseAdapter.insertEntry(suData);
                    Toast.makeText(getActivity(),
                            "Account Successfully Created ", Toast.LENGTH_LONG)
                            .show();
                    Intent intent = new Intent(getActivity(),LoginActivity.class);
                    startActivity(intent);
                }
            }


        });

        return v;
    }

    private boolean isAllFieldsValid() {
        boolean valid = true; 
        String trim_userName = editTextUserName.getText().toString().trim();
        if("".equals(trim_userName)){
            editTextUserName.setError("Please enter your username");
            valid = false;
        }
        String trim_pasword = editTextPassword.getText().toString().trim();
        if("".equals(trim_pasword)){
            editTextPassword.setError("Please enter your password");
            valid = false;
        }
        String trim_confirm_pwd = editTextConfirmPassword.getText().toString().trim();
        if("".equals(trim_confirm_pwd)){
            editTextConfirmPassword.setError("Please enter your confirmed password");
            valid = false;
        }
        String trim_weight = editTextWeight.getText().toString().trim();
        if("".equals(trim_weight)){
            editTextWeight.setError("Please enter your weight");
            valid = false;
        }
        String trim_height = editTextHeight.getText().toString().trim();
        if("".equals(trim_height)){
            editTextHeight.setError("Please enter your height");
            valid = false;
        }
        String trim_age = editTextAge.getText().toString().trim();
        if("".equals(trim_age)){
            editTextAge.setError("Please enter your age");
            valid = false;
        }
        if (radioBtnFemale.isChecked()==false && radioBtnMale.isChecked()==false) {
            Toast.makeText(getActivity(), "Please selec t your gender", Toast.LENGTH_SHORT).show();;
            return false;
        }
        return valid;
    }
}

对于庞大的代码感到抱歉。以前我的数据库只存储了用户名和密码,但在我添加了其他字段,如年龄,性别,体重,身高,卡路里之后......问题就出现了。我仍然很难理解db,所以请帮忙。

1 个答案:

答案 0 :(得分:1)

TABLE DATA不是有效的表名,因为它包含空格字符。

您可以在任何地方引用名称,但使用其他名称会更容易,例如TableData