我有待办事项清单,但工作不正常。我使用谷歌经历了很多网站,最后我做到了这一点。但是有一些错误不能正常工作。通知管理器也无法正常工作请帮我解决。谢谢。
Database.java
public class Database extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "Todo_Database";
private static final String TABLE_DATA = "Lists";
private static final String KEY_MESSAGE = "message";
private static final String KEY_DATE = "date";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//onUpgrade(db, 3, 4);
String CREATE_DATA_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_DATA + "("
+ KEY_MESSAGE + " TEXT NOT NULL, " + KEY_DATE + " TEXT NOT NULL " + ")";
db.execSQL(CREATE_DATA_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATA);
// Create tables again
onCreate(db);
}
void createEntry(String message,String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_MESSAGE, message);
values.put(KEY_DATE, date);
db.insert(TABLE_DATA, null, values);
db.close();
}
public String print(String date) {
String result = "";
try{
SQLiteDatabase db = this.getWritableDatabase();
String[] whereArgs = new String[] {date};
String selectQuery = "SELECT "+ KEY_MESSAGE + " FROM " + TABLE_DATA + " WHERE " + KEY_DATE + "=?" + "";
Cursor c = db.rawQuery(selectQuery, whereArgs);
for (c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(0) + ";";
}
db.close();
}
catch(Exception e)
{
result = "";
}
return result;
}
public void deleteMessage(String message, String date) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_DATA + " WHERE " + KEY_MESSAGE + "='" + message + "' AND " + KEY_DATE + "='" + date + "';");
db.close();
}
public void updateMessage(String message, String date, String preMessage, String preDate) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_DATA + " SET " + KEY_MESSAGE + "='" + message + "', " + KEY_DATE + "='" + date + "'" + " WHERE " + KEY_MESSAGE + "='" + preMessage + "' AND " + KEY_DATE + "='" + preDate + "';");
db.close();
}
MainActivity.java
public class MainActivity extends Activity {
Context cont = this;
String selectedDate = "";
ListView lv_List;
TextView tv_MainDate;
TextView tv_SubDateLeft;
TextView tv_SubDateRight;
TextView tv_Error;
Database db = new Database(this);
String currentDate="";
String nextDate="";
String previousDate="";
String selectedItem = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
lv_List = (ListView) findViewById(R.id.listView1);
tv_MainDate = (TextView) findViewById(R.id.MainDateTv);
tv_SubDateLeft = (TextView) findViewById(R.id.SubDateLeftTv);
tv_SubDateRight = (TextView) findViewById(R.id.SubDateRightTv);
tv_Error = (TextView) findViewById(R.id.ErrorTv);
tv_Error.setVisibility(View.INVISIBLE);
currentDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
RunModules();
new AsyncCaller().execute();
tv_SubDateRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
currentDate = tv_SubDateRight.getText().toString();
RunModules();
}
});
tv_SubDateLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
currentDate = tv_SubDateLeft.getText().toString();
RunModules();
}
});
lv_List.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
registerForContextMenu(lv_List);
openContextMenu(lv_List);
selectedItem = lv_List.getItemAtPosition(position).toString();
}
});
}
private void RunModules() {
// TODO Auto-generated method stub
tv_MainDate.setText(currentDate);
String dt = currentDate; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dt));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 1); // number of days to add
tv_SubDateRight.setText(sdf.format(c.getTime())); // dt is now the new date
c.add(Calendar.DATE, -2);
tv_SubDateLeft.setText(sdf.format(c.getTime()));
if(db.print(currentDate).equals("")){
tv_Error.setVisibility(View.VISIBLE);
lv_List.setVisibility(View.INVISIBLE);
}
else{
UpdateListView();
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflate = getMenuInflater();
inflate.inflate(R.menu.contextmenu, menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo contextMenuInfo=(AdapterContextMenuInfo)item.getMenuInfo();
switch(item.getItemId())
{
case R.id.edit:
EditItem();
break;
case R.id.delete:
db.deleteMessage(selectedItem, currentDate);
UpdateListView();
break;
}
return super.onContextItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
AddItem();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void AddItem(){
final Dialog builder = new Dialog(this);
builder.requestWindowFeature(builder.getWindow().FEATURE_NO_TITLE);
builder.setContentView(R.layout.add_item);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.setCancelable(false);
final TextView dateSelection = (TextView) builder.findViewById(R.id.AddselectDateTv);
final EditText message = (EditText) builder.findViewById(R.id.AddeditText1);
Button Done = (Button) builder.findViewById(R.id.AddDone);
Button Cancel = (Button) builder.findViewById(R.id.AddCancel);
Done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(message.getText().toString().equals("")){
Toast.makeText(getApplicationContext(), "Empty message!", Toast.LENGTH_SHORT).show();
}else{
if(dateSelection.getText().equals("Select Date")){
Toast.makeText(getApplicationContext(), "Select a date!", Toast.LENGTH_SHORT).show();
}
else{
db.createEntry(message.getText().toString(), selectedDate);
UpdateListView();
Toast.makeText(getApplicationContext(), "Successfully Added!", Toast.LENGTH_SHORT).show();
builder.cancel();
}
}
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
builder.cancel();
}
});
dateSelection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog builder = new Dialog(cont);
builder.requestWindowFeature(builder.getWindow().FEATURE_NO_TITLE);
builder.setContentView(R.layout.calender);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.setCancelable(false);
TextView done = (TextView) builder.findViewById(R.id.CalenderDone);
final DatePicker datePicker = (DatePicker) builder.findViewById(R.id.datePicker1);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
builder.cancel();
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth()+1;
int year = datePicker.getYear();
String modifiedmonth = "";
if(String.valueOf(month).length() == 1){
modifiedmonth = "0" + String.valueOf(month);
}
else{
modifiedmonth = String.valueOf(month);
}
selectedDate = String.valueOf(day) + "-" + String.valueOf(modifiedmonth) + "-" + String.valueOf(year);
dateSelection.setText(selectedDate);
}
});
builder.show();
}
});
builder.show();
}
public void EditItem(){
final Dialog builder = new Dialog(this);
builder.requestWindowFeature(builder.getWindow().FEATURE_NO_TITLE);
builder.setContentView(R.layout.edit_item);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.setCancelable(false);
final TextView dateSelection = (TextView) builder.findViewById(R.id.EditselectDateTv);
final EditText message = (EditText) builder.findViewById(R.id.EditeditText1);
Button Done = (Button) builder.findViewById(R.id.EditDone);
Button Cancel = (Button) builder.findViewById(R.id.EditCancel);
message.setText(selectedItem);
final String previousMessage = selectedItem;
final String previousDate = currentDate;
Done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(message.getText().toString().equals("")){
Toast.makeText(getApplicationContext(), "Empty message!", Toast.LENGTH_SHORT).show();
}else{
if(dateSelection.getText().equals("Select Date")){
Toast.makeText(getApplicationContext(), "Select a date!", Toast.LENGTH_SHORT).show();
}
else{
//db.createEntry(message.getText().toString(), selectedDate);
db.updateMessage(message.getText().toString(), selectedDate, previousMessage, previousDate);
UpdateListView();
Toast.makeText(getApplicationContext(), "Successfully Edited!", Toast.LENGTH_SHORT).show();
builder.cancel();
}
}
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
builder.cancel();
}
});
dateSelection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog builder = new Dialog(cont);
builder.requestWindowFeature(builder.getWindow().FEATURE_NO_TITLE);
builder.setContentView(R.layout.calender);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.setCancelable(false);
TextView done = (TextView) builder.findViewById(R.id.CalenderDone);
final DatePicker datePicker = (DatePicker) builder.findViewById(R.id.datePicker1);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
builder.cancel();
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth()+1;
int year = datePicker.getYear();
String modifiedmonth = "";
if(String.valueOf(month).length() == 1){
modifiedmonth = "0" + String.valueOf(month);
}
else{
modifiedmonth = String.valueOf(month);
}
selectedDate = String.valueOf(day) + "-" + String.valueOf(modifiedmonth) + "-" + String.valueOf(year);
dateSelection.setText(selectedDate);
}
});
builder.show();
}
});
builder.show();
}
public void UpdateListView(){
if(db.print(currentDate).equals("")){
tv_Error.setVisibility(View.VISIBLE);
lv_List.setVisibility(View.INVISIBLE);
}else{
tv_Error.setVisibility(View.INVISIBLE);
lv_List.setVisibility(View.VISIBLE);
ArrayList<String> myStringArray1 = new ArrayList<String>();
String data = db.print(currentDate);
StringTokenizer token = new StringTokenizer(data,";");
while(token.hasMoreTokens()){
myStringArray1.add(token.nextToken());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myStringArray1);
lv_List.setAdapter(adapter);
}
}
public class AsyncCaller extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
}
@Override
protected Void doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
boolean shown = false;
String dt = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
while(true)
{
String newdt = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
if(!dt.equals(newdt))
shown = true;
if(db.print(dt).equals("")){
}else{
if(!shown){
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher; // icon from resources
CharSequence tickerText = "Today's do lists"; // ticker-text
long when = System.currentTimeMillis(); // notification time
//Toast.makeText(getApplicationContext(), String.valueOf(when), Toast.LENGTH_SHORT).show();
Context context21 = getApplicationContext(); // application Context
CharSequence contentTitle = "Today's do lists"; // expanded message title
CharSequence contentText = "click to view"; // expanded message text
Intent notificationIntent = new Intent(cont, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(cont, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
/* long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;
notification.ledARGB = Color.RED;
notification.ledOffMS = 300;
notification.ledOnMS = 300;*/
notification.setLatestEventInfo(context21, contentTitle, contentText, contentIntent);
mNotificationManager.notify(0, notification);
shown = true;
}
}
}
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
}
}