Sqlite ile Temel Veritabanı İşlemleri

Bu yazımda Sqlite ile temel veritabanı işlemlerini, örnek bir uygulama ile anlatacağım.

"StandartSqlite" adlı uygulamamız, bir seçim algoritması dikkate alınarak geliştirilmiştir.
Adayların kayıt işlemleri için "myDatabase" adlı bir veritabanı ve "adaylar" adlı bir veritabanı tablosu oluşturulmuştur.


Uygulamada;
-Yeni aday kaydı (Insert),
- Aday kayıtlarını görüntüleme (Select),
- Detaylı aday kaydı görüntüleme,
- Aday sorgulama,
- Aday kaydı güncelleme (Update) ve
- Aday kaydı silme (Delete) işlemleri yapılmaktadır.

1- Ana Menü kaynak kodları ve arayüzü

MainActivity.java

Temel Sqlite İşlemleri Ana Menü
package com.blog_yeniyaz.temelsqlite;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity
{
    private final myDBClass myDb = new myDBClass(this);
    private static final String TABLE_ADAY = "adaylar";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /* ana menü başlığı */
        TextView caption = (TextView) findViewById(R.id.textView1);
        caption.setText(getString(R.string.app_name) + "\n" + getString(R.string.anamenu));

        final Button kayit_ekleye_git = (Button) findViewById(R.id.btnInsert);

        kayit_ekleye_git.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //    Intent newActivity = new Intent(MainActivity.this, AddActivity.class);
                //   startActivity(newActivity);
                startActivity(new Intent("com.blog_yeniyaz.temelsqlite.KAYIT_EKLE"));
            }
        });

        final Button kayit_goster = (Button) findViewById(R.id.btnShow_Time);

        kayit_goster.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //Intent newActivity = new Intent(MainActivity.this,ShowActivity.class);
                //   startActivity(newActivity);
                startActivity(new Intent("com.blog_yeniyaz.temelsqlite.KAYIT_GOSTER"));
            }
        });

        final Button kayit_guncelle = (Button) findViewById(R.id.btnDegistir);

        kayit_guncelle.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // Open Form ListUpdate
                Intent newActivity = new Intent(MainActivity.this, ListUpdateActivity.class);
                startActivity(newActivity);
            }
        });

        Button kayit_sil = (Button) findViewById(R.id.btnKayit_Sil);

        kayit_sil.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent newActivity = new Intent(MainActivity.this, ListDeleteActivity.class);
                startActivity(newActivity);
            }
        });

        final Button program_kapat = (Button) findViewById(R.id.btnKapat);

        program_kapat.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Temel Sqlite İşlemleri");
                builder.setMessage("Uygulamadan çıkmak istiyor musunuz?");

                builder.setPositiveButton("EVET", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);

                        //..MainActivity.this.finish();
                        System.exit(0);
                        //android.os.Process.killProcess(android.os.Process.myPid());
                        //MainActivity.super.onDestroy();

                    }
                });
                builder.setNegativeButton("HAYIR", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();             }
        });

        /* Tablo boş ise kayıt yap */
        SQLiteDatabase insData = myDb.getReadableDatabase();
        String countQuery = "SELECT * FROM " + TABLE_ADAY + ";";

        assert insData != null;
        Cursor KayitKontrol = insData.rawQuery(countQuery, null);
        if(KayitKontrol.getCount() <= 0)
        {
            myDb.InsertData("1","1001","AdayAdi1 Soyadi1","9350101");
            myDb.InsertData("2","1002","AdayAdi2 Soyadi2","9350102");
            myDb.InsertData("3","1003","AdayAdı3 Soyadı3","9350103");
            myDb.InsertData("4","1004","AdayAdı4 Soyadı4","9350104");
            myDb.InsertData("5","1005","AdayAdı5 Soyadı5","9350105");
            myDb.InsertData("6","1006","AdayAdı6 Soyadı6","9350106");
            myDb.InsertData("7","1007","AdayAdı7 Soyadı7","9350107");

            KayitKontrol.close();
            myDb.close();
            Log.d("InsertData", "Adaylar basari ile kayit edildi.");
        }
        else
        {
            KayitKontrol.close();
            myDb.close();
            Log.v("InsertData", "Kayit yapilmis fonksiyon cagrilmadi...");
        }
    }/* onCreate(Bundle */

} /* first */

myDBClass.java

package com.blog_yeniyaz.temelsqlite;

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

