mercredi 19 août 2015

Display single record from ListView / ListAdapter from sql database

I do a bit of travelling and I wanted to create an app that allowed me to save taxi bookings into a database. I have only added a few fields to give me an idea how this all works. I'm quite new to programming and followed a number of tutorials to create an app that allows me to take a csv file and upload it to the app database. This works well and I have no problems displaying the data.

What I cannot fathom is how to enable clicking upon a record and displaying this in a new screen / view and then return to the main list again when a button is closed.

What I want to achieve is have the list of bookings and click one to display more details. then close this popup to see the original full list.

Code as below - All help appreciates and thanks in advance....

MainActivity.java

package com.stravides.jdw;

        import android.app.Dialog;
        import android.app.ListActivity;
        import android.content.ActivityNotFoundException;
        import android.content.ContentValues;
        import android.content.Intent;
        import android.database.sqlite.SQLiteDatabase;
        import android.net.Uri;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.ListAdapter;
        import android.widget.ListView;
        import android.widget.SimpleAdapter;
        import android.widget.TextView;
        import java.io.BufferedReader;
        import java.io.FileReader;
        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.HashMap;

public class MainActivity extends ListActivity {
    TextView lbl;
    DBController controller = new DBController(this);
    Button btnimport;
    Button btnphone;
    Button btnclear;

    ListView lv;
    ArrayList<HashMap<String, String>> myList;
    public static final int requestcode = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lbl = (TextView) findViewById(R.id.txtresulttext);
        btnimport = (Button) findViewById(R.id.btnupload);
        btnphone =  (Button) findViewById(R.id.btnphone);
        btnclear =  (Button) findViewById(R.id.btnclear);
        lv = getListView();


        btnimport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
                fileintent.setType("gagt/sdf");
                try {
                    startActivityForResult(fileintent, requestcode);
                } catch (ActivityNotFoundException e) {
                    lbl.setText("No activity that can handle file selection. Showing alternatives.");
                }

            }
        });

        btnclear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = controller.getWritableDatabase();
                String tableName = "taxiinfo";
                db.execSQL("delete from " + tableName);
                myList = controller.getAllProducts();
                if (myList.size() == 0) {
                    ListView lv = getListView();
                    ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,R.layout.v, new String[]
                                {"bID", "bDate", "bTime", "bFrom", "bTo"}, new int[]{0,0,0,0,0});
                    setListAdapter(adapter);
                    lbl.setText("Data Cleared");
                }
            }
        });

        btnphone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String uri = "tel:" + "0031251491418";
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse(uri));
                startActivity(intent);
            }
        });

        myList= controller.getAllProducts();
        if (myList.size() != 0) {
            ListView lv = getListView();
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
                    R.layout.v, new String[]{"bID", "bDate", "bTime", "bFrom", "bTo"}, new int[]{
                    R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo});
            setListAdapter(adapter);
            lbl.setText("");
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        switch (requestCode) {
            case requestcode:
                String filepath = data.getData().getPath();
                controller = new DBController(getApplicationContext());
                SQLiteDatabase db = controller.getWritableDatabase();
                String tableName = "taxiinfo";
                db.execSQL("delete from " + tableName);
                try {
                    if (resultCode == RESULT_OK) {
                        try {
                            FileReader file = new FileReader(filepath);
                            BufferedReader buffer = new BufferedReader(file);
                            ContentValues contentValues = new ContentValues();
                            String line = "";
                            db.beginTransaction();
                            while ((line = buffer.readLine()) != null) {
                                String[] str = line.split(",", 5);
                                String bID = str[0];
                                String bDate = str[1];
                                String bTime = str[2];
                                String bFrom = str[3];
                                String bTo = str[4];
                                contentValues.put("bID", bID);
                                contentValues.put("bDate", bDate);
                                contentValues.put("bTime", bTime);
                                contentValues.put("bFrom", bFrom);
                                contentValues.put("bTo", bTo);
                                db.insert(tableName, null, contentValues);
                                lbl.setText("Successfully Updated Database.");
                            }
                            db.setTransactionSuccessful();
                            db.endTransaction();
                        } catch (IOException e) {
                            if (db.inTransaction())
                                db.endTransaction();
                            Dialog d = new Dialog(this);
                            d.setTitle(e.getMessage().toString() + "first");
                            d.show();
                        }
                    } else {
                        if (db.inTransaction())
                            db.endTransaction();
                        Dialog d = new Dialog(this);
                        d.setTitle("Only CSV files allowed");
                        d.show();
                    }
                } catch (Exception ex) {
                    if (db.inTransaction())
                        db.endTransaction();
                    Dialog d = new Dialog(this);
                    d.setTitle(ex.getMessage().toString() + "second");
                    d.show();
                }
        }

        myList= controller.getAllProducts();
        if (myList.size() != 0) {
            ListView lv = getListView();
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
                    R.layout.v, new String[]{"bID", "bDate", "bTime", "bFrom", "bTo"}, new int[]{
                    R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo});
            setListAdapter(adapter);
            lbl.setText("Data Imported");
        }
    }
}

DBController.java

package com.stravides.jdw;
        import android.content.Context;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.database.sqlite.SQLiteOpenHelper;
        import android.util.Log;
        import java.util.ArrayList;
        import java.util.HashMap;

