Langsung ke konten utama

SQLiteDatabase Part3: Retrieve data from Database Example

Part 3: view all details which are available in database


ScreenShos:






Step 1: Add the following method in DBAdapter

DBAdapter.java

       public Cursor getAllValues(){
              return database.rawQuery("select * from sample_table", null);
       }

Step 2: Create custom xml to inflate to ListView

custom_listview_item.xml

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

    <TextView
        android:id="@+id/custom_textView_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Name :"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:id="@+id/custom_textView_contact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/custom_textView_name"
        android:layout_marginTop="20dp"
        android:text="Contact :"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/custom_textView_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="id :" />

</RelativeLayout>

Step 3: create ViewAllActivity and its respective layout file

activity_view_all.xml

<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"
    tools:context=".ViewAllActivity" >

    <ListView
        android:id="@+id/viewall_listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true">
    </ListView>

</RelativeLayout>

ViewAllActivity.java

packagecom.swamys.databaseexample;

importandroid.app.Activity;
importandroid.database.Cursor;
import android.os.Bundle;
import android.view.View;
importandroid.view.ViewGroup;
importandroid.widget.BaseAdapter;
importandroid.widget.ListView;
importandroid.widget.TextView;

importcom.swamys.database.dbadapter.DBAdapter;

public class ViewAllActivity extends Activity {

       DBAdapter dbAdapter;
       ListView listView;
       Cursor cursor;

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

              listView = (ListView) findViewById(R.id.viewall_listView);
              dbAdapter = newDBAdapter(getApplicationContext());
              cursor = dbAdapter.getAllValues();
              cursor.moveToFirst();
              MyAdapter adapter = new MyAdapter();
              listView.setAdapter(adapter);
       }

       private class MyAdapter extends BaseAdapter {

              @Override
              public int getCount() {
                     return cursor.getCount();
              }

              @Override
              public Object getItem(int position) {
                     return null;
              }

              @Override
              public long getItemId(int position) {
                     return 0;
              }

              @Override
              public View getView(int position, View convertView, ViewGroup parent) {

                     cursor.moveToPosition(position);
                     View view = getLayoutInflater().inflate(
                                  R.layout.custom_listview_item, null);
                     TextView textView_name = (TextView) view
                                  .findViewById(R.id.custom_textView_name);
                     TextView textView_contact = (TextView) view
                                  .findViewById(R.id.custom_textView_contact);
                     TextView textView_id = (TextView) view
                                  .findViewById(R.id.custom_textView_id);
                     textView_id.setText("" + cursor.getInt(0));
                     textView_name.setText(cursor.getString(1));
                     textView_contact.setText(cursor.getString(2));

                     return view;
              }
       }

       @Override
       protected void onDestroy() {
              super.onDestroy();
              dbAdapter.closeConnection();
       }

}

Step 4: create a button in main Layout add the following code

activity_main.xml

    <Button
        android:id="@+id/main_button_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/main_button_insert"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="View All"
        android:onClick="viewAll" />

Step 5: add the view button Click method in MainActivity

MainActivity.java

public void viewAll(View view){
              Intent intent = new Intent(getApplicationContext(),ViewAllActivity.class);
              startActivity(intent);
             
       }

Step 6: Register ViewAllActivity in manifest

Manifest.xml

<?xml version="1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.swamys.databaseexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.swamys.databaseexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name="com.swamys.databaseexample.InsertActivity"
            android:label="@string/title_activity_insert" >
        </activity>
        <activity
            android:name="com.swamys.databaseexample.ViewAllActivity"
            android:label="@string/title_activity_view_all">
        </activity>
    </application>

</manifest>






Komentar

Postingan populer dari blog ini

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s...

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail...

How to Perform Rest API using Retrofit in Android (Part-1)

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley. This post is Split into Two Parts. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations. Second Part Contains how to perform Retrofit Operations in Android. Architecture of Retrofit Web Service We need 3 Things for Complete Retrofit Architecture. RestAdapter An Interface with all networking methods and parameters. Getter Setter Class to save data coming from server. Project Structure: Create MySQL DataBase and PHP Scripts. Following image shows my database structure. PHP Scripts: I created db_config.php which contains the script to connect DB. <?php /** * Database config variables */ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "retrofit_exampl...