public class myDBClass extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "mydatabase";
    private static final String TABLE_ADAY = "adaylar";

    public myDBClass(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        boolean dbExist = checkDatabase();

        if(!dbExist)
        {
            db.execSQL("CREATE TABLE " + TABLE_ADAY +
                      " (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
                      " AdayID INTEGER," +
                      " Name TEXT(40)," +
                      " Tel TEXT(10));");

            Log.d("CREATE TABLE ", "Tablo basari ile olusturuldu...");
        }
        else
        {
            SQLiteDatabase.openDatabase(DATABASE_NAME, null, SQLiteDatabase.OPEN_READWRITE);
            Log.d("OPEN TABLE ", "Tablo basari ile acildi...");
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ADAY);
        onCreate(db);
    }

    private boolean checkDatabase()
    {
        SQLiteDatabase checkDB = null;

        try
        {
            checkDB = SQLiteDatabase.openDatabase(DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);
            Log.d("OPEN DATABASE ", "Database islemler icin hazir..");
        }
        catch(SQLiteException e)
        {
            //exit
        }

        return checkDB != null;
    }

    //örnek aday kayıt girişi
  public long InsertData(String strID, String strAdayID, String strName, String strTel)
    {
        try
        {
            SQLiteDatabase db;
            db = this.getWritableDatabase(); 

            ContentValues value_data = new ContentValues();
            value_data.put("ID", strID);
            value_data.put("AdayID", strAdayID);
            value_data.put("Name", strName);
            value_data.put("Tel", strTel);

            assert db != null;
            long rows = db.insert(TABLE_ADAY, null, value_data);

            db.close();
            return rows; // return inserted.
        }
        catch (Exception e)
        {
            return -1;
        }
    }/* InsertData() */

} /* first */

2- Yeni Aday Kaydı Ekleme kaynak kodları ve arayüzü

AddActivity.java

Sqlite ile Temel Veritabanı İşlemleri-Kayıt Ekle

package com.blog_yeniyaz.temelsqlite;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AddActivity extends Activity
{
    final myDBClass myDb = new myDBClass(this);
    private static final String TABLE_ADAY = "adaylar";

    private EditText tAdayID;
    private EditText tName;
    private EditText tTel;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        final Button save = (Button) findViewById(R.id.btnSave);

        save.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try
                {
                    SaveData();
                    tAdayID.requestFocus();
                }
                finally
                {
                    myDb.close();
                }
            }
        });

        /* ANA MENÜ ye dön*/
        final Button geridon = (Button) findViewById(R.id.btnAnamenu);

        geridon.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //Intent newActivity = new Intent(AddActivity.this, MainActivity.class);
                //startActivity(newActivity);
                AddActivity.this.finish();
            }
        });

    } /* onCreate(Bundle */

    @SuppressWarnings("ConstantConditions")
    public boolean SaveData()
    {
        tAdayID = (EditText) findViewById(R.id.txtAdayID);
        tName = (EditText) findViewById(R.id.txtName);
        tTel = (EditText) findViewById(R.id.txtTel);

        // Dialog
        final AlertDialog.Builder adb = new AlertDialog.Builder(this);
        AlertDialog ad = adb.create();

        // Check AdayID
        if(tAdayID.getText().toString().length() == 0)
        {
            ad.setMessage(getString(R.string.aday_no));
            ad.show();
            tAdayID.requestFocus();
            return false;
        }

        // Check Name
        if(tName.getText().toString().length() == 0)
        {
            ad.setMessage("Lutfen Aday Adi giriniz ");
            ad.show();
            tName.requestFocus();
            return false;
        }

        // Check Tel
        if(tTel.getText().toString().length() == 0)
        {
            ad.setMessage("Lutfen Aday Tel.No. giriniz ");
            ad.show();
            tTel.requestFocus();
            return false;
        }

        // Check Data (AdayID exists)
        String arrData[] = SelectData(tAdayID.getText().toString());
        if(arrData != null)
        {
            ad.setMessage("Bu Aday daha once kayit edilmis..");
            ad.show();
            tAdayID.requestFocus();
            return false;
        }

        InsertData(tAdayID.getText().toString(), tName.getText().toString(), tTel.getText().toString());
        return true;
    }

    private void InsertData(String strAdayID, String strName, String strTel)
    {
        final AlertDialog.Builder mesajVer = new AlertDialog.Builder(this);
        AlertDialog mes_goster = mesajVer.create();

        ContentValues value_Data = new ContentValues();
        value_Data.put("AdayID", strAdayID);
        value_Data.put("Name", strName);
        value_Data.put("Tel", strTel);

        try
        {
            SQLiteDatabase db = myDb.getWritableDatabase();
            assert db != null;
            db.insertOrThrow(TABLE_ADAY, null, value_Data);

            //getString doğrudan işlem_ekle yerine de yazılabilir
            String islem_ekle = getString(R.string.kayit_ekle);

            mes_goster.setTitle("Yeni Aday Kaydi");
            mes_goster.setMessage(strName + " adli adayin \n" + islem_ekle);
            mes_goster.show();

            tAdayID.setText("");
            tName.setText("");
            tTel.setText("");
        }
        catch (Exception e)
        {
            mes_goster.setTitle("Yeni Aday Kaydi");
            mes_goster.setMessage("Hata : Aday Kaydi yapılamadı.\n" + "Yeniden deneyiniz...");
            mes_goster.show();
        }
    }

    // Select Data ** Daha önce kayıt yapılmış mı ? ***
    public String[] SelectData(String strAdayID)
    {
        try
        {
            String curData[] = null;
            SQLiteDatabase db = myDb.getReadableDatabase();

            String strSQL = "SELECT * FROM " + TABLE_ADAY + " WHERE AdayID = " + strAdayID + ";";

            assert db != null;
            Cursor cursor = db.rawQuery(strSQL, null);

            if(cursor != null)
            {
                if (cursor.moveToFirst())
                {
                    curData = new String[cursor.getColumnCount()];
                    curData[0] = cursor.getString(0); // ID
                    curData[1] = cursor.getString(1); // AdayID
                    curData[2] = cursor.getString(2); // Name
                    curData[3] = cursor.getString(3); // Tel
                }
            }

            myDb.close();
            db.close();
            return curData;
        }
        catch (Exception e)
        {
            return null;
        }
    }

} /* first */

