Jumat, 09 Juni 2017

Membuat SQLite Database Menu Registrasi dan View list

“Membuat SQLite Database Menu Registrasi dan View list”


Pada laporan kali ini saya akan membuat projeck android yaitu Menu Registrasi dan View List,

1.Buatlah project android dengan nama Tugas2
Activity Name = DBPracticeActivity
Layout Name = main

2. pada praktikum kali ini kita akan membuat banyak class baik itu java maupun xml, untuk memudahkan praktikum saya membuat 2 package yang didalamnya ada beberapa file java seperti gambar berikut.

 

3. kemudian buat lagi beberaa file xml pada folder layout seperti gambar ini :
   

 
4. Ubahlah isi coding main.xml menjadi seperti berikut :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
   <TextView android:layout_height="wrap_content"
       android:id="@+id/textViewMainHeading"
       android:layout_width="wrap_content"
       android:text="Slect your choice"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true">
       
   </TextView>
   <Button android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:text="Register" android:id="@+id/buttonMainRegister"
       android:layout_below="@+id/textViewMainHeading"
       android:layout_centerHorizontal="true" android:layout_marginTop="70dp">
       
   </Button>
   <Button android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:text="View List and Details"
       android:id="@+id/ButtonMainList"
       android:layout_below="@+id/textViewMainHeading"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="133dp">
       
   </Button>
</RelativeLayout>


5. Ubahlah isi coding registration.xml menjadi seperti berikut :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

   <Button
       android:id="@+id/buttonRegisterBack"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true"
       android:text="Back" >
   </Button>

   <EditText android:layout_height="wrap_content"
       android:inputType="textPersonName"
       android:id="@+id/editTextRegName"
       android:layout_width="120dp"
       android:layout_below="@+id/buttonRegisterBack"
       android:layout_toRightOf="@+id/textViewRegName"
       android:layout_marginLeft="51dp"
       android:layout_marginTop="18dp">
       <requestFocus>
           
       </requestFocus>
   </EditText>
   <TextView android:layout_height="wrap_content"
       android:id="@+id/textViewRegName"
       android:layout_width="wrap_content"
       android:text="Name"
       android:layout_alignBottom="@+id/editTextRegName"
       android:layout_toRightOf="@+id/buttonRegisterBack"
       android:layout_marginLeft="36dp"
       android:layout_marginBottom="14dp">
       
   </TextView>
   <EditText android:layout_height="wrap_content"
       android:inputType="textPostalAddress"
       android:layout_width="120dp"
       android:layout_below="@+id/editTextRegName"
       android:layout_alignLeft="@+id/editTextRegName"
       android:layout_marginTop="26dp"
       android:id="@+id/editTextRegAddress">
       
   </EditText>
   <TextView android:layout_height="wrap_content"
       android:id="@+id/textViewRegAddress"
       android:layout_width="wrap_content"
       android:text="Address"
       android:layout_alignTop="@+id/editTextRegAddress"
       android:layout_alignLeft="@+id/textViewRegName"
       android:layout_marginTop="14dp">
       
   </TextView>
   <EditText android:layout_height="wrap_content"
       android:inputType="phone"
       android:layout_centerVertical="true"
       android:layout_alignLeft="@+id/editTextRegAddress"
       android:id="@+id/editTextRegPhone"
       android:layout_width="120dp">
       
   </EditText>
   <TextView android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:layout_centerVertical="true"
       android:layout_alignLeft="@+id/textViewRegAddress"
       android:id="@+id/textViewRegPhone"
       android:text="Phone No.">
       
   </TextView>
   <Button android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:layout_below="@+id/editTextRegPhone"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="38dp"
       android:id="@+id/buttonRegister"
       android:text="Register">
       
   </Button>
   <ImageView android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:src="@drawable/login_icon"
       android:layout_below="@+id/buttonRegister"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="38dp"
       android:id="@+id/imageViewRegLogin">
       
   </ImageView>
   
</RelativeLayout>



6. Ubahlah isi coding list_users.xml menjadi seperti berikut :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >

   <ImageView
       android:id="@+id/icon"
       android:layout_width="22px"
       android:layout_height="22px"
       android:layout_marginLeft="4px"
       android:layout_marginRight="10px"
       android:layout_marginTop="4px"
       android:src="@drawable/login_icon" >
   </ImageView>

   <TextView
       android:id="@+id/textViewList"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignTop="@+id/icon"
       android:layout_marginLeft="20dp"
       android:layout_toRightOf="@+id/icon"
       android:text="@+id/label"
       android:textSize="20px" />