public class DBController extends SQLiteOpenHelper {
    private static final String LOGCAT = null;
    public DBController(Context applicationcontext) {
        super(applicationcontext, "jdwtaxi.db", null, 1);  // creating DATABASE
        Log.d(LOGCAT, "Created");
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        String query;
        query = "CREATE TABLE IF NOT EXISTS taxiinfo ( Id INTEGER PRIMARY KEY, bID TEXT,bDate TEXT,bTime TEXT,bFrom TEXT, bTo TEXT)";
        database.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int version_old,int current_version) {
        String query;
        query = "DROP TABLE IF EXISTS taxiinfo";
        database.execSQL(query);
        onCreate(database);
    }

    public ArrayList<HashMap<String, String>> getAllProducts() {
        ArrayList<HashMap<String, String>> taxiList;
        taxiList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM taxiinfo";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                //Id, Company,Name,Price
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Id", cursor.getString(0));
                map.put("bID", cursor.getString(1));
                map.put("bDate", cursor.getString(2));
                map.put("bTime", cursor.getString(3));
                map.put("bFrom", cursor.getString(4));
                map.put("bTo", cursor.getString(5));
                taxiList.add(map);
            } while (cursor.moveToNext());
        }
        return taxiList;
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="9"
    android:background="#FFC7C7C7"
    >


    <LinearLayout
        android:id="@+id/lvcontainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:layout_alignParentTop="true"
        android:orientation="horizontal"
        android:padding="1dp"
        android:background="#FFC7C7C7"
        android:weightSum="5">

        <TextView
            android:id="@+id/txttaxibID"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="Ref"
            android:textColor="#000000"
            android:textSize="13sp"
            android:clickable="false" />

        <TextView
            android:id="@+id/txttaxibDate"
            android:layout_width="15dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:padding="3dp"
            android:text="Date"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/txttaxibTime"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="Time"
            android:padding="3dp"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/txttaxibFrom"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="From"
            android:padding="3dp"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/txttaxibTo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="To"
            android:padding="3dp"
            android:textColor="#000000"
            android:textSize="13sp" />
    </LinearLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/lvcontainer"
        android:layout_weight="6.59"
        android:clickable="false"></ListView>

    <TextView
        android:id="@+id/txtresulttext"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginLeft="5dp"
        android:layout_below="@android:id/list"
        android:layout_marginTop="2dp"
        android:layout_weight="0.5"
        android:gravity="left"
        android:text=""
        android:textColor="#FFF55F54"
        android:textSize="10sp"
        android:textStyle="italic|bold"></TextView>



    <LinearLayout
        android:id="@+id/lvbottom"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:layout_weight="1"
        android:weightSum="1">

        <Button
            android:id="@+id/btnupload"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.33"
            android:gravity="center"
            android:text="UPLOAD"
            android:textColor="#ffffff"
            android:background="#1083f5"
            android:textSize="15sp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btnclear"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.33"
            android:gravity="center"
            android:text="CLEAR"
            android:textColor="#ffffff"
            android:background="#1003f5"
            android:textSize="15sp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btnphone"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.34"
            android:gravity="center"
            android:text="CALL JDW"
            android:textColor="#ffffff"
            android:background="#ffff0000"
            android:textSize="15sp"
            android:textStyle="bold" />


    </LinearLayout>

</LinearLayout>

v.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/lvh"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:scrollbars="horizontal"
        android:background="#ffe6e6e6"
        android:weightSum="5"
        android:minHeight="30dp"
        android:measureWithLargestChild="false"
        android:longClickable="false">
        <TextView
            android:id="@+id/txttaxibID"
            android:layout_width="1dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="Ref"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/txttaxibDate"
            android:layout_width="15dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:padding="3dp"
            android:text="Date"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/txttaxibTime"
            android:layout_width="1dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="Time"
            android:padding="3dp"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/txttaxibFrom"
            android:layout_width="1dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="From"
            android:padding="3dp"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/txttaxibTo"
            android:layout_width="1dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="To"
            android:padding="3dp"
            android:textColor="#000000"
            android:textSize="13sp" />

    </LinearLayout>

</LinearLayout>

csv data for testing

354302,21/06/2015,12:40,Schiphol Taxi Counter Jan de Wit Group,Hotel Fletcher Zeeduin
354303,22/06/2015,08:00,Hotel Fletcher Zeeduin,3H.18 Dudokhuis Hoofdingang
354304,22/06/2015,17:30,3H.18 Dudokhuis Hoofdingang,Hotel Fletcher Zeeduin
354305,23/06/2015,08:00,Hotel Fletcher Zeeduin,3H.18 Dudokhuis Hoofdingang
354306,23/06/2015,17:30,3H.18 Dudokhuis Hoofdingang,Hotel Fletcher Zeeduin
354307,24/06/2015,08:00,Hotel Fletcher Zeeduin,3H.18 Dudokhuis Hoofdingang
354308,24/06/2015,17:30,3H.18 Dudokhuis Hoofdingang,Hotel Fletcher Zeeduin
354309,25/06/2015,08:00,Hotel Fletcher Zeeduin,3H.18 Dudokhuis Hoofdingang
354312,25/06/2015,14:00,3H.18 Dudokhuis Hoofdingang,Schiphol Taxi Counter Jan de Wit Group

Aucun commentaire:

Enregistrer un commentaire