3- Aday Kayıtlarını Görüntüleme kaynak kodları ve arayüzü
ShowActivity.java



package com.blog_yeniyaz.temelsqlite;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;

public class ShowActivity extends Activity
{
    final myDBClass myDb = new myDBClass(this);
    private static final String TABLE_ADAY = "adaylar";

    public ArrayList> AdayListe;

    final Context con_text = this;
    public Button listeYenile;
    public EditText Kriter;
    private Boolean AramaYapildimi = false;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);

        Kriter = (EditText) findViewById(R.id.edShow_list_search);
        AdayListe = SelectAllData();

        ListView listeGoster = (ListView)findViewById(R.id.listView1);

        SimpleAdapter firstAdaptor;
        firstAdaptor = new SimpleAdapter(ShowActivity.this, AdayListe, R.layout.activity_column,
                new String[] {"AdayID", "Name", "Tel"}, new int[] {R.id.ColMemberID, R.id.ColName, R.id.ColTel});
        listeGoster.setAdapter(firstAdaptor);
        registerForContextMenu(listeGoster);

        listeGoster.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id)
            {
                // Show on new activity
                Intent newActivity = new Intent(ShowActivity.this, DetailActivity.class);

                //newActivity.putExtra("MemID", AdayListe.get(position).get("AdayID").toString());
                newActivity.putExtra("MemID", AdayListe.get(position).get("AdayID"));
                startActivity(newActivity);
            }
        });

        //ANA MENÜ ye DÖN
        final Button cancel = (Button) findViewById(R.id.btnCancel);
        cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent newActivity = new Intent(ShowActivity.this, MainActivity.class);
                startActivity(newActivity);
                //ShowActivity.this.finish();
            }
        });

        final Button AramaBaslat = (Button) findViewById(R.id.btnShow_list_search);

        AramaBaslat.setOnClickListener(new View.OnClickListener()
        {
            @SuppressWarnings("ConstantConditions")
            @Override
            public void onClick(View v)
            {
                // Check AdayID
                if(Kriter.getText().toString().length() == 0)
                {
                    final AlertDialog.Builder adb = new AlertDialog.Builder(con_text);
                    AlertDialog ad = adb.create();
                    ad.setTitle("Arama Yap");
                    // ad.setMessage(getString(R.string.aday_no));
                    ad.setMessage("Aranacak Kriteri girmediniz");
                    ad.show();
                    Kriter.requestFocus();
                }

                AramaYapildimi = true;
                listeYenile.setEnabled(true);
                ShowListData();

            }
        });

        listeYenile = (Button) findViewById(R.id.btnShowYenile);
        listeYenile.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //Intent intent = new Intent(ShowActivity.this, Result.class);
                //startActivity(intent);
                listeYenile.setEnabled(false);
                startActivity(new Intent("com.blog_yeniyaz.temelsqlite.KAYIT_GOSTER"));
            }
        });

    }  /* onCreate(Bundle */

    public void ShowListData()
    {
        // AramaYapildimi = true;
        AdayListe = SelectAllData();

        ListView listeView = (ListView)findViewById(R.id.listView1);
        SimpleAdapter sAdaptor;
        sAdaptor = new SimpleAdapter(ShowActivity.this, AdayListe, R.layout.activity_column,
                   new String[] {"AdayID", "Name", "Tel"}, new int[] {R.id.ColMemberID, R.id.ColName, R.id.ColTel});
        listeView.setAdapter(sAdaptor);
        registerForContextMenu(listeView);
    }

    // Show All Data
    @SuppressWarnings("ConstantConditions")
    public ArrayList> SelectAllData()
    {
        try
        {
            ArrayList> MyArrList = new ArrayList>();
            HashMap map;

            SQLiteDatabase db = myDb.getReadableDatabase(); // Read Data
            String strSQL;

            String Bul = Kriter.getText().toString();

            if (AramaYapildimi.equals(Boolean.TRUE))
            {
                /* Eşit olanları listeler
                strSQL = "SELECT  * FROM " + TABLE_ADAY + " WHERE AdayID = '" + Bul + "'" +
                         " OR Name = '" + Bul + "' OR Tel = '" + Bul + "';";
                */

                // LIKE ile arama
                strSQL = "SELECT * FROM " + TABLE_ADAY +
                         " WHERE AdayID LIKE '%" + Bul + "%'" +
                         " OR Name LIKE '%" + Bul + "%'" +
                         " OR Tel LIKE '%" + Bul + "%' ORDER BY AdayID, Name;";
            }
            else
            {
                strSQL = "SELECT * FROM " + TABLE_ADAY + " ORDER BY AdayID, Name";
            }

            assert db != null;
            cursor = db.rawQuery(strSQL, null);

            if(cursor != null)
            {
                if (cursor.moveToFirst())
                {
                    do
                    {
                        map = new HashMap();
                        map.put("AdayID", cursor.getString(1));
                        map.put("Name", cursor.getString(2));
                        map.put("Tel", cursor.getString(3));
                        MyArrList.add(map);
                    } while (cursor.moveToNext());
                }
            }

            myDb.close();
            db.close();
            return MyArrList;
        }
        catch (Exception e)
        {
            return null;
        }
    } /* ArrayList */

} /* first */

