Android app inserting and displaying data in a ListView

时间:2017-08-04 11:58:29

标签: android sqlite listview

I'm making an app where Epileptic users can store information into an SQLite database about seizures they have recently had and display view them in another activity via a ListView. The app stops working on the emulator when I press the submit data button and if I press any button or tab that brings me to the page (ActivityDiary) where they can view any records..

In the logcat I'm getting a critical RuntimeException .. here FATAL EXCEPTION: main Process: com.example.administrator.seizuretrack, PID: 2783

android.database.sqlite.SQLiteException: near "TimeTEXTDescriptionTEXT": syntax error (code 1): , while compiling: CREATE TABLE diary_table (ID INTEGER PRIMARY KEY AUTOINCREMENT,Date TEXT TimeTEXTDescriptionTEXT

Activity for submitting the data:

public class RecordSeizuresActivity extends AppCompatActivity {

    /**instantiating the floating button objects**/
    FloatingActionButton homeBut;
    FloatingActionButton seizureBut;
    FloatingActionButton diaryBut;
    DatabaseHelper myDB;

    /**instantiate the objects for database handling**/
    private Button butAddData, butViewData;
    private EditText dateText, timeText, desText;

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

        /************Database code in onCreate method*************************/
        /**Create an instance of Database Helper class, call the constructor**/
        myDB = new DatabaseHelper(this);
        dateText = (EditText) findViewById(R.id.dateText);
        timeText = (EditText) findViewById(R.id.timeText);
        desText = (EditText) findViewById(R.id.desText);
        butAddData = (Button) findViewById(R.id.butAddData);
        butViewData = (Button) findViewById(R.id.butViewData);

        myDB = new DatabaseHelper(this);

        butAddData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getDate = dateText.getText().toString();
                String getTime = timeText.getText().toString();
                String getDescription = desText.getText().toString();

                if (dateText.length() != 0 && timeText.length() != 0 && desText.length() != 0){

                    AddData(getDate, getTime, getDescription);
                    /**reset the text boxes so that they are blank**/
                    dateText.setText(" ");
                    timeText.setText(" ");
                    desText.setText(" ");

                } else {
                    Toast.makeText(getApplicationContext(), "Please enter all fields!", Toast.LENGTH_LONG).show();
                }
            }
        });

            butViewData.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent intent = new Intent(RecordSeizuresActivity.this,ActivityDiary.class);
                startActivity(intent);
            }
        });
    }

    public void AddData(String getDate, String getTime, String getDescription){
        boolean insertData = myDB.AddData(getDate, getTime, getDescription);

        if (insertData == true){
            Toast.makeText(getApplicationContext(), "Successfully Entered A New Seizure Record!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show();
        }
    }

DatabaseHelper: 
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseHelper";
    public static final String DATABASE_NAME = "SeizureTrack.db";
    public static final String TABLE_NAME = "diary_table";

    public static final String COL_1 = "ID";
    public static final String COL_2 = "Date";
    public static final String COL_3 = "Time";
    public static final String COL_4 = "Description";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COL_2 + " TEXT " + COL_3 + "TEXT" + COL_4 + "TEXT");
    }

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

    public boolean AddData(String item, String item2, String item3) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2, item);
        contentValues.put(COL_3, item2);
        contentValues.put(COL_4, item3);

        Log.d(TAG, "AddData: Adding " + item + item2 + item3 + " to " + TABLE_NAME);
        long result = db.insert(TABLE_NAME, null, contentValues);

        /**if data is inserted incorrectly it will return -1**/
        if (result == -1){
            return false;
        } else {
            return true;
        }
    }

    public Cursor getListContents() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
        return data;
    }
}

activity for viewing the data: 

public class ActivityDiary extends AppCompatActivity {
    FloatingActionButton homeBut;
    FloatingActionButton seizureBut;
    FloatingActionButton diaryBut;

    DatabaseHelper myDB;
    ArrayList<User> userList;
    ListView listView;
    User user;

    /**instantiate the objects for database handling**/

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

        Toast.makeText(getApplicationContext(), "Diary", Toast.LENGTH_LONG).show();

        homeBut = (FloatingActionButton)findViewById(R.id.floatingHomeButton);
        homeBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ActivityDiary.this, HomeActivity.class));
            }
        });
        seizureBut = (FloatingActionButton)findViewById(R.id.floatingRecSeizuresButton);
        seizureBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ActivityDiary.this, RecordSeizuresActivity.class));
            }
        });
        diaryBut = (FloatingActionButton)findViewById(R.id.floatingDiaryButton);
        diaryBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ActivityDiary.this, ActivityDiary.class));
            }
        });

        /************Database code in onCreate method*************************/
        /**Create an instance of Database Helper class, call the constructor**/
        myDB = new DatabaseHelper(this);

        userList = new ArrayList<>();
        Cursor data = myDB.getListContents();

        int numRows = data.getCount();
        if(numRows == 0){
            /**handles all NullPointerExceptions**/
            Toast.makeText(ActivityDiary.this, "You No Have Seizures On Record!", Toast.LENGTH_LONG).show();
        } else {
            while (data.moveToNext()) {
                user = new User(data.getString(1), data.getString(2), data.getString(3));
                userList.add(user);
            }

            ThreeColumn_ListAdapter adapter = new ThreeColumn_ListAdapter(this, R.layout.adapter_view_layout, userList);
            listView = (ListView) findViewById(R.id.listView);
            listView.setAdapter(adapter);
        }
    }
}

List adapter class: 

public class ThreeColumn_ListAdapter extends ArrayAdapter<User> {
    private LayoutInflater uInflater;
    private ArrayList<User> users;
    private int uViewResourceId;


    public ThreeColumn_ListAdapter(Context context, int textViewResourceId, ArrayList<User> users){
        super(context, textViewResourceId, users);
        this.users = users;
        uInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        uViewResourceId = textViewResourceId;
    }
    public View getView(int position, View convertView, ViewGroup parents){
        User user = users.get(position);

        if(user != null){
            TextView getDes = (TextView) convertView.findViewById(R.id.textSeizureType);
            TextView getDate = (TextView) convertView.findViewById(R.id.textDate);
            TextView getTime = (TextView) convertView.findViewById(R.id.textTime);

            if(getDes != null){
                getDes.setText((user.getDescription()));
            }
            if(getDate != null){
                getDate.setText((user.getDate()));
            }
            if(getTime != null){
                getTime.setText((user.getTime()));
            }
        }
        return convertView;
    }
}

Manifest file: 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.seizuretrack">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".LoginActivity1"
            android:label="@string/title_activity_login1"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.administrator.seizuretrack.MainActivity" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HomeActivity" />
        <activity android:name=".AboutActivity"/>
        <activity android:name=".RecordSeizuresActivity"/>
        <activity android:name=".ActivitySettings"/>
        <activity android:name=".ActivityDiary"/>
    </application>
</manifest>

2 个答案:

答案 0 :(得分:1)

update your db.execSQL query like this

 String CREATE_BILL_TABLE = "CREATE TABLE "
            + TABLE_NAME +
            "("
            + id +
            " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COL_2 +
            " TEXT,"
            + COL_3 +
            " TEXT,"
            + COL_4 + " TEXT" + ")";      


    db.execSQL(CREATE_BILL_TABLE);

答案 1 :(得分:0)

It's better to consider using some ORM instead of using SQLite directly. There are some variants:

1) Realm: https://realm.io/docs/java/latest/#getting-started

2) GreenDao: http://greenrobot.org/greendao/documentation/updating-to-greendao-3-and-annotations/

3) etc...