我正在创建一个简单的记事本应用程序,并且当在模拟器上按下返回按钮以返回显示列表的MainActivity时,在列表视图中显示数据时会出现问题。它仅在我关闭应用程序并再次打开它时显示数据,然后填充列表视图。我在下面显示了我的代码。
package example.mynotepad;
import example.mynotepad.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
public class MainActivity extends Activity implements OnItemClickListener {
Button Add_Btn;
ListView nListView;
NotesAdapter nAdapter;
Cursor nCursor;
public static boolean isDbCreated = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add_Btn = (Button) findViewById(R.id.add_btn);
Add_Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent AddNotes = new Intent(MainActivity.this, AddNotes.class);
startActivity(AddNotes);
}
});
nListView = (ListView) findViewById(R.id.listView1);
final NotesDbHelper nHelper = new NotesDbHelper(this);
nHelper.Open();
new Handler().post(new Runnable() {
@Override
public void run() {
nCursor = nHelper.AllData();
nAdapter = new NotesAdapter(MainActivity.this, nCursor);
nListView.setAdapter(nAdapter);
}
});
nListView.setOnItemClickListener(this);
nListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int position, long arg3) {
// TODO Auto-generated method stub
TextView id = (TextView) v.findViewById(R.id.textView1);
final int i = Integer.parseInt(id.getText().toString());
AlertDialog.Builder aDialog = new AlertDialog.Builder(
MainActivity.this);
aDialog.setTitle("Delete Note?");
aDialog.setMessage("This Will Delete It Permanently?");
aDialog.setPositiveButton((getString(R.string.Delete)),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface Dialog,
int which) {
nHelper.Delete(i); // Delete Method in DBHelper
nCursor.requery();
nAdapter.notifyDataSetChanged();
nListView.setAdapter(nAdapter);
}
});
aDialog.setNegativeButton((getString(R.string.Cancel)),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
aDialog.show();
return false;
}
});
}
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
TextView noteid = (TextView) view.findViewById(R.id.textView1);
TextView notetitle = (TextView) view.findViewById(R.id.textView2);
TextView notebody = (TextView) view.findViewById(R.id.textView3);
int i = Integer.parseInt(noteid.getText().toString());
String nt = notetitle.getText().toString();
String nb = notebody.getText().toString();
Intent Update = new Intent(MainActivity.this, UpdateNotes.class);
Update.putExtra("id", i);
Update.putExtra("ntitle", nt);
Update.putExtra("nbody", nb);
startActivityForResult(Update, 101);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 101:
nCursor.requery();
nAdapter.notifyDataSetChanged();
nListView.setAdapter(nAdapter);
break;
}
}
}
}
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:text="@string/add_note_btn" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:splitMotionEvents="true" >
</ListView>
</LinearLayout>
package example.mynotepad;
import example.mynotepad.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddNotes extends Activity {
Button Cancel_Btn, Save_Btn;
EditText ET_Title, ET_Notes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_notes);
Cancel_Btn = (Button) findViewById(R.id.cancel_btn);
Save_Btn = (Button) findViewById(R.id.save_btn);
ET_Title = (EditText) findViewById(R.id.et_title);
ET_Notes = (EditText) findViewById(R.id.et_notes);
final NotesDbHelper Helper = new NotesDbHelper(AddNotes.this);
Save_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (ET_Title.getText().toString().trim().equals("")) {
Toast.makeText(getApplicationContext(), "Title Required",
Toast.LENGTH_SHORT).show();
} else if (ET_Notes.getText().toString().trim().equals("")) {
Toast.makeText(getApplicationContext(),
"Don't Forget To Type A Note", Toast.LENGTH_SHORT)
.show();
} else {
boolean Added = true;
try {
String NoteTitle = ET_Title.getText().toString();
String NoteBody = ET_Notes.getText().toString();
Helper.Open();
Helper.AddNote(NoteTitle, NoteBody);
} catch (Exception e) {
Added = false;
e.printStackTrace();
}
finally {
if (Added) {
Toast toast = Toast.makeText(AddNotes.this, "Note Added Successfully", Toast.LENGTH_LONG);
toast.show();
}
Helper.Close();
ET_Title.setText("");
ET_Notes.setText("");
}
}
}
});
Cancel_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tv_title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/et_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:ems="10"
android:inputType="textCapWords" />
<TextView
android:id="@+id/tv_note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tv_note"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/et_notes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginBottom="40dp"
android:ems="10"
android:inputType="textCapSentences|textMultiLine" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/cancel_btn"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="160dp"
android:text="@string/cancel_note_btn" />
<Button
android:id="@+id/save_btn"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="@string/save_note_btn" />
</LinearLayout>
</LinearLayout>
package example.mynotepad;
import example.mynotepad.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateNotes extends Activity {
NotesDbHelper nHelper;
Button UpdateBtn, CancelBtn;
EditText nTitle, nBody;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update_notes);
UpdateBtn = (Button) findViewById(R.id.update_btn);
CancelBtn = (Button) findViewById(R.id.Ucancel_btn);
nTitle = (EditText) findViewById(R.id.Uet_title);
nBody = (EditText) findViewById(R.id.Uet_notes);
Intent intent = getIntent();
Bundle mods = intent.getExtras();
final int id = mods.getInt("id");
String ntitle = mods.getString("ntitle");
String nbody = mods.getString("nbody");
nTitle.setText(ntitle);
nBody.setText(nbody);
UpdateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
nHelper = new NotesDbHelper(UpdateNotes.this);
nHelper.Open();
String nt = nTitle.getText().toString();
String nb = nBody.getText().toString();
nHelper.Update(id, nt, nb);
nHelper.Close();
Intent display = new Intent(UpdateNotes.this,
MainActivity.class);
setResult(RESULT_OK, display);
finish();
Toast.makeText(getApplicationContext(), "Update Successful",
Toast.LENGTH_SHORT).show();
}
});
CancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(UpdateNotes.this, MainActivity.class);
startActivity(intent);
}
});
}
}
package example.mynotepad;
import example.mynotepad.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class NotesAdapter extends CursorAdapter {
public NotesAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
public void bindView(View view, Context context, Cursor cursor) {
TextView noteID = (TextView) view.findViewById(R.id.textView1);
TextView noteTITLE = (TextView) view.findViewById(R.id.textView2);
TextView noteBODY = (TextView) view.findViewById(R.id.textView3);
noteID.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0))));
noteTITLE.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
noteBODY.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}
@SuppressLint("InflateParams")
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View View = mInflater.inflate(R.layout.list, null);
return View;
}
protected void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
notifyDataSetChanged();
}
}
NotesDbHelper:
package example.mynotepad;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class NotesDbHelper {
public static final String DATABASE_NAME = "NotesDB.db";
public static final int version = 1;
public static final String Notes_Table = "Notes";
public static final String Note_ID = "_id";
public static final String NoteTitle = "NoteTitle";
public static final String NoteBody = "NoteBody";
private SQLiteDatabase nDatabase;
public Context Context;
public NotesDbHelper(Context c) {
Context = c;
}
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}
@Override
public void onCreate(SQLiteDatabase Database) {
Database.execSQL("create table " + Notes_Table + " ( " + Note_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT , " + NoteTitle
+ " TEXT NOT NULL ," + NoteBody + " TEXT NOT NULL);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public NotesDbHelper Open() throws SQLException {
DatabaseHelper nDatabaseHelper = new DatabaseHelper(Context);
nDatabase = nDatabaseHelper.getWritableDatabase();
return this;
}
public void Close() {
nDatabase.close();
}
public long AddNote(String noteTitle, String noteBody) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(NoteTitle, noteTitle);
cv.put(NoteBody, noteBody);
return nDatabase.insertOrThrow(Notes_Table, null, cv);
}
public Cursor AllData() {
// TODO Auto-generated method stub
String[] all = new String[] { Note_ID, NoteTitle, NoteBody };
Cursor cursor = nDatabase.query(Notes_Table, all, null, null, null,
null, null);
return cursor;
}
public void Update(int id, String nt, String nb) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(NoteTitle, nt);
cv.put(NoteBody, nb);
nDatabase.update(Notes_Table, cv, Note_ID + " = " + id, null);
}
public void Delete(int i) {
// TODO Auto-generated method stub
nDatabase.delete(Notes_Table, Note_ID + " = " + i, null);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20sp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20sp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20sp" />
</LinearLayout>
我已多次查看我的代码,看起来很好。可能这是我看不到的非常简单的东西,我不知道。真的很感激任何帮助。提前谢谢。
答案 0 :(得分:0)
请添加
setResult(RESULT_OK, display);
finish();
在Save_Btn.setOnClickListener的onClick函数
中即
Save_Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (ET_Title.getText().toString().trim().equals("")) {
Toast.makeText(getApplicationContext(), "Title Required",
Toast.LENGTH_SHORT).show();
} else if (ET_Notes.getText().toString().trim().equals("")) {
Toast.makeText(getApplicationContext(),
"Don't Forget To Type A Note", Toast.LENGTH_SHORT)
.show();
} else {
boolean Added = true;
try {
String NoteTitle = ET_Title.getText().toString();
String NoteBody = ET_Notes.getText().toString();
Helper.Open();
Helper.AddNote(NoteTitle, NoteBody);
} catch (Exception e) {
Added = false;
e.printStackTrace();
}
finally {
if (Added) {
Toast toast = Toast.makeText(AddNotes.this, "Note Added Successfully", Toast.LENGTH_LONG);
toast.show();
}
Helper.Close();
ET_Title.setText("");
ET_Notes.setText("");
}
setResult(RESULT_OK, display);
finish();
}
}
});
答案 1 :(得分:0)
因为您的数据来自DataBase并且您在onCreate()中填充了列表,当您向后导航时没有必要调用该列表,例如当您旋转屏幕时。您应该再次获取数据,例如在Resume上或在Activity结果和更新适配器上,传递新的Cursor来使用。
nListView = (ListView) findViewById(R.id.listView1);
final NotesDbHelper nHelper = new NotesDbHelper(this);
nHelper.Open();
new Handler().post(new Runnable() {
@Override
public void run() {
nCursor = nHelper.AllData();
nAdapter = new NotesAdapter(MainActivity.this, nCursor);
nListView.setAdapter(nAdapter);
}
});
nListView.setOnItemClickListener(this);
nListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int position, long arg3) {
// TODO Auto-generated method stub
TextView id = (TextView) v.findViewById(R.id.textView1);
final int i = Integer.parseInt(id.getText().toString());
AlertDialog.Builder aDialog = new AlertDialog.Builder(
MainActivity.this);
aDialog.setTitle("Delete Note?");
aDialog.setMessage("This Will Delete It Permanently?");
aDialog.setPositiveButton((getString(R.string.Delete)),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface Dialog,
int which) {
nHelper.Delete(i); // Delete Method in DBHelper
nCursor.requery();
nAdapter.notifyDataSetChanged();
nListView.setAdapter(nAdapter);
}
});
aDialog.setNegativeButton((getString(R.string.Cancel)),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
aDialog.show();
return false;
}
});
我认为将此代码放入方法可以调用它,例如:ListIni()应该完成这项工作,然后在onCreate()
和onActivityResult()
中调用它基本上是用新的方法重新创建适配器对象你的案例中的项目集是Cursor。
更新
创建功能
private void AdapterIni() {
nListView = (ListView) findViewById(R.id.listView1);
final NotesDbHelper nHelper = new NotesDbHelper(this);
nHelper.Open();
new Handler().post(new Runnable() {
@Override
public void run() {
nCursor = nHelper.AllData();
nAdapter = new NotesAdapter(MainActivity.this, nCursor);
nListView.setAdapter(nAdapter);
}
});
nListView.setOnItemClickListener(this);
nListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int position, long arg3) {
// TODO Auto-generated method stub
TextView id = (TextView) v.findViewById(R.id.textView1);
final int i = Integer.parseInt(id.getText().toString());
AlertDialog.Builder aDialog = new AlertDialog.Builder(
MainActivity.this);
aDialog.setTitle("Delete Note?");
aDialog.setMessage("This Will Delete It Permanently?");
aDialog.setPositiveButton((getString(R.string.Delete)),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface Dialog,
int which) {
nHelper.Delete(i); // Delete Method in DBHelper
nCursor.requery();
nAdapter.notifyDataSetChanged();
nListView.setAdapter(nAdapter);
}
});
aDialog.setNegativeButton((getString(R.string.Cancel)),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
aDialog.show();
return false;
}
});`
然后替换它,这样你就不会在MainActivity onCreate()中两次调用相同的代码
然后在你的MainActivity onActivityResult函数中调用你的AdapterIni()方法。