[アンドロイド] P3の改善アプリケーション - Android用データベース
で 2 幸いなことに、我々が持っています データベースを作成します と 完全なインタフェースのデザイン アプリケーション. この時点で、我々は完璧なスポットに続けます
注意:
私は英語で記述します。このシリーズのスクリプト. しかし、それはあなたが簡単に従いますので、「ベトナムから翻訳 "私の英語のライティングスタイルがあります.
ここに: Androidのスタジオ 1.2.2
AndroidのSDK 5.1.1
ミンSDK: 4.0 (アンドロイド 4.0 上記のアプリを使用します)
しかし、あなたは絶対にEclipseと下Android上で行うことができます
ステップ 1: アイテムのアダプタの作成
我々はRecyclerViewHolderを通じてRecyclerViewのアイテムアダプタを作成します。, それは私たちのリストをスムーズにするのに役立ちます, 最適化されました.
package cachhoc.net.tut.demodatabase;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ItemNoteAdapter extends RecyclerView.Adapter<ItemNoteAdapter.RecyclerViewHolder> {
// list of note
private List<Note> list = new ArrayList<Note>();
private Context context;
public ItemNoteAdapter(Context context, List<Note> list) {
this.context = context;
this.list = list;
}
@Override
public int getItemCount() {
return list.size();
}
/**
* connect to item view
*/
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View itemView = inflater.inflate(R.layout.item, viewGroup, false);
return new RecyclerViewHolder(itemView);
}
/**
* set data for item
*/
@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int position) {
Note note = list.get(position);
viewHolder.tvTitle.setText(note.getTitle());
viewHolder.tvContent.setText(note.getContent());
}
public void addItem(int position, Note note) {
list.add(position, note);
notifyItemInserted(position);
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
}
/**
* ViewHolder for item view of list
*/
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
OnClickListener {
public LinearLayout container;
public TextView tvTitle;
public TextView tvContent;
public RecyclerViewHolder(View itemView) {
super(itemView);
container = (LinearLayout) itemView.findViewById(R.id.item_container);
tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
tvContent = (TextView) itemView.findViewById(R.id.tv_content);
container.setOnClickListener(this);
}
// click item then display note
@Override
public void onClick(View v) {
MainActivity.showNote(context, list.get(getPosition()).getId());
}
}
}
私はノートshowNoteを表示するためのメソッドを呼び出す必要があり上方にクリックされたとき 1 アイテム. このメソッドは、クラスMainActivityで書かれています.
ステップ 2: 建設MainActivity
package cachhoc.net.tut.demodatabase;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ItemNoteAdapter adapter;
private List<Note> listNote = new ArrayList<>();
private Context context;
private DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
db = new DatabaseHelper(context);
connectView();
}
/**
* connect java with xml view
*/
private void connectView() {
// find Float Action Button
findViewById(R.id.fab).setOnClickListener(this);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_note);
// If the size of views will not change as the data changes.
recyclerView.setHasFixedSize(true);
// Setting the LayoutManager.
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// Setting the adapter.
adapter = new ItemNoteAdapter(context, listNote);
recyclerView.setAdapter(adapter);
}
/**
* update list note when resume (open app or finish NoteActivity)
*/
public void onResume() {
super.onResume();
updateListNote();
}
/**
* select all note from database and set to ls
* use for loop to add into listNote.
* We must add all item in ls into listNote then adapter can update
* we add reverse ls to show new note at top of list
*/
private void updateListNote() {
// clear old list
listNote.clear();
// add all notes from database, reverse list
ArrayList<Note> ls = db.getListNote("SELECT * FROM " + DatabaseHelper.TABLE_NOTE);
// reverse list
for (int i = ls.size() - 1; i >= 0; i--) {
listNote.add(ls.get(i));
}
adapter.notifyDataSetChanged();
}
/**
* display note have id
*/
public static void showNote(Context context, long id) {
Intent intent = new Intent(context, NoteActivity.class);
// send id to NoteActivity
intent.putExtra(NoteActivity.ID, id);
context.startActivity(intent);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab:
showNote(context, NoteActivity.NEW_NOTE);
break;
default:
break;
}
}
}
コードは、理解することは非常に簡単です. のみ 2 あなたは以下の懸念を共有することができます:
- それがレイアウトRecyclerView設定する必要が動作するようにできるようにするには. LinearLayoutManagerという名前の彼のコードでは一方RecyclerViewリストは、リストビューのように平滑化されます. あなたが使用する場合は、グリッドになりますGridLayoutManager.
-
チョンTA選択のArrayList
LSに割り当てられたデータベースから. そして、むしろlistNoteにこれらの要素をコピーします 割り当てられていないlistNoteの=のLS その後listNoteは異なるメモリ領域を備えていますので、 (LSのメモリ) アダプタが更新できないことができ. 私はリストの先頭の後に書かれたメモを入れたいので、私たちはまたlistNoteに割り当てるには、lsを逆転します.
ステップ 3: ノート起草NoteActivityを作成
package cachhoc.net.tut.demodatabase;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v7.app.AlertDialog;
public class NoteActivity extends AppCompatActivity {
/**
* if action is add new note, it will init by NEW_NOTE
*/
public static final long NEW_NOTE = -1;
/**
* key for get id note from other activity to display note
*/
public static final String ID = "ID";
/**
* to edit, add,... note from database
*/
private DatabaseHelper db;
/**
* note curren
*/
private Note note;
private EditText editTitle;
private EditText editContent;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
context = this;
db = new DatabaseHelper(context);
connectView();
getInfo();
}
/**
* conect with xml view
*/
private void connectView() {
editTitle = (EditText) findViewById(R.id.edit_title);
editContent = (EditText) findViewById(R.id.edit_content);
}
/**
* get info note to display
*/
private void getInfo() {
long id = getIntent().getLongExtra(ID, NEW_NOTE);
// not new note then find note from database by id of note
if (id != NEW_NOTE) {
String sql = "SELECT * FROM " + DatabaseHelper.TABLE_NOTE + " WHERE " + DatabaseHelper.KEY_ID_NOTE + " = " + id;
note = db.getNote(sql);
}
if (note != null) {
editTitle.setText(note.getTitle());
editContent.setText(note.getContent());
} else {
editTitle.setText("");
editContent.setText("");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_note, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
save();
break;
case R.id.menu_delete:
delete();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* get title and content of note, if they empty then finish
* if they not empty then check note is null?
* if note is null (create new note), we will create note and insert into database
* if note not null then we update note
* after save we finish activity
*/
private void save() {
String title = editTitle.getText().toString().trim();
String content = editContent.getText().toString().trim();
String notify = null;
if (TextUtils.isEmpty(title) && TextUtils.isEmpty(content)) {
notify = "note empty, don't save!";
} else {
// new note
if (note == null) {
Note note = new Note();
note.setTitle(title).setContent(content);
if (db.insertNote(note) > 0) {
notify = "add success!";
} else {
notify = "add fail!";
}
} else { // update note
note.setTitle(title).setContent(content);
if (db.updateNote(note)) {
notify = "update success!";
} else {
notify = "update fail!";
}
}
}
Toast.makeText(context, notify, Toast.LENGTH_SHORT).show();
finish();
}
/**
* get title and content of note, if they empty then finish
* if they not empty then show dialog to show question delete
* if select no delete then close dialog
* if select delete then delete note
*/
private void delete() {
String title = editTitle.getText().toString().trim();
String content = editContent.getText().toString().trim();
if (TextUtils.isEmpty(title) && TextUtils.isEmpty(content)) {
finish();
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle(R.string.delete).setIcon(R.mipmap.ic_launcher)
.setMessage("Do you want delete note?");
builder.setPositiveButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteNote();
}
});
builder.show();
}
}
/**
* check note is null?
* if is null then finish
* if note not null then delete in database and finish
*/
private void deleteNote() {
if (note != null) {
String where = DatabaseHelper.KEY_ID_NOTE + " = " + note.getId();
String notify = "delete success!";
if (!db.deleteNote(where)) {
notify = "delete failt!";
}
Toast.makeText(context, notify, Toast.LENGTH_SHORT).show();
}
finish();
}
/**
* click back button on phone
*/
@Override
public void onBackPressed() {
save();
}
}
NoteActivityで, その意図IDに送信されますし始めたとき、. NEUのID = NEW_NOTE (た -1) それは新しいノートを作成することを意味します, 我々はeditTitleのためのsetTextと空の文字列をeditContent. それ以外の場合は、データベースからそのIDに注意してください取ると上に表示されます.
コードを完全に混乱. 私たちは、あなたがアプリケーションを完了することができます願っています.
あなたは、スポットすることができますされ ダウンロードプロジェクトDemoDatabase
一部 4 次に私が変更した場合、現在のアプリケーションエラーが発生することなく、データベースを更新する方法をご案内します.
チュートリアルで行われた投稿 データベースtrongのアンドロイド によって nguyenvanquan7826



