简体   繁体   中英

SQLite Database issue in TextView

I've been working on an app where the main Activity leads to CalendarActivity , which has a button leading to another Activity where the user creates an event. Once the event is created, the user is taken back to CalendarActivity , and a previously empty TextView displays the event. The code I've used seems like it should work, and is near verbatim from an online tutorial. I researched the comments of the video and the video maker's blog, and many others seem to say it works fine. I've check over and over, and I believe that its grammatically correct, etc, but I can not get it to load the event into the TextView . Any pointers even would help. I would ask you keep it near basic english, I am just getting into programming and am using this app as a learning experience.

Thanks!

CalendarActivity :

package com.bm.sn.sbeta;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class CalendarActivity extends AppCompatActivity {

CalendarView calendar;
Button createEvent;
public static String createEventDate;
DatabaseHelper db;

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

    Cursor result = db.getAllData();
    if (result.getCount() == 0) {

        noEventToday();

    }else{

        TextView eventList = (TextView)findViewById(R.id.eventList);
        StringBuffer stringBuffer = new StringBuffer();

        while (result.moveToNext()) {

            stringBuffer.append("eventDat : "+result.getString(0)+"\n");
            stringBuffer.append("timeHour : "+result.getString(1)+"\n");
            stringBuffer.append("timeMinue : "+result.getString(2)+"\n");
            stringBuffer.append("event : "+result.getString(3)+"\n");
            stringBuffer.append("location : "+result.getString(4)+"\n");
            stringBuffer.append("crew : "+result.getString(5)+"\n\n");
            eventList.setText(stringBuffer);


        }
    }

    calendar = (CalendarView)findViewById(R.id.calendar);
    calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
            createEventDate = (month+"."+dayOfMonth+"."+year);
            createEvent.setText("Create Event for "+createEventDate);
            }
    });

    createEvent = (Button)findViewById(R.id.eventCreateButton);
    createEvent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent toEventCreateActivity = new Intent(CalendarActivity.this, EventCreateActivity.class);
            startActivity(toEventCreateActivity);
        }
    });
}

/*public void fillEventList (){

}

public void noEventToday(){
    TextView eventList = (TextView)findViewById(R.id.eventList);
    eventList.setText("Nothing scheduled for today.");
}*/
}

EventCreateActivity :

package com.bm.sn.sbeta;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class EventCreateActivity extends AppCompatActivity {

DatabaseHelper db;

String textViewText = CalendarActivity.createEventDate;

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

    db = new DatabaseHelper(this);

    final TextView titleTextView = (TextView)findViewById(R.id.titleTextView);
    titleTextView.setText("Create event for "+textViewText);

    final TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);

    final EditText entryEvent = (EditText)findViewById(R.id.entryEvent);
    final EditText entryLocation = (EditText)findViewById(R.id.entryLocation);
    final EditText entryCrew = (EditText)findViewById(R.id.entryCrew);

    Button createEventButton = (Button)findViewById(R.id.saveEvent);
    createEventButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            db.insertData(
                    titleTextView.toString(),
                    timePicker.getCurrentHour().toString(),
                    timePicker.getCurrentMinute().toString(),
                    entryEvent.getText().toString(),
                    entryLocation.getText().toString(),
                    entryCrew.getText().toString()
                    );

            Toast.makeText(EventCreateActivity.this, "I'll keep that in mind.", Toast.LENGTH_LONG).show();
            Intent toCalendarActivity = new Intent(EventCreateActivity.this, CalendarActivity.class);
            startActivity(toCalendarActivity);


        }
    });
}
}

DatabaseHelper :

package com.bm.sn.sbeta;

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

public class DatabaseHelper extends SQLiteOpenHelper{

public static final String DATABASE_NAME = "SavitaCalendar.db";
public static final String TABLE_NAME = "CalendarEvents";
public static final String col_0 = "ID";
public static final String col_1 = "eventDate" ;
public static final String col_2 = "timeHour";
public static final String col_3 = "timeMinute";
public static final String col_4 = "event";
public static final String col_5 = "location";
public static final String col_6 = "crew";


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,EVENTDATE TEXT,TIMEHOUR TEXT,TIMEMINUTE TEXT, EVENT TEXT, LOCATION TEXT, CREW TEXT); ");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}