</RelativeLayout>

7. Ubahlah isi coding edit_user.xml menjadi seperti berikut :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >

   <Button
       android:id="@+id/buttonEditBack"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true"
       android:text="Back" >
   </Button>

   <TextView
       android:id="@+id/textViewEditAddress"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/textViewEditName"
       android:layout_alignTop="@+id/editTextEditAddress"
       android:layout_marginTop="14dp"
       android:text="Address" >
   </TextView>

   <Button
       android:id="@+id/buttonEdit"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/editTextEditPhone"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="38dp"
       android:text="Update" >
   </Button>

   <ImageView
       android:id="@+id/imageViewEditLogin"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/buttonEdit"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="38dp"
       android:src="@drawable/login_icon" >
   </ImageView>

   <TextView
       android:id="@+id/textViewEditName"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBottom="@+id/editTextEditName"
       android:layout_marginBottom="14dp"
       android:layout_toRightOf="@+id/buttonEditBack"
       android:text="Name" >
   </TextView>

   <EditText
       android:id="@+id/editTextEditName"
       android:layout_width="120dp"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/buttonEdit"
       android:layout_below="@+id/buttonEditBack"
       android:inputType="textPersonName" >

       <requestFocus>
       </requestFocus>
   </EditText>

   <EditText
       android:id="@+id/editTextEditAddress"
       android:layout_width="120dp"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/editTextEditName"
       android:layout_below="@+id/editTextEditName"
       android:layout_marginTop="14dp"
       android:inputType="textPostalAddress" >
   </EditText>

   <EditText
       android:id="@+id/editTextEditPhone"
       android:layout_width="120dp"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/editTextEditAddress"
       android:layout_below="@+id/editTextEditAddress"
       android:layout_marginTop="14dp"
       android:inputType="phone" >
   </EditText>

   <TextView
       android:id="@+id/textViewEditPhone"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignTop="@+id/editTextEditPhone"
       android:layout_marginTop="15dp"
       android:layout_toRightOf="@+id/buttonEditBack"
       android:text="Phone No." >
   </TextView>

</RelativeLayout>


8. Ubahlah isi coding details_users.xml menjadi seperti berikut :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >

   <ImageView
       android:id="@+id/imageViewDetailsUserIcon"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="31dp"
       android:src="@drawable/login_icon" >
   </ImageView>

   <TextView
       android:id="@+id/textViewDetailsName"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/imageViewDetailsUserIcon"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="51dp"
       android:text="Name" >
   </TextView>

   <TextView
       android:id="@+id/textViewDetailsAddress"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/textViewDetailsName"
       android:layout_below="@+id/textViewDetailsName"
       android:layout_marginTop="28dp"
       android:text="Address" >
   </TextView>

   <TextView
       android:id="@+id/textViewDetailsPhone"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/textViewDetailsAddress"
       android:layout_below="@+id/textViewDetailsAddress"
       android:layout_marginTop="28dp"
       android:text="Phone" >
   </TextView>

   <Button
       android:id="@+id/buttonDetailsBack"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true"
       android:text="Back" >
   </Button>

   <Button
       android:id="@+id/buttonEditDetails"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/textViewDetailsPhone"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="44dp"
       android:text="Edit Details" >
   </Button>

</RelativeLayout>


9. Ubahlah isi coding DBPracticeActivity.java menjadi seperti berikut :

package com.example.tugas2;

//import com.example.db.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DBPracticeActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button regButton = (Button) findViewById(R.id.buttonMainRegister);
        Button listButton = (Button) findViewById(R.id.ButtonMainList);
        regButton.setOnClickListener(this);
        listButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
        case R.id.buttonMainRegister:
            intent = new Intent();
            intent.setClass(getApplicationContext(), Registration.class);
            startActivity(intent);
            break;
        case R.id.ButtonMainList:
            intent = new Intent();
            intent.setClass(getApplicationContext(), ListUsers.class);
            startActivity(intent);
            break;
        }
    }
}




10. Ubahlah isi coding DetailsUsers.java menjadi seperti berikut :

package com.example.tugas2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class DetailsUsers extends Activity implements OnClickListener {
    private static String position = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details_users);
        Intent intent = getIntent();
        position = intent.getStringExtra("position");
        Log.d("value of position from intent", position);
        DatabaseHandler db = new DatabaseHandler(this);
        User user = db.getUser(position);
        TextView textViewDetailName = (TextView) findViewById(R.id.textViewDetailsName);
        textViewDetailName.setText(user.getName());

        TextView textViewDetailAddress = (TextView) findViewById(R.id.textViewDetailsAddress);
        textViewDetailAddress.setText(user.getAddress());

        TextView textViewDetailsPhone = (TextView) findViewById(R.id.textViewDetailsPhone);
        textViewDetailsPhone.setText(user.getPhone());

        Button backButton = (Button) findViewById(R.id.buttonDetailsBack);
        backButton.setOnClickListener(this);

        Button editButton = (Button) findViewById(R.id.buttonEditDetails);
        editButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.buttonDetailsBack) {
            Intent intent = new Intent(getApplicationContext(), ListUsers.class);
            startActivity(intent);
        } else if (v.getId() == R.id.buttonEditDetails) {
            Intent intent = new Intent(getApplicationContext(), EditUsers.class);
            intent.putExtra("position", position);
            startActivity(intent);
        }
    }
}




11. Ubahlah isi coding EditUsers.java menjadi seperti berikut :

package com.example.tugas2;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class EditUsers extends Activity implements OnClickListener {
    private static String position = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_user);
        Intent intent = getIntent();
        position = intent.getStringExtra("position");

        DatabaseHandler db = new DatabaseHandler(this);
        Log.d("position", position);
        // get user for the position clicked for edit
        User user = db.getUser(position);

        Log.d("User Name", user.getName());
        Log.d("Address", user.getAddress());
        Log.d("Users phone", user.getPhone());

        // set the values in editText boxes
        EditText name = ((EditText) findViewById(R.id.editTextEditName));
        name.setText(user.getName());
        EditText address = ((EditText) findViewById(R.id.editTextEditAddress));
        address.setText(user.getAddress());
        EditText phone = ((EditText) findViewById(R.id.editTextEditPhone));
        phone.setText(user.getPhone());

        Button backButton = (Button) findViewById(R.id.buttonEditBack);
        backButton.setOnClickListener(this);

        Button updateButton = (Button) findViewById(R.id.buttonEdit);
        updateButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.buttonEditBack) {
            Intent intent = new Intent(getApplicationContext(), ListUsers.class);
            startActivity(intent);
        } else if (v.getId() == R.id.buttonEdit) {
            User user = new User(
                    ((EditText) findViewById(R.id.editTextEditName)).getText()
                            .toString(),
                    ((EditText) findViewById(R.id.editTextEditAddress))
                            .getText().toString(),
                    ((EditText) findViewById(R.id.editTextEditPhone)).getText()
                            .toString());
            DatabaseHandler db = new DatabaseHandler(this);
            int updateCount = db.editUser(user, position);
            if (updateCount == 1) {
                Toast toast = Toast.makeText(getApplicationContext(),
                        "User successfully updated", Toast.LENGTH_SHORT);
                toast.show();
            } else {
                Toast toast = Toast.makeText(getApplicationContext(),
                        "User update failed, Try Again", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }

}


12.Ubahlah isi coding ListUsers.java menjadi seperti berikut :

package com.example.tugas2;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class ListUsers extends ListActivity {
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
            DatabaseHandler db = new DatabaseHandler(this);
           String[] users = db.getAllUsers();
           if(users!=null) {
               for(String us:users) {
                   Log.d("String Array Value", us);
               }
               db.close();
           }
           // Use your own layout
           ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_users, R.id.textViewList, users);
           setListAdapter(adapter);
       }
       
        @Override
         protected void onListItemClick(ListView l, View v, int position, long id) {
           Log.d("On click of a item", Integer.toString(position));
           Intent intent = new Intent();
           intent.setClass(getApplicationContext(), DetailsUsers.class);
           intent.putExtra("position", Integer.toString(position + 1));  //position starts from 0, but in db row starts from 1
           startActivity(intent);
         }
    }


13. Ubahlah isi coding Registration.java menjadi seperti berikut :

package com.example.tugas2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Registration extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration);
        Button regButton = (Button) findViewById(R.id.buttonRegister);
        regButton.setOnClickListener(this);
        Button backButton = (Button) findViewById(R.id.buttonRegisterBack);
        backButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
        case R.id.buttonRegister:
            register();
            break;
        case R.id.buttonRegisterBack:
            intent = new Intent();
            intent.setClass(getApplicationContext(), DBPracticeActivity.class);
            startActivity(intent);
            break;
        }
    }

    private void register() {
        String user = ((EditText) findViewById(R.id.editTextRegName)).getText()
                .toString();
        String address = ((EditText) findViewById(R.id.editTextRegAddress))
                .getText().toString();
        String phone = ((EditText) findViewById(R.id.editTextRegPhone))
                .getText().toString();
        DatabaseHandler db = new DatabaseHandler(this);
        int id = db.addUser(new User(user, address, phone));
        db.close();
        if (id > 0) {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "User registered at id " + id, Toast.LENGTH_SHORT);
            toast.show();
        } else {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "User registration failed", Toast.LENGTH_SHORT);
            toast.show();
        }
        ((EditText) findViewById(R.id.editTextRegName)).setText("");
        ((EditText) findViewById(R.id.editTextRegAddress)).setText("");
        ((EditText) findViewById(R.id.editTextRegPhone)).setText("");
    }


14. Ubahlah isi coding DatabaseHandler.java menjadi seperti berikut :

package com.example.tugas2;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
   private static final int DATABASE_VERSION = 1;
   // Database Name
   private static final String DATABASE_NAME = "userDB";
   // Employee table name
   private static final String TABLE_USERS = "users";

   private static String USER_ID =  "user_id";
   private static String NAME = "name";
   private static String PHONE = "phone";
   private static String ADDRESS = "address";
   
   public DatabaseHandler(Context context) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }
   
   @Override
   public void onCreate(SQLiteDatabase db) {
       String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "("
               + USER_ID + " INTEGER PRIMARY KEY,"
               + NAME + " TEXT,"
               + PHONE + " TEXT,"
               + ADDRESS + " TEXT"
               + ")";
       db.execSQL(CREATE_USER_TABLE);
       //db.close();
       
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       // Drop older table if existed
       db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
       // Create tables again
       onCreate(db);
       
   }
   
   // Adding new user
   public int addUser(User user)
   {
       SQLiteDatabase db = this.getWritableDatabase();
       ContentValues values = new ContentValues();
       values.put(NAME, user.getName());
       values.put(ADDRESS, user.getAddress());
       values.put(PHONE, user.getPhone());
       // Inserting Row
       int id = (int) db.insert(TABLE_USERS, null, values);
       db.close(); // Closing database connection
       return id;
   }
   
   //updating a existing user
   public int editUser(User user, String position) {
           SQLiteDatabase db = this.getWritableDatabase();
           ContentValues values = new ContentValues();
           values.put(NAME, user.getName());
           values.put(PHONE, user.getPhone());
           values.put(ADDRESS, user.getAddress());
           // updating row
           return db.update(TABLE_USERS, values, USER_ID + " = ?",
                   new String[] { String.valueOf(position) });
   }
   
   public User getUser(String id) {
       SQLiteDatabase db = this.getReadableDatabase();
       Cursor cursor = db.query(TABLE_USERS, new String[] { USER_ID,
               NAME, ADDRESS, PHONE }, USER_ID + "=?",
               new String[] {String.valueOf(id)}, null, null, null, null);
       if (cursor != null)
           cursor.moveToFirst();

       User user = new User(cursor.getString(1),
               cursor.getString(2), cursor.getString(3));
       db.close();
       // return user
       return user;
       
   }
   
       // LIst all users
       public String[] getAllUsers() {
           ArrayList<String> usersList = new ArrayList<String>();
           String selectQuery = "SELECT  * FROM " + TABLE_USERS;
           try {
               SQLiteDatabase db = this.getReadableDatabase();
               Cursor cursor = db.rawQuery(selectQuery, null);
               // looping through all rows and adding to list
               if (cursor.moveToFirst()) {
                   do {
                       String user = cursor.getString(1) + ", " + cursor.getString(2) +  ", " + cursor.getString(3);
                       usersList.add(user);
                   } while (cursor.moveToNext());
               }
   
               String[] users = new String[usersList.size()];
               db.close();
               return (usersList.toArray(users));
           }
           catch(Exception e) {
               Log.d("Error in getting users from DB", e.getMessage());
               return null;
           }
       }
       
}

15. Ubahlah isi coding User.java menjadi seperti berikut :

package com.example.tugas2;



public class User {
    public User() {
           super();
           // TODO Auto-generated constructor stub
       }
       private int userId;
       private String name;
       private String address;
       private String phone;
       
       public User(String name, String address, String phone) {
           super();
           this.name = name;
           this.address = address;
           this.phone = phone;
       }
       public String getName() {
           return name;
       }
       public void setName(String name) {
           this.name = name;
       }
       public String getAddress() {
           return address;
       }
       public void setAddress(String address) {
           this.address = address;
       }
       public String getPhone() {
           return phone;
       }
       public void setPhone(String phone) {
           this.phone = phone;
       }

    }









hasil running :

 



 





 

Tidak ada komentar:

Posting Komentar