アンドロイド上でデータベースを作成するための指示に従ってください. しかし、私はそうNE失敗しました。:
10-22 09:55:29.233 12687-12687/? E / SQLiteLog: (1) そのようなテーブルはありません: tb_note
10-22 09:55:29.233 12687-12687/? D / AndroidRuntime: VMをシャットダウン
10-22 09:55:29.233 12687-12687/? W / dalvikvm: threadidは= 1: キャッチされない例外で終了スレッド (グループ= 0xa617c908)
10-22 09:55:29.233 12687-12687/? E / AndroidRuntime: 致命的な例外: メイン
10-22 09:55:29.233 12687-12687/? E / AndroidRuntime: java.lang.RuntimeException: 活動を再開することができません。 {nguyenduchai.cse.com.mynote / nguyenduchai.cse.com.mynote.MainActivity}: android.database.sqlite.SQLiteException: そのようなテーブルはありません: tb_note (コード 1): , コンパイル中: SELECT * tb_note FROM
10-22 09:55:29.233 12687-12687/? E / AndroidRuntime: android.app.ActivityThread.performResumeActivityで(ActivityThread.java:2742)
することなく、彼らのノスタルジックを修正しました。 ? あなたは一人で解決する方法を知っています…
あなたはレビューを参照してください。, 何のテーブルが存在しないことが報告されているtb_note. あなたが読んで申し訳ありませんを設定しました.
私はテーブルを作成しません知っているtb_note, エラーにアクセスしてください. しかし、彼の慎重に検討コードおよび, あなたが前に実行する手順を見直し. しかし、修正はありません. 特異な星 ?
22時の周りにあなたがあなた自身のためのメッセージに直面しています: fb.com/nguyenvanquan7826
OK. 感謝の禁止.
私の友人は私に尋ねてみましょう: 私はすべてのような手順に従わなければなりません. 私は持っています 1 問題は、新しいノートを追加した後、各ノートが表示されることです 1 真に 1 ページ画面, 他のノートを参照するには、画面をドラッグ, あなたのビデオのように表示されません. そう, 私はどのようなので、表示したいです?
あなたは、アイテムの高さを調整NHE. それがありますので.
ニャチャンに感謝. 私は、このエラーを治します.