4- Detaylı Aday kaydı Görüntüleme kaynak kodları ve arayüzü
DetailActivity.java


package com.blog_yeniyaz.temelsqlite;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class DetailActivity extends Activity
{
    final myDBClass myDb = new myDBClass(this);
    private static final String TABLE_ADAY = "adaylar";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        // Read var from Intent
        Intent intent = getIntent();
        String MemID = intent.getStringExtra("MemID");

        // Show Data
        ShowData(MemID);

        // btnCancel (Cancel)
        final Button cancel = (Button) findViewById(R.id.btnCancel);
        cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //Intent newActivity = new Intent(DetailActivity.this,ShowActivity.class);
                //startActivity(newActivity);
                DetailActivity.this.finish();
            }
        });

    }

    public void ShowData(String MemID)
    {
        // txtAdayID, txtName, txtTel
        final TextView tAdayID = (TextView) findViewById(R.id.txtAdayID);
        final TextView tName = (TextView) findViewById(R.id.txtName);
        final TextView tTel = (TextView) findViewById(R.id.txtTel);


        // Show Data
        // String arrData[] = myDb.SelectData(MemID);
        String arrData[] = SelectData(MemID);
        if(arrData != null)
        {
            tAdayID.setText(arrData[1]);
            tName.setText(arrData[2]);
            tTel.setText(arrData[3]);
        }
    }

    // Select Data
    public String[] SelectData(String strAdayID)
    {
        try
        {
            String select_Data[] = null;
            SQLiteDatabase db;
            db = myDb.getReadableDatabase();

            String strSQL = "SELECT * FROM " + TABLE_ADAY + " WHERE AdayID = " + strAdayID + ";";

            assert db != null;
            Cursor cursor = db.rawQuery(strSQL, null);
            if(cursor != null)
            {
                if (cursor.moveToFirst())
                {
                    select_Data = new String[cursor.getColumnCount()];
                    select_Data[0] = cursor.getString(0); // ID
                    select_Data[1] = cursor.getString(1); // AdayID
                    select_Data[2] = cursor.getString(2); // Name
                    select_Data[3] = cursor.getString(3); // Tel
                }
            }

            myDb.close();
            db.close();
            return select_Data;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.detail, menu);
        return true;
    }
}

5- Aday Kaydı Güncelleme kaynak kodları ve arayüzü
ListUpdateActivity.java (kaydı değiştirilecek adayların listesi)




package com.blog_yeniyaz.temelsqlite;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;

public class ListUpdateActivity extends Activity
{
    final myDBClass myDb = new myDBClass(this);
    private static final String TABLE_ADAY = "adaylar";

    public ArrayList> AdayListe;

    final Context con_text = this;
    public Button listeYenile;
    public EditText Kriter;
    private Boolean AramaYapildimi = false;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_update);

        Kriter = (EditText) findViewById(R.id.edUpdate_list_search);

        AdayListe = SelectAllData();

        ListView listeGoster = (ListView)findViewById(R.id.listView1);

        SimpleAdapter sAdap;
        sAdap = new SimpleAdapter(ListUpdateActivity.this, AdayListe, R.layout.activity_column,
                new String[] {"AdayID", "Name", "Tel"}, new int[] {R.id.ColMemberID, R.id.ColName, R.id.ColTel});
        listeGoster.setAdapter(sAdap);

        listeGoster.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id)
            {
                Intent newActivity = new Intent(ListUpdateActivity.this, UpdateActivity.class);

                //newActivity.putExtra("MemID", AdayListe.get(position).get("ID").toString());
                newActivity.putExtra("MemID", AdayListe.get(position).get("ID"));
                startActivity(newActivity);
            }
        });

        final Button cancel = (Button) findViewById(R.id.btnCancel);

        cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent newActivity = new Intent(ListUpdateActivity.this, MainActivity.class);
                startActivity(newActivity);
                //ListUpdateActivity.this.finish();
            }
        });

        final Button AramaBaslat = (Button) findViewById(R.id.btnUpdate_list_search);

        AramaBaslat.setOnClickListener(new View.OnClickListener()
        {
            @SuppressWarnings("ConstantConditions")
            @Override
            public void onClick(View v)
            {
                // Check AdayID
                if(Kriter.getText().length() == 0)
                {
                    final AlertDialog.Builder adb = new AlertDialog.Builder(con_text);
                    AlertDialog ad = adb.create();
                    ad.setTitle("Arama Yap");
                    // ad.setMessage(getString(R.string.aday_no));
                    ad.setMessage("Aranacak Kriteri girmediniz");
                    ad.show();
                    Kriter.requestFocus();
                }

                AramaYapildimi = true;
                listeYenile.setEnabled(true);
                ShowListData();
            }
        });

        listeYenile = (Button) findViewById(R.id.btnUpdateYenile);
        listeYenile.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                listeYenile.setEnabled(false);
                startActivity(new Intent("com.blog_yeniyaz.temelsqlite.KAYIT_UPDATE"));
            }
        });

    } /* onCreate(Bundle */

    public void ShowListData()
    {
        // AramaYapildimi = true;
        AdayListe = SelectAllData();

        ListView listeView = (ListView)findViewById(R.id.listView1);
        SimpleAdapter sAdaptor;
        sAdaptor = new SimpleAdapter(ListUpdateActivity.this, AdayListe, R.layout.activity_column,
                   new String[] {"AdayID", "Name", "Tel"}, new int[] {R.id.ColMemberID, R.id.ColName, R.id.ColTel});
        listeView.setAdapter(sAdaptor);
        registerForContextMenu(listeView);
    }

    // Show All Data
    @SuppressWarnings("ConstantConditions")
    public ArrayList> SelectAllData()
    {
        try
        {
            ArrayList> MyArrList = new ArrayList>();
            HashMap map;

            SQLiteDatabase db = myDb.getReadableDatabase(); // Read Data
            String strSQL;

            String Bul = Kriter.getText().toString();

            // if (AramaYapildimi == true)
            if (AramaYapildimi.equals(Boolean.TRUE))
            {
                // LIKE ile arama
                strSQL = "SELECT * FROM " + TABLE_ADAY +
                        " WHERE AdayID LIKE '%" + Bul + "%'" +
                        " OR Name LIKE '%" + Bul + "%'" +
                        " OR Tel LIKE '%" + Bul + "%' ORDER BY Name;";
            }
            else
            {
                strSQL = "SELECT * FROM " + TABLE_ADAY + " ORDER BY AdayID, Name;";
            }

            assert db != null;
            cursor = db.rawQuery(strSQL, null);

            if(cursor != null)
            {
                if (cursor.moveToFirst())
                {
                    do
                    {
                        map = new HashMap();
                        map.put("ID", cursor.getString(0));
                        map.put("AdayID", cursor.getString(1));
                        map.put("Name", cursor.getString(2));
                        map.put("Tel", cursor.getString(3));
                        MyArrList.add(map);
                    } while (cursor.moveToNext());
                }
            }

            cursor.close();
            db.close();
            return MyArrList;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}

UpdateActivity.java(kaydı değiştirilecek adayın seçimi)


package com.blog_yeniyaz.temelsqlite;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class UpdateActivity extends Activity
{
    final myDBClass myDb = new myDBClass(this);
    private static final String TABLE_ADAY = "adaylar";

    private EditText tAdayID;
    private EditText tName;
    private EditText tTel;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        // Read data from Intent
        Intent intent= getIntent();
        final String MemID = intent.getStringExtra("MemID");

        // Show Data
        ShowData(MemID);

        // btnSave (Save)
        final Button save = (Button) findViewById(R.id.btnSave);

        save.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(SaveData(MemID))
                {
                    Intent new_activity = new Intent(UpdateActivity.this, ListUpdateActivity.class);
                    startActivity(new_activity);
                }

            }
        });

        //Geri dön
        final Button cancel = (Button) findViewById(R.id.btnCancel);

        cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent new_activity = new Intent(UpdateActivity.this, MainActivity.class);
                startActivity(new_activity);
                //UpdateActivity.this.finish();
            }
        });

    } /* onCreate(Bundle */


    public void ShowData(String MemID)
    {
        EditText tID = (EditText) findViewById(R.id.txtId);
        tAdayID = (EditText) findViewById(R.id.txtAdayID);
        tName = (EditText) findViewById(R.id.txtName);
        tTel = (EditText) findViewById(R.id.txtTel);

        // Show Data
        // String arrData[] = myDb.SelectData(MemID);
        String arrData[] = SelectData(MemID);
        if(arrData != null)
        {
            tID.setText(arrData[0]);
            tAdayID.setText(arrData[1]);
            tName.setText(arrData[2]);
            tTel.setText(arrData[3]);
        }
    }

    // Select Data
    public String[] SelectData(String strID)
    {
        try
        {
            String curData[] = null;
            SQLiteDatabase db = myDb.getReadableDatabase(); // Read Data
            String strSQL;

            //Cursor cursor = db.query(TABLE_ADAY, new String[] { "*" }, "ID=?",
                   // new String[] { String.valueOf(strID) }, null, null, null, null);

            strSQL = "SELECT * FROM " + TABLE_ADAY + " WHERE ID = " + strID + ";";

            assert db != null;
            Cursor cursor = db.rawQuery(strSQL, null);

            if(cursor != null)
            {
                if (cursor.moveToFirst())
                {
                    curData = new String[cursor.getColumnCount()];
                    curData[0] = cursor.getString(0); // ID
                    curData[1] = cursor.getString(1); // AdayID
                    curData[2] = cursor.getString(2); // Name
                    curData[3] = cursor.getString(3); // Tel
                }
            }

            myDb.close();
            db.close();
            return curData;
        }
        catch (Exception e)
        {
            return null;
        }
    } /* String[] SelectData */

    @SuppressWarnings("ConstantConditions")
    public boolean SaveData(String MemID)
    {
        tAdayID = (EditText) findViewById(R.id.txtAdayID);
        tName = (EditText) findViewById(R.id.txtName);
        tTel = (EditText) findViewById(R.id.txtTel);

        // Dialog
        final AlertDialog.Builder adb = new AlertDialog.Builder(this);
        AlertDialog ad = adb.create();

        if(tAdayID.getText().length() == 0)
        {
            ad.setMessage(getString(R.string.aday_no));
            ad.show();
            tAdayID.requestFocus();
            return false;
        }

        if(tName.getText().length() == 0)
        {
            ad.setMessage("Lutfen Aday Adi giriniz ");
            ad.show();
            tName.requestFocus();
            return false;
        }

        if(tTel.getText().length() == 0)
        {
            ad.setMessage("Lutfen Aday Tel.No. giriniz ");
            ad.show();
            tTel.requestFocus();
            return false;
        }

        // Save Data
        UpdateData(MemID, tAdayID.getText().toString(), tName.getText().toString(), tTel.getText().toString());
        ad.setMessage(getString(R.string.kayit_degisti));
        ad.show();
        return true;
    } /* boolean SaveData */

    //Update Data
    public long UpdateData(String strID, String strAdayID, String strName, String strTel)
    {
        try
        {
            SQLiteDatabase db = myDb.getReadableDatabase();

            ContentValues Value_Data = new ContentValues();
            Value_Data.put("AdayID", strAdayID);
            Value_Data.put("Name", strName);
            Value_Data.put("Tel", strTel);

            assert db != null;
            long rows = db.update(TABLE_ADAY, Value_Data, " ID = ?",
                                   new String[] { String.valueOf(strID) });
            myDb.close();
            db.close();
            return rows; // return updated.
        }
        catch (Exception e)
        {
            return -1;
        }
    }

}/* first */

6- Aday Kaydı Silme kaynak kodları ve arayüzü

ListDeleteActivity.java


package com.blog_yeniyaz.temelsqlite;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class ListDeleteActivity extends Activity
{
    private final myDBClass myDb = new myDBClass(this);
    private static final String TABLE_ADAY = "adaylar";

    public ArrayList> AdayListe;

    final Context con_text = this;
    public Button listeYenile;
    public EditText Kriter;
    private Boolean AramaYapildimi = false;
    String MemID;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_delete);

        Kriter = (EditText) findViewById(R.id.edDelete_list_search);

        final Button geri_don = (Button) findViewById(R.id.btnCancel);

        geri_don.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                /* force close: Emülatörde çalışıyor, ancak USB Cihazda çalışmıyor */
                //System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());
                ListDeleteActivity.super.onDestroy();

                /* Ana Menü */
                Intent newActivity = new Intent(ListDeleteActivity.this, MainActivity.class);
                startActivity(newActivity);            }
        });

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set title
        alertDialogBuilder.setTitle(getString(R.string.kayit_sil_baslik));
        // set dialog message
        alertDialogBuilder
                .setMessage(getString(R.string.kayit_sil_soru))
                .setCancelable(false)
                .setIcon(R.drawable.kayit_sil)
                .setPositiveButton("Evet", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        long flag = KayitSil(MemID);
                        if (flag > 0)
                        {
                            Toast.makeText(ListDeleteActivity.this,
                                    getString(R.string.kayit_silindi_mesaj),
                                    Toast.LENGTH_LONG).show();
                        }
                        else
                        {
                            Toast.makeText(ListDeleteActivity.this,
                                    getString(R.string.kayit_silinmedi_mes1),
                                    Toast.LENGTH_LONG).show();
                            //getString(R.string.kayit_silinmedi_mes1) + "\n" +
                                   // getString(R.string.kayit_silinmedi_mes2),
                        }
                        ShowListData();//ListViewi yenile
                    }
                })
                .setNegativeButton(getString(R.string.kayit_sil_cevap), new DialogInterface.OnClickListener()
                {
                    //hayır ise
                    public void onClick(DialogInterface dialog, int id)
                    {
                        dialog.cancel();
                    }
                });

        // create alert dialog
        final AlertDialog alertDialog = alertDialogBuilder.create();
        AdayListe = SelectAllData();

        ListView listeGoster =(ListView)findViewById(R.id.listView1);

        SimpleAdapter sAdap;
        sAdap = new SimpleAdapter(ListDeleteActivity.this,AdayListe, R.layout.activity_column,
                new String[] {"AdayID", "Name", "Tel"}, new int[] {R.id.ColMemberID, R.id.ColName, R.id.ColTel});
        listeGoster.setAdapter(sAdap);
        registerForContextMenu(listeGoster);

        listeGoster.setClickable(true);
        listeGoster.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView arg0, View arg1, int position, long id)
            {
                //MemID = AdayListe.get(position).get("ID").toString();
                MemID = AdayListe.get(position).get("ID");
                alertDialog.show();
            }
        });

        final Button AramaBaslat = (Button) findViewById(R.id.btnDelete_list_search);

        AramaBaslat.setOnClickListener(new View.OnClickListener()
        {
            @SuppressWarnings("ConstantConditions")
            @Override
            public void onClick(View v)
            {
                // Check AdayID
                if(Kriter.getText().length() == 0)
                {
                    final AlertDialog.Builder adb = new AlertDialog.Builder(con_text);
                    AlertDialog ad = adb.create();
                    ad.setTitle("Arama Yap");
                    // ad.setMessage(getString(R.string.aday_no));
                    ad.setMessage("Aranacak Kriteri girmediniz");
                    ad.show();
                    Kriter.requestFocus();
                }

                AramaYapildimi = true;
                listeYenile.setEnabled(true);
                ShowListData();
            }
        });

        listeYenile = (Button) findViewById(R.id.btnDeleteYenile);
        listeYenile.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent("com.blog_yeniyaz.temelsqlite.KAYIT_SIL"));
                listeYenile.setEnabled(false);
            }
        });

    } /* onCreate(Bundle */

    public long KayitSil(String strAdayID)
    {
        try
        {
            SQLiteDatabase db = myDb.getReadableDatabase();
            assert db != null;
            long rows = db.delete(TABLE_ADAY, "ID = ?",
                        new String[] { String.valueOf(strAdayID) });

            db.close();
            return rows; // return deleted.
        }
        catch (Exception e)
        {
            return -1;
        }
    }

    // Show List data
    public void ShowListData()
    {
        AdayListe = SelectAllData();
        ListView listeView = (ListView)findViewById(R.id.listView1);
        SimpleAdapter sAdaptor;

        sAdaptor = new SimpleAdapter(ListDeleteActivity.this, AdayListe, R.layout.activity_column,
                   new String[] {"AdayID", "Name", "Tel"}, new int[] {R.id.ColMemberID, R.id.ColName, R.id.ColTel});
        listeView.setAdapter(sAdaptor);
        registerForContextMenu(listeView);
    }

    @SuppressWarnings("ConstantConditions")
    public ArrayList> SelectAllData()
    {
        try
        {
            ArrayList> MyArrList = new ArrayList>();
            HashMap map;

            SQLiteDatabase db = myDb.getReadableDatabase();
            String strSQL;

            String Bul = Kriter.getText().toString();

            // if (AramaYapildimi == true)
            if (AramaYapildimi.equals(Boolean.TRUE))
            {
                // LIKE ile arama
                strSQL = "SELECT * FROM " + TABLE_ADAY +
                         " WHERE AdayID LIKE '%" + Bul + "%'" +
                         " OR Name LIKE '%" + Bul + "%'" +
                         " OR Tel LIKE '%" + Bul + "%' ORDER BY AdayID, Name;";
            }
            else
            {
                strSQL = "SELECT * FROM " + TABLE_ADAY + " ORDER BY AdayID, Name";
            }

            assert db != null;
            Cursor cursor = db.rawQuery(strSQL, null);

            if(cursor != null)
            {
                if (cursor.moveToFirst())
                {
                    do
                    {
                        map = new HashMap();
                        map.put("ID", cursor.getString(0));
                        map.put("AdayID", cursor.getString(1));
                        map.put("Name", cursor.getString(2));
                        map.put("Tel", cursor.getString(3));
                        MyArrList.add(map);
                    } while (cursor.moveToNext());
                }
            }

            db.close();
            return MyArrList;
        }
        catch (Exception e)
        {
            return null;
        }
    } /* ArrayList */

} /* first */



İyi bir geliştirici olabilmek için, iyi bir veritabanı yöneticisi olmak artık bilgi ve iletişim teknolojileri dünyasının olmazsa olmazlarından birisidir.
Android'in Sqlite veritabanını tercih etmesi nedeni ile uygulamamızı Sqlite kullanarak geliştirdim.

Ancak ileride burada Mysql veritabanını kullanarak Server-Client uygulama örneklerine de yer vereceğim.

Uygulama, seçime katılan herhangi bir partiye yönelik olarak, adayların resimleri ve aday tanıtım bilgileride dahil edilerek geliştirilebilir.

Uygulamanın Kaynak Kodlarını buradan indirebilirsiniz.

Kolay gelsin.