public void insertData (String eventDate, String timeHour, String timeMinute, String event, String location, String crew){

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(col_1, eventDate);
    contentValues.put(col_2, timeHour);
    contentValues.put(col_3, timeMinute);
    contentValues.put(col_4, event);
    contentValues.put(col_5, location);
    contentValues.put(col_6, crew);

    db.insert(TABLE_NAME, null, contentValues);
    db.close();

}

public Cursor getAllData(){

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor result = db.rawQuery("select * from "+TABLE_NAME, null);
    return result;

}
}

You're reading your data from the DB in onCreate() .

onCreate() is called when the Activity is (re)created. It is not guaranteed that it will be called when you navigate back from EventCreateActivity .

Take a look at the docs on the Activity lifecycle.

As @nuccio pointed it out, you also seem to forgot to initialize your DatabaseHelper instance.

You should use a singleton pattern there, something like this:

private static DatabaseHelper instance;

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

public static DatabaseHelper getInstance(Context context) {
    if (instance == null) {
        instance = new DatabaseHelper(context.getApplicationContext());
    }
    return instance;
}

You could start EventCreateActivity using startActivityForResult() , and override onActivityResult() in CalendarActivity to update your TextView .

For example:

public class CalendarActivity extends AppCompatActivity {

    private static final int REQUEST_CREATE_EVENT = 0;

    CalendarView calendar;
    Button createEvent;
    public static String createEventDate;
    TextView eventList;

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

        eventList = (TextView) findViewById(R.id.eventList);

        getEvents();

        calendar = (CalendarView) findViewById(R.id.calendar);
        calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                createEventDate = (month + "." + dayOfMonth + "." + year);
                createEvent.setText("Create Event for " + createEventDate);
            }
        });

        createEvent = (Button) findViewById(R.id.eventCreateButton);
        createEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toEventCreateActivity = new Intent(CalendarActivity.this, EventCreateActivity.class);
                startActivityForResult(toEventCreateActivity, REQUEST_CREATE_EVENT);
            }
        });
    }

    private void getEvents() {
        // getting our DatabaseHelper instance
        DatabaseHelper db = DatabaseHelper.getInstance(this);

        Cursor result = db.getAllData();
        if (result.getCount() == 0) {
            noEventToday();
        } else {
            StringBuffer stringBuffer = new StringBuffer();
            while (result.moveToNext()) {
                stringBuffer.append("eventDat : " + result.getString(0) + "\n");
                stringBuffer.append("timeHour : " + result.getString(1) + "\n");
                stringBuffer.append("timeMinue : " + result.getString(2) + "\n");
                stringBuffer.append("event : " + result.getString(3) + "\n");
                stringBuffer.append("location : " + result.getString(4) + "\n");
                stringBuffer.append("crew : " + result.getString(5) + "\n\n");
                eventList.setText(stringBuffer);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK && requestCode == REQUEST_CREATE_EVENT) {
            getEvents();
        }
    }

    public void noEventToday(){
        TextView eventList = (TextView)findViewById(R.id.eventList);
        eventList.setText("Nothing scheduled for today.");
    }
}

And in EventCreateActivity :

createEventButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        db.insertData(
            titleTextView.toString(),
            timePicker.getCurrentHour().toString(),
            timePicker.getCurrentMinute().toString(),
            entryEvent.getText().toString(),
            entryLocation.getText().toString(),
            entryCrew.getText().toString()
        );

        Toast.makeText(EventCreateActivity.this, "I'll keep that in mind.", Toast.LENGTH_LONG).show();

        setResult(RESULT_OK);
        finish();
    }
});

An even better approach would be to pass your new event data in the Intent , so you don't have to read the DB when going back to CalendarActivity .

Or at least return the new row ID, so only one record needs to be queried.

You didn't instantiate your db properly in CalendarActivity.

add this

db = new DatabaseHelper(this);

Here is where to add this to the class:

 package com.mac.training.calendaractivitysqlhelperthing;

 imports ...

 public class CalendarActivity extends AppCompatActivity {

 CalendarView calendar;
 Button createEvent;
 public static String createEventDate;
 DatabaseHelper db;

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

    //ADD this line here
    db = new DatabaseHelper(this);

    Cursor result = db.getAllData();
    if (result.getCount() == 0) {

       //noEventToday();

    }else{

        //etc

That alone should work, but if not. Also update your Manifest as well with this:

activity android:name=".EventCreateActivity"

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


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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
       </activity>

         <activity android:name=".EventCreateActivity" />
     </application>

</manifest>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM