Aplikasi CRUD Data Kontak Menggunakan SQLite

TheHeran.com/ April 30, 2017/ SQLite/ 0 comments

Aplikasi CRUD Data Kontak Menggunakan SQLite merupakan lanjutan dari beberapa tutorial yang berkaitan dengan SQLite. Tutorial SQLite tersebut dapat di baca pada link di bawah ini:

  1. https://theheran.com/load-data-sqlite-ke-spinner-android/

Pada edisi saat ini akan di bahas tentang CRUD (Create, Read, Update Delete) dengan studi kasus data kontak pada database SQLite. Secara sederhana aplikasi yang akan di design dapat melakukan penambahan data, perubahan data, mengambil atau membaca data dan melakukan hapus data. Demo aplikasi bisa download pada link di bawah ini.

DOWNLOAD DEMO APK

 

START PROJECT

  1. Buat project dengan nama package “com.example.crudsqlite”.  untuk lebih lengkap tentang membuat project menggunakan IDE Eclipse bisa di lihat disini. Bagi yang menggunakan Android Studio project ini bisa langsung diconvert menggunakan IDE Android Studio
  2. Buka file strings.xml dan lakukan modifikasi seperti koding dibawah ini
       <?xml version="1.0" encoding="utf-8"? >
       <resources >
    
           <string name="app_name" >Crud Sqlite   </string >
           <string name="hello_world" >Hello world!   </string >
           <string name="action_settings" >Settings   </string >
           <string name="action_resetData" >Reset Data   </string >
           <string name="action_logout" >Logout   </string >
           <string name="title_activity_manag_user" >Manajemen Data User   </string >
           <string name="title_activity_main_activity" >List Data User   </string >
           <string name="txtTheheran" > www.theheran.com | 571078A7   </string >
       
        
            <string-array name="tipeUser" >
                <item >Pilih   </item >
                <item >SUPER ADMIN   </item >
                <item >USER   </item >
           </string-array >
    
       </resources >
    
    
  3. Buat class baru beri nama ModelUser.java  kemudian ketikkan kode dibawah ini. Bagi yang mau download file classnya bisa di download disini
    package com.example.crudsqlite;
    
    public class ModelUser {
    
    	/*
    	 Author : www.theheran.com | [email protected]
    	 PIN BBM: 571078A7
    	*/
    	
    	private String idUser;
    	private String nama;
    	private String username;
    	private String password;
    	private String email;
    	private String tipeUser;
    	private String no;
    	private Boolean isLogin;
    	
    	
    	
    	public String getIdUser() {
    		return idUser;
    	}
    	public void setIdUser(String idUser) {
    		this.idUser = idUser;
    	}
    	
    	public String getNama() {
    		return nama;
    	}
    	public void setNama(String nama) {
    		this.nama = nama;
    	}
    	public String getUsername() {
    		return username;
    	}
    	
    	public void setUsername(String username) {
    		this.username = username;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
    	public String getEmail() {
    		return email;
    	}
    	public void setEmail(String email) {
    		this.email = email;
    	}
    	public String getTipeUser() {
    		return tipeUser;
    	}
    	public void setTipeUser(String tipeUser) {
    		this.tipeUser = tipeUser;
    	}
    	public String getNo() {
    		return no;
    	}
    	public void setNo(String no) {
    		this.no = no;
    	}
    	public Boolean getIsLogin() {
    		return isLogin;
    	}
    	public void setIsLogin(Boolean isLogin) {
    		this.isLogin = isLogin;
    	}
    	
    	
    }
    
    
  4. Selanjutnya buat class baru dan beri nama DatabaseHandler.java . Class ini berfungsi untuk menampung operasi-operasi yang berkaitan dengan database SQLite mulai dari membuat database, input data, edit data dan lain-lain.
    package com.example.crudsqlite;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DatabaseHandler extends SQLiteOpenHelper {
    
    	/*
    	 Author : www.theheran.com | [email protected]
    	 PIN BBM: 571078A7
    	*/
    	
        // Versi database
        private static final int DATABASE_VERSION = 1;
        
        // Nama Database
        private static final String DATABASE_NAME = "db_user";
    
        // Nama Tabel
        private static final String TABLE_USER = "tb_user";
    
        // Colom pada tabel
        public static final String KEY_ID_USER = "id";
        public static final String KEY_NAMA = "nama";
        public static final String KEY_USERNAME = "username";
        public static final String KEY_PASSWORD = "password";
        public static final String KEY_EMAIL = "email";
        public static final String KEY_TIPE_USER = "tipe_user";
        
      
    
        public DatabaseHandler(Context context) {
        	super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        // Membuat Tabel
        @Override
        public void onCreate(SQLiteDatabase db) {
    		dataAwal(db);
        }
        
        
        private void dataAwal(SQLiteDatabase db){
        	
    		String CREATE_modelUserS_TABLE = "CREATE TABLE " + TABLE_USER + "("
    				+ KEY_ID_USER + " INTEGER PRIMARY KEY," + KEY_NAMA + " TEXT," + KEY_USERNAME + " TEXT," +
    				 KEY_PASSWORD + " TEXT," + KEY_EMAIL + " TEXT," + KEY_TIPE_USER + " TEXT)";
    			db.execSQL(CREATE_modelUserS_TABLE);
        	
        	String masterAdmin = "INSERT INTO " + TABLE_USER +"("+KEY_NAMA+","+KEY_USERNAME+","+KEY_PASSWORD+","+KEY_EMAIL+","+KEY_TIPE_USER+")" +
        			" VALUES ('Master Admin','admin','admin','[email protected]','SUPER ADMIN')";
    		db.execSQL(masterAdmin);
        }
        
     // Proses Reset data
        public void prosesResetData() {
        	SQLiteDatabase db = this.getWritableDatabase();
        	String hapusTabel= "DROP TABLE " + TABLE_USER;
    		db.execSQL(hapusTabel);
    		dataAwal(db);
        }
        
    
        // Upgrading database
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        	// Drop older table if existed
    		db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
    		// Create tables again
    		onCreate(db);
        }
    
    
        // Tambah Data user Baru
        public void prosesTambahUser(ModelUser modelUser) {
    		SQLiteDatabase db = this.getWritableDatabase();
    		ContentValues values = new ContentValues();
    		values.put(KEY_NAMA, modelUser.getNama());
    		values.put(KEY_USERNAME, modelUser.getUsername());
    		values.put(KEY_PASSWORD, modelUser.getPassword());
    		values.put(KEY_EMAIL, modelUser.getEmail());
    		values.put(KEY_TIPE_USER, modelUser.getTipeUser());
    		// Input Data
    		db.insert(TABLE_USER, null, values);
    		db.close(); 
    		// Tutup koneksi database
        }
        
        // Update Data
        public int prosesUpdate(ModelUser modelUser) {
    		SQLiteDatabase db = this.getWritableDatabase();
    		ContentValues values = new ContentValues();
    		values.put(KEY_NAMA, modelUser.getNama());
    		values.put(KEY_USERNAME, modelUser.getUsername());
    		values.put(KEY_PASSWORD, modelUser.getPassword());
    		values.put(KEY_EMAIL, modelUser.getEmail());
    		values.put(KEY_TIPE_USER, modelUser.getTipeUser());
    		//proses update tabel
    		return db.update(TABLE_USER, values, KEY_ID_USER + " = ?",new String[] { String.valueOf(modelUser.getIdUser()) });
        }
        
        // Hapus Data
        public int prosesHapus(String idUser) {
    		SQLiteDatabase db = this.getWritableDatabase();
    		return db.delete(TABLE_USER, KEY_ID_USER + " = ?",new String[] {idUser });
        }
        
        
        public ModelUser getUserById(String id){
        	ModelUser mdUser=null;
        	
            String selectQuery = "SELECT  * FROM " + TABLE_USER+" where "+KEY_ID_USER+"="+id;
          
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            
            if (cursor.moveToFirst()) {
                do {
                	mdUser = new ModelUser();
                	
                	mdUser.setIdUser(cursor.getString(cursor.getColumnIndex(KEY_ID_USER)));
                	mdUser.setNama(cursor.getString(cursor.getColumnIndex(KEY_NAMA)));
                	mdUser.setUsername(cursor.getString(cursor.getColumnIndex(KEY_USERNAME)));
                	mdUser.setPassword(cursor.getString(cursor.getColumnIndex(KEY_PASSWORD)));
                	mdUser.setEmail(cursor.getString(cursor.getColumnIndex(KEY_EMAIL)));
                	mdUser.setTipeUser(cursor.getString(cursor.getColumnIndex(KEY_TIPE_USER)));
               } while (cursor.moveToNext());
            }
             
            // Tutup Koneksi
            cursor.close();
            db.close();
             
            return mdUser;
        }
        
        public ModelUser getLogin(String username,String Password){
        	ModelUser mdUser=null;
        	
        	String selectQuery = "SELECT  * FROM " + TABLE_USER+" where "+KEY_USERNAME+"='"+username+"' and "+KEY_PASSWORD+"='"+Password+"'";
            
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            
            if (cursor.moveToFirst()) {
                do {
                	mdUser = new ModelUser();
                	
                	mdUser.setIdUser(cursor.getString(cursor.getColumnIndex(KEY_ID_USER)));
                	mdUser.setNama(cursor.getString(cursor.getColumnIndex(KEY_NAMA)));
                	mdUser.setUsername(cursor.getString(cursor.getColumnIndex(KEY_USERNAME)));
                	mdUser.setPassword(cursor.getString(cursor.getColumnIndex(KEY_PASSWORD)));
                	mdUser.setEmail(cursor.getString(cursor.getColumnIndex(KEY_EMAIL)));
                	mdUser.setTipeUser(cursor.getString(cursor.getColumnIndex(KEY_TIPE_USER)));
                	mdUser.setIsLogin(true);
               } while (cursor.moveToNext());
            }else{
            	mdUser = new ModelUser();
            	mdUser.setIsLogin(false);
            }
            
            // Tutup Koneksi
            cursor.close();
            db.close();
        	
            return mdUser;
        }
    
        
        // Method ambil semua data user
        public   Cursor prosesAmbilSemuaDatauser(){
        	
    	        String selectQuery = "SELECT  * FROM " + TABLE_USER;
    	        SQLiteDatabase db = this.getReadableDatabase();
    	        Cursor cursor = db.rawQuery(selectQuery, null);
    	        // returning cursor
    	        return cursor;
    	 }
        
        
    
     
        
    }
    
    
  5. Buat class baru beri nama LoginActivity.java dan untuk nama layoutnya beri nama activity_login.xml. Class ini akan di panggil pertama kali ketika aplikasi di buka. Ketikkan koding dibawah ini:
    package com.example.crudsqlite;
    
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.view.KeyEvent;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class LoginActivity extends Activity {
    	EditText username,password;
    	
    	
    	/*
    	 Author : www.theheran.com | [email protected]
    	 PIN BBM: 571078A7
    	*/
    	
    	private long lastPressedTime;
    	private static final int PERIOD = 2000;
    	
    	@Override
    	public void onBackPressed() {
    	    super.onBackPressed();
    	    this.finish();
    	}	
    	
    	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	    //Handle the back button
    		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
    	        switch (event.getAction()) {
    	        case KeyEvent.ACTION_DOWN:
    	            if (event.getDownTime() - lastPressedTime             < PERIOD) { finish(); }else { Toast.makeText(getApplicationContext(), "Tekan 2 kali untuk keluar",Toast.LENGTH_SHORT).show(); lastPressedTime = event.getEventTime(); } return true; } } return false; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (android.os.Build.VERSION.SDK_INT > 9) {
    			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    					.permitAll().build();
    			StrictMode.setThreadPolicy(policy);
    		}
    		
    		
    		username = (EditText) findViewById(R.id.text_username);
    		password = (EditText) findViewById(R.id.text_pass);
    		username.setText("admin");
    		password.setText("admin");
    		
    		
    	}
    	
    	public void Login (View v){
    		if(username.getText().toString().isEmpty()){
    			username.setError("Kosong");
    		}else if(password.getText().toString().isEmpty()){
    			password.setError("Kosong");
    		}else{
    			DatabaseHandler db = new DatabaseHandler(getApplicationContext());
    			ModelUser mdUser = db.getLogin(username.getText().toString(), password.getText().toString());
    			
    			if(mdUser.getIsLogin()){
    				Intent i = new Intent(getApplicationContext(),MainActivity.class);
    				startActivity(i);
    				finish();
    			}else{
    				Toast.makeText(LoginActivity.this, "Periksa Username atau Password",Toast.LENGTH_LONG).show();
    			}
    		}
    	}
    	
    	public void Batal (View v){
    		finish();
    	}
    	
    	
    }
    
    
  6. Buka layout activity_login.xml dari class LoginActivity.java kemudian lakukan modifikasi seperti koding dibawah ini. Pada layout ini di perlukan beberapa resource xml dan icon yang dapat di download pada link di bawah ini
  7. Download backgroud bg.jpg, person2.png dan bg_transparent_white.xml serta letakkan di folder res/drawable-hdpi atau res/drawable
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/bg" android:orientation="vertical" >
    
           <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/layHeader" android:orientation="horizontal" >
    
               <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="22dp" android:background="@drawable/bg_transparent_white" android:orientation="horizontal" android:padding="20dp" >
    
                   <EditText android:id="@+id/text_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:gravity="center" android:hint="USERNAME" android:textSize="20sp" >
    
                       <requestFocus / >
                   </EditText >
    
                   <EditText android:id="@+id/text_pass" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/text_username" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="21dp" android:gravity="center" android:hint="PASSWORD" android:inputType="textPassword" android:textSize="20sp" / >
    
                   <Button android:id="@+id/btn_cancel" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignRight="@+id/text_pass" android:layout_below="@+id/text_pass" android:layout_marginTop="26dp" android:background="#ffff4444" android:onClick="Batal" android:text="BATAL" android:textColor="@android:color/white" android:textSize="20sp" android:textStyle="bold" / >
    
                   <Button android:id="@+id/btn_login" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/btn_cancel" android:layout_alignBottom="@+id/btn_cancel" android:layout_alignLeft="@+id/text_pass" android:background="#00893d" android:onClick="Login" android:text="LOGIN" android:textColor="@android:color/white" android:textSize="20sp" android:textStyle="bold" / >
               </RelativeLayout >
    
               <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/relativeLayout1" android:layout_marginTop="28dp" android:background="@drawable/bg_transparent_white" android:gravity="center" android:text="www.theheran.com | 571078A7" android:textColor="@android:color/black" android:textSize="15dp" / >
    
           </RelativeLayout >
    
           <RelativeLayout android:id="@+id/layHeader" android:layout_width="fill_parent" android:layout_height="136dp" android:orientation="horizontal" >
    
              <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_below="@+id/img" android:textStyle="bold" android:textColor="@android:color/black" android:layout_centerHorizontal="true" android:text="@string/app_name" android:textAppearance="?android:attr/textAppearanceMedium" / >
    
              <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="100dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:src="@drawable/person2" / >
            
           </RelativeLayout >
       
    
       </RelativeLayout >
    
  8. Buat class ManagUserActivity.java dan pada layoutnya beri nama manag_user.xml, Class ini merupakan class yang akan menghandle  untuk proses tambah dan ubah data. Lakukan modifikasi seperti dibawah ini
    package com.example.crudsqlite;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.Toast;
    
    public class ManagUserActivity extends Activity {
    	
    	/*
    	 Author : www.theheran.com | [email protected]
    	 PIN BBM: 571078A7
    	*/
    	
    	EditText nama,username,password,email; //declarasi EditText
    	Spinner tipeUser;String mode="",idUser="0";
    	Button btnSimpan;
    	
    	
    	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	    //Handle the back button
    		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
    	        switch (event.getAction()) {
    	        case KeyEvent.ACTION_DOWN:
    	            
    	        	Intent i = new Intent(getApplicationContext(),MainActivity.class);
    				startActivity(i);
    				finish();
    				
    	            return true;
    	        }
    	    }
    	    return false;
    	    
    	}
    	
    	private static  String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";	
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_manag_user);
    		
    		
    		nama =(EditText) findViewById(R.id.txtNama);
    		username =(EditText) findViewById(R.id.txtUsername);
    		password =(EditText) findViewById(R.id.txtPassword);
    		email =(EditText) findViewById(R.id.txtEmail);
    		
    		tipeUser =(Spinner) findViewById(R.id.spinner1);
    		btnSimpan=(Button) findViewById(R.id.btnSimpan);
    		
    		//Cek mode hasil parameter yang dikirim oleh class MainActivity.java
    		Intent in = this.getIntent();
    		mode= in.getStringExtra("mode");
    		
    		if(mode.equals("Edit")){
    			  idUser =  in.getStringExtra("id_user");
    			  if(idUser.equals("1")){
    				  username.setEnabled(false);
    				  password.setEnabled(false);
    			  }else{
    				  username.setEnabled(true);
    				  password.setEnabled(true);
    			  }
    			  
    			  DatabaseHandler db = new DatabaseHandler(getApplicationContext());
    			  ModelUser dataUser = db.getUserById(idUser);
    			  
    			  nama.setText(dataUser.getNama());
    			  username.setText(dataUser.getUsername());
    			  password.setText(dataUser.getPassword());
    			  email.setText(dataUser.getEmail());
    			  tipeUser.setSelection(getSelection(dataUser.getTipeUser()));
    			  
    		}
    		
    	}
    	
    		// handle tombol Simpan. pada XML layout tombol sudah di beri properti onClick dan di beri nama "Simpan"
    		public View Simpan(View v){
    				if(nama.getText().toString().isEmpty()){
    					nama.setError("Form Kosong");
    				}else if(username.getText().toString().isEmpty()){
    					username.setError("Form Kosong");
    				}else if(password.getText().toString().isEmpty()){
    					password.setError("Form Kosong");
    				}else if(email.getText().toString().isEmpty()){
    					email.setError("Form Kosong");
    				}else if(!email.getText().toString().matches(EMAIL_REGEX)){
    					email.setError("Format Email Salah");
    				}else if(tipeUser.getSelectedItemPosition()==0){
    					Toast.makeText(ManagUserActivity.this, "Silahkan Tentukan Tipe User",Toast.LENGTH_LONG).show();
    				}else{
    					ModelUser mdUser = new ModelUser();
    					mdUser.setNama(nama.getText().toString());
    					mdUser.setUsername(username.getText().toString());
    					mdUser.setPassword(password.getText().toString());
    					mdUser.setEmail(email.getText().toString());
    					mdUser.setTipeUser(tipeUser.getSelectedItem().toString());
    					
    					DatabaseHandler db = new DatabaseHandler(getApplicationContext());
    					  
    					  
    					if(mode.equals("Edit")){
    						mdUser.setIdUser(idUser);
    						int status = db.prosesUpdate(mdUser);
    						if(status   >0){
    							Toast.makeText(ManagUserActivity.this, "Data Berhasil Diubah ",Toast.LENGTH_LONG).show();
    							
    						}else{
    							Toast.makeText(ManagUserActivity.this, "Data Gagal Diubah ",Toast.LENGTH_LONG).show();
    						}
    						
    						Intent i = new Intent(getApplicationContext(),MainActivity.class);
    						startActivity(i);
    						finish();
    						
    						
    					}else{
    						db.prosesTambahUser(mdUser);
    						Toast.makeText(ManagUserActivity.this, "Proses Berhasil ",Toast.LENGTH_LONG).show();
    						
    						Intent i = new Intent(getApplicationContext(),MainActivity.class);
    						startActivity(i);
    						finish();
    					}
    					
    				}
    				
    			return v;
    		}
    	
    		public View Kembali(View v){
    				Intent i = new Intent(getApplicationContext(),MainActivity.class);
    				startActivity(i);
    				finish();
    			return v;
    		}
    		
    	
    	 private int getSelection(final String tipeUser){
    	    	int val= 0;
    	          
    	    	if(tipeUser.equals("SUPER ADMIN")){
    	    		val= 1;
    	    	}else if(tipeUser.equals("USER")){
    	    		val= 2;
    	    	}
    	    	
    	    	return val;
    	   }
    	    	
    
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.manag_user, menu);
    		return true;
    	}
    
    	@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_logouts) {
    			
    			Intent i = new Intent(getApplicationContext(),LoginActivity.class);
    			startActivity(i);
    			finish();
    			
    			return true;
    		}
    		return super.onOptionsItemSelected(item);
    	}
    }
    
    
  9. Buka layout dari class ManagUserActivity.java yaitu activity_manag_user.xml dan lakukan modifikasi seperti koding dibawah ini
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/bg" >
        
            <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="@drawable/bg_transparent_white" >
            
           <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="@drawable/bg_transparent_white" >
    
           <Button android:id="@+id/btnSimpan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/spinner1" android:layout_below="@+id/spinner1" android:layout_marginTop="14dp" android:layout_toLeftOf="@+id/textView2" android:background="#00893d" android:onClick="Simpan" android:text="SIMPAN" android:textColor="#FFFFFF" android:textStyle="bold" / >
    
           <EditText android:id="@+id/txtNama" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_alignRight="@+id/textView3" android:layout_below="@+id/textView3" android:ems="10" android:hint="Nama User" >
    
               <requestFocus / >
           </EditText >
    
           <Spinner android:id="@+id/spinner1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:entries="@array/tipeUser" android:layout_below="@+id/textView1" / >
    
           <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="Input Nama User" android:textAppearance="?android:attr/textAppearanceMedium" / >
    
           <EditText android:id="@+id/txtUsername" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignRight="@+id/txtNama" android:layout_below="@+id/TextView01" android:ems="10" android:hint="Username" / >
    
           <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/txtUsername" android:layout_below="@+id/txtNama" android:layout_marginTop="19dp" android:text="Username" android:textAppearance="?android:attr/textAppearanceMedium" / >
    
           <EditText android:id="@+id/txtPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignRight="@+id/txtUsername" android:layout_below="@+id/TextView02" android:inputType="textPassword" android:ems="10" android:hint="Password" / >
    
           <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/txtPassword" android:layout_below="@+id/txtUsername" android:layout_marginTop="22dp" android:text="Password" android:textAppearance="?android:attr/textAppearanceMedium" / >
    
           <EditText android:id="@+id/txtEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignRight="@+id/textView1" android:layout_below="@+id/TextView03" android:inputType="textEmailAddress" android:ems="10" android:hint="Email" / >
    
           <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/txtPassword" android:layout_marginTop="22dp" android:text="Email" android:textAppearance="?android:attr/textAppearanceMedium" / >
    
           <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/TextView03" android:layout_alignRight="@+id/txtPassword" android:layout_below="@+id/txtEmail" android:text="Tipe User" android:textAppearance="?android:attr/textAppearanceMedium" / >
    
           <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/btnSimpan" android:layout_centerHorizontal="true" android:visibility="invisible" android:text="TextView" / >
    
           <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView2" android:layout_alignRight="@+id/spinner1" android:layout_toRightOf="@+id/textView2" android:background="#ffff4444" android:onClick="Kembali" android:text="KEMBALI" android:textColor="#FFFFFF" android:textStyle="bold" / >
        
           </RelativeLayout >
           </RelativeLayout >
    
       </RelativeLayout >
    
  10. Download file bg_grey.xml dan letakkan di res/drawable atau res/drawable-hdpi
  11.  Buat layout xml  baru  dan beri nama list_row_user.xml. layout ini akan menampung data kontak dalam bentuk listview. Beberapa tutorial yang berkaitan dapat di buka pada list di bawah ini.
  12.    <?xml version="1.0" encoding="utf-8"? >
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@drawable/bg_grey" android:padding="0dp" >
    
           <TextView android:id="@+id/tvNamaUser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginLeft="3dp" android:layout_toRightOf="@+id/tvNomor" android:gravity="left|center_vertical" android:text="Nama" android:textColor="#000000" android:textSize="20dp" android:textStyle="bold" / >
    
           <TextView android:id="@+id/tvEmail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/tvNamaUser" android:layout_marginTop="2dip" android:layout_toRightOf="@+id/tvNomor" android:text="email" android:textColor="#000000" android:textSize="15dp" android:textStyle="italic" / >
    
    
           <TextView android:id="@+id/tvTipeUser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/tvEmail" android:layout_marginBottom="5dp" android:layout_marginTop="1dip" android:layout_toRightOf="@+id/tvNomor" android:text="mmm" android:textColor="@android:color/holo_blue_dark" android:gravity="right" android:textSize="15dp" android:paddingRight="10dp" android:textStyle="bold" / >
           <TextView android:id="@+id/tvNomor" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="3dp" android:layout_marginRight="2dp" android:gravity="left" android:text="0" android:textColor="#000000" android:textSize="20dp" android:textStyle="bold" / >
    
       </RelativeLayout >
    
  13. Buat class baru beri nama dengan ListUserAdapter.java. Class ini berfungsi untuk menampilkan listview menggunakan adapter dari ModelUser.
    package com.example.crudsqlite;
    
    import java.util.List;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;
    
    public class ListUserAdapter extends BaseAdapter{
    	
    	/*
    	 Author : www.theheran.com | [email protected]
    	 PIN BBM: 571078A7
    	*/
    	
    	
    	private Activity context;
    	private LayoutInflater inflater;
    	private List   <ModelUser > NasItem;
    	
    	
    
    	public ListUserAdapter(Activity activity, List   <ModelUser > NasItem) {
    		
    		ListUserAdapter.this.context = activity;
    		ListUserAdapter.this.NasItem = NasItem;
    	}
    	
    	@Override
    	public int getCount() {
    		return NasItem.size();
    	}
    
    	@Override
    	public Object getItem(int location) {
    		return NasItem.get(location);
    	}
    
    	@Override
    	public long getItemId(int position) {
    		return position;
    	}
    	
    	@SuppressLint("InflateParams")
    	@Override
    	public View getView(int position, View view, ViewGroup parent) {
    		if (inflater == null)
    			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		
    		if (view == null) view = inflater.inflate(R.layout.list_row_user, null);
    
    		View rowView= inflater.inflate(R.layout.list_row_user, null, true);
    		
    		TextView tvNomor = (TextView) rowView.findViewById(R.id.tvNomor);
    		TextView tvNamaUser = (TextView) rowView.findViewById(R.id.tvNamaUser);
    		TextView tvEmail = (TextView) rowView.findViewById(R.id.tvEmail);
    		TextView tvTipeUser = (TextView) rowView.findViewById(R.id.tvTipeUser);
    		ModelUser m = NasItem.get(position);
    		
    		tvNomor.setText(m.getNo());
    		tvNamaUser.setText(m.getNama());
    		tvEmail.setText(m.getEmail());
    		tvTipeUser.setText(m.getTipeUser());
    		return rowView;
    	}
    }
    
    
  14. Selanjutnya download file XML dibawah ini dan letakkan di folder res/menu
  15. Buka layout activity_main.xml dan lakukan modifikasi koding seperti dibawah ini
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg" tools:context="com.example.crudsqlite.MainActivity" >
        
        
           <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:background="@drawable/bg_transparent_white" >
    
                <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/bg_transparent_white" android:cacheColorHint="#00000000" android:padding="5dp" android:scrollingCache="false" android:layout_above="@+id/button1" / >
             
                <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_toLeftOf="@+id/textView1" android:background="#00893d" android:onClick="Tambah" android:text="TAMBAH" android:textColor="#FFFFFF" android:textStyle="bold" / >
    
                <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="-" / >
    
                <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_toRightOf="@+id/textView1" android:background="@android:color/holo_blue_dark" android:onClick="Reload" android:text="RELOAD" android:textColor="#FFFFFF" android:textStyle="bold" / >
            
           </RelativeLayout >
    
        
    
       </RelativeLayout >
    
    
  16. Buka class MainActivity.java kemudian lakukan modifikasi seperti dibawah ini
    package com.example.crudsqlite;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.AlertDialog.Builder;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.PopupMenu;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
    	private List   <ModelUser > newsList = new ArrayList   <ModelUser >();
    	private ListUserAdapter adapter;
    	ListUserAdapter custum = new ListUserAdapter(null, newsList);
    	ListView listView;
    	public String[] idUserArray;
    	
    	/*
    	 Author : www.theheran.com | [email protected]
    	 PIN BBM: 571078A7
    	*/
    	
    	private long lastPressedTime;
    	private static final int PERIOD = 2000;
    	
    	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	    //Handle the back button
    		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
    	        switch (event.getAction()) {
    	        case KeyEvent.ACTION_DOWN:
    	            if (event.getDownTime() - lastPressedTime    < PERIOD) {
    	            	
    	                finish();
    	            }else {
    	                Toast.makeText(getApplicationContext(), "Tekan 2 kali untuk keluar",Toast.LENGTH_SHORT).show();
    	                lastPressedTime = event.getEventTime();
    	            }
    	            return true;
    	        }
    	    }
    	    return false;
    	    
    	}
    	
    	
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		
    		listView= (ListView)findViewById(R.id.listView);
    		adapter = new ListUserAdapter(MainActivity.this, newsList);
    		listView.setAdapter(adapter);
    		reloadData();
    		
    		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    			@Override
                public void onItemClick(AdapterView   <? > parent, View view,final int position, long id) {
    				
    				  if(idUserArray[position].equals("1")){
    					  PopupMenu popup = new PopupMenu(MainActivity.this, view);
    					  popup.getMenuInflater().inflate(R.menu.popup_super_admin, popup.getMenu());
    					  popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
    							 public boolean onMenuItemClick(MenuItem item) {
    							
    							 if(item.getTitle().equals("Edit Data")){
    								
    								 	Intent i = new Intent(getApplicationContext(),ManagUserActivity.class);
    									i.putExtra("mode", "Edit");
    									i.putExtra("id_user",idUserArray[position]);
    									startActivity(i);
    									finish();
    									
    							 }
    							  return true;
    						}});popup.show();
    						
    				  }else{
    
    					  PopupMenu popup = new PopupMenu(MainActivity.this, view);
    					  popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
    					  popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
    							 public boolean onMenuItemClick(MenuItem item) {
    							
    							 if(item.getTitle().equals("Edit Data")){
    								
    								 	Intent i = new Intent(getApplicationContext(),ManagUserActivity.class);
    									i.putExtra("mode", "Edit");
    									i.putExtra("id_user",idUserArray[position]);
    									startActivity(i);
    									finish();
    									
    									
    							 }else{
    								
    								 Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
    									alertDialog.setTitle("Hapus Data");
    									alertDialog.setMessage("Kamu Yakin Mau Hapus Data ini?");
    									alertDialog.setPositiveButton("YAKIN BANGET",
    											new DialogInterface.OnClickListener() {
    												public void onClick(DialogInterface dialog, int whichButton) {
    													
    													DatabaseHandler db = new DatabaseHandler(getApplicationContext());
    													int status = db.prosesHapus(idUserArray[position]);
    													if(status   >0){
    														Toast.makeText(MainActivity.this, "Data Berhasil Dihapus ",Toast.LENGTH_LONG).show();
    													}else{
    														Toast.makeText(MainActivity.this, "Data Gagal Dihapus ",Toast.LENGTH_LONG).show();
    													}
    													newsList.clear();
    													reloadData();
    													
    												}
    											});
    
    									alertDialog.setNegativeButton("ENGGAK",
    											new DialogInterface.OnClickListener() {
    												public void onClick(DialogInterface dialog, int whichButton) {
    													
    												}
    											});
    									alertDialog.show();
    							 }
    							  return true;
    						}});popup.show();
    				  }
    				  
    				
    				 
    			
                }
            });
    		
    	}
    	
    	public View Tambah(View v){
    			Intent i = new Intent(getApplicationContext(),ManagUserActivity.class);
    			i.putExtra("mode", "Tambah");
    			startActivity(i);
    			finish();
    		return v;
    	}
    	
    	public View Reload(View v){
    			reloadData();
    		return v;
    	}
    
    	private void reloadData(){
            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
            Cursor cursor=db.prosesAmbilSemuaDatauser();
            
            if (cursor.moveToFirst()) {
            	        	
            	idUserArray=new String[cursor.getCount()];
            	int i=0,No=1;
            	newsList.clear();
                do {
                	ModelUser mdUser = new ModelUser();
                	
                	mdUser.setIdUser(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_ID_USER)));
                	mdUser.setNama(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_NAMA)));
                	mdUser.setUsername(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_USERNAME)));
                	mdUser.setPassword(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_PASSWORD)));
                	mdUser.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_EMAIL)));
                	mdUser.setTipeUser(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_TIPE_USER)));
                	mdUser.setNo(String.valueOf(No)+".");
                	
                	idUserArray[i] = mdUser.getIdUser();
                	
                	No++;
                	i++;
                	newsList.add(mdUser);
                } while (cursor.moveToNext());
                
                // Tutup Koneksi
    	        cursor.close();
    	        db.close();
            }
    	}
    	
    	
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.menu_action, menu);
    		return true;
    	}
    
    	@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_reset) {
    			
    			 Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
    				alertDialog.setTitle("Reset Data");
    				alertDialog.setMessage("Kamu Yakin Mau Reset Data?");
    				alertDialog.setPositiveButton("YAKIN BANGET",
    						new DialogInterface.OnClickListener() {
    							public void onClick(DialogInterface dialog, int whichButton) {
    								DatabaseHandler db = new DatabaseHandler(getApplicationContext());
    								db.prosesResetData();
    								reloadData();
    								
    							}
    						});
    
    				alertDialog.setNegativeButton("ENGGAK",
    						new DialogInterface.OnClickListener() {
    							public void onClick(DialogInterface dialog, int whichButton) {
    								
    							}
    						});
    				alertDialog.show();
    				
    			return true;
    		}else{
    			Intent i = new Intent(getApplicationContext(),LoginActivity.class);
    			startActivity(i);
    			finish();
    		}
    		return super.onOptionsItemSelected(item);
    	}
    	
    	
    }
    
    
  17. Buka AndroidManifest.xml dan lakukan modifikasi seperti dibawah ini
       <?xml version="1.0" encoding="utf-8"? >
       <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.crudsqlite" android:versionCode="1" android:versionName="1.0" >
    
           <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" / >
    
           <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light" >
               <activity android:name=".LoginActivity" android:label="Form Login" >
                   <intent-filter >
                       <action android:name="android.intent.action.MAIN" / >
    
                       <category android:name="android.intent.category.LAUNCHER" / >
                   </intent-filter >
               </activity >
               <activity android:name=".ManagUserActivity" android:label="@string/title_activity_manag_user" >
               </activity >
            
                <activity android:name=".MainActivity" android:label="@string/title_activity_main_activity" >
               </activity >
            
           </application >
    
       </manifest >
    
    
  18. Bagi anda yang malas copy paste coding bisa download coding dibawah ini. Sesuaikan dengan letak dari coding tersebut

Src

File res

Class pada package com.example.crudsqlite

File pada folder res/drawable-hdpi atau res/drawable

File pada folder res/layout

File pada folder res/menu

File pada folder res/dimen

Download AndroidManifest.xml

 

SCREENSHOOT

Login

Home

Tambah/Edit Data

Home

List Click

Hapus Data

Action Menu

Reset Data

DOWNLOAD DEMO APK

Comments

comments