[Android] Database for Android - P3 Improving Application

In 2 Fortunately, we have create database and complete interface design application. At this point we continue to perfect spots

Noted:
The script in this series I will write in English. However, it is my English writing style "translated from Vietnamese" so you will easily follow.
HERE: Android studio 1.2.2
Android SDK 5.1.1
Min SDK: 4.0 (Android 4.0 above will be used apps)
But you absolutely can do on Eclipse and the lower android

Step 1: Creating Adapter for item

We will create the item Adapter for RecyclerView through RecyclerViewHolder, it will help our list smoother, Optimized.

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

Above I have to call the method to display the note showNote when clicked 1 item. This method is written in class MainActivity.

Step 2: Construction 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;
        }
    }
}

Code is also very easy to understand. Only 2 Can you share the following concerns:

  • To be able to work it needs to be set a Layout RecyclerView. In his code named LinearLayoutManager Meanwhile RecyclerView list will be smoothed as ListView. If you use, it will be a grid GridLayoutManager.

  • Chúng ta Select ArrayList from the database assigned to ls. Then to copy these elements into rather listNote unassigned listNote = ls because then listNote will feature a different memory area (the memory of ls) makes the adapter can not be updated. We also reverse ls to assign to listNote because I want to put the note was written after the top of the list.

Step 3: Create a note drafted 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();
    }

}

In NoteActivity, when it started to get sent to the id that intent. Nếu id = NEW_NOTE (was -1) it means creating a new note, we setText for editTitle and editContent the empty string. Otherwise, we will take note that id from the database and displayed on.

Code completely confusing. We hope you can complete the application.

You are spot can download project DemoDatabase

Part 4 Next I will guide you how to update the database if a change without the current application error.

Posts made in the tutorial Database trong Android by nguyenvanquan7826