我一直在开发一个应用程序,该应用程序的主要Activity导致CalendarActivity,该应用程序具有一个按钮,该按钮导致用户创建事件的另一个Activity。创建事件后,将用户带回到CalendarActivity,并且先前为空的TextView显示事件。我使用的代码似乎应该可以工作,并且在线教程几乎逐字记录。我研究了视频和视频制作者博客的评论,许多其他人似乎都说效果很好。我已经检查了一遍又一遍,并且我相信它在语法上是正确的,等等,但是我无法将其加载到TextView中。任何指针甚至都将有所帮助。我想请您将其保持在基本的英语水平附近,我只是开始编程,并且正在使用此应用程序作为学习经验。

谢谢!
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;

}
}

最佳答案

您正在从数据库中以onCreate()读取数据。

(重新)创建onCreate()时会调用Activity。当您从EventCreateActivity导航回去时,不能保证会调用它。

看看Activity生命周期上的docs

正如@nuccio指出的那样,您似乎也忘记了初始化DatabaseHelper实例。

您应该在此处使用单例模式,如下所示:

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

您可以使用EventCreateActivity来启动startActivityForResult(),并在onActivityResult()中覆盖CalendarActivity以更新TextView

例如:
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.");
    }
}

并在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();
    }
});

更好的方法是将新的事件数据传递到Intent中,因此当您返回CalendarActivity时不必读取数据库。

或者至少返回新的行ID,因此只需要查询一条记录。

09-13 02:23