mardi 16 février 2016

Android: Open a new layout file on button click and apply SQLite data to it

I have a gridview here:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

    xmlns:android="http://ift.tt/nIICcg"

    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context=".MainActivity">



    <LinearLayout
        android:id="@+id/topContent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="7">

        <TextView
            android:id="@+id/textView0"
            android:background="@color/white"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ID: "
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />


        <TextView
            android:id="@+id/textView1"
            android:background="@color/purple"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridCode"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView2"
            android:background="@color/green"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridDay"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView3"
            android:background="@color/orange"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridStart"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView4"
            android:background="@color/blue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridDuration"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView5"
            android:background="@color/yellow"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridType"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />

        <TextView
            android:id="@+id/textView6"
            android:background="@color/red"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/gridRoom"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:gravity="center"
            />
    </LinearLayout>

    <GridView
        android:id="@+id/gridTable"
        android:layout_below="@+id/topContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="10dip"
        android:verticalSpacing="15dip"
        android:stretchMode="columnWidth"
        android:gravity="center"

        android:numColumns="7"

        android:background="@color/colorPrimary"
        android:textSize="14sp"
        >
    </GridView>

</RelativeLayout> 

And a database helper:

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

public class DatabaseHelper extends SQLiteOpenHelper
{
    //database information
    public static final String DATABASE_NAME    = "timetable.db";
    public static final String TABLE_NAME       = "timetable_data";

    //the data each column will store
    public static final String COL_1 = "ID";
    public static final String COL_2 = "CODE";
    public static final String COL_3 = "DAY";
    public static final String COL_4 = "START";
    public static final String COL_5 = "DURATION";
    public static final String COL_6 = "TYPE";
    public static final String COL_7 = "ROOM";


    //construct the database
    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,CODE TEXT,DAY TEXT,START TEXT,DURATION TEXT,TYPE TEXT,ROOM TEXT)");
    }

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

    public boolean insertData(String code, String day, String start, String duration, String type, String room)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,code);
        contentValues.put(COL_3,day);
        contentValues.put(COL_4,start);
        contentValues.put(COL_5,duration);
        contentValues.put(COL_6,type);
        contentValues.put(COL_7, room);

        long result = db.insert(TABLE_NAME,null,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }

    public Cursor getAllData()
    {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("select * from "+TABLE_NAME,null);
        return data;
    }

    public Integer deleteEntry(String id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME,"ID = ?", new String [] {id});
    }
}

What I'm trying to do, is create an adapter that can be applied to that gridview when a button is pressed. The adapter should pull all of the information from the database and insert each bit of data into each cell of the grid. I'd like all of this to happen when a button is pressed, pressing the button will show the grid in a new layout, and when the back button is pressed go back to the main_acitivty layout. but I'm not sure if I need the other layout file there, or where the button goes, or even if this is possible to do, so any help would be appreciated! thanks!

Main_activity source:

import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    DatabaseHelper timetableDB;

    EditText roomInput, codeInput, idInput;
    Spinner dayInput, durationInput, timeInput, sessionInput;
    Button button_add, button_display, button_delete, button_display_grid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timetableDB = new DatabaseHelper(this);

        codeInput = (EditText) findViewById(R.id.codeInput);
        dayInput = (Spinner) findViewById(R.id.dayInput);
        timeInput = (Spinner) findViewById(R.id.timeInput);
        durationInput = (Spinner) findViewById(R.id.durationInput);
        sessionInput = (Spinner) findViewById(R.id.sessionInput);
        roomInput = (EditText) findViewById(R.id.roomInput);
        idInput = (EditText) findViewById(R.id.idInput);

        button_add = (Button) findViewById(R.id.button_add);
        button_display = (Button) findViewById(R.id.button_display);
        button_display_grid = (Button) findViewById(R.id.button_display_grid);
        button_delete = (Button) findViewById(R.id.button_delete);

        AddData();
        displayData();
        deleteData();
    }

    button_display_grid.setOnClickListener(new View.OnClickListener()

    {
        //This method starts the GridView activity when the button is pressed
        @Override
        public void onClick (View v)
        {
            Intent i = new Intent(MainActivity.this, GridViewActivity.class);
            startActivity(i);
        }
    }

    public void deleteData()
    {
        button_delete.setOnClickListener(
                new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        Integer deletedData = timetableDB.deleteEntry(idInput.getText().toString());
                        if(deletedData > 0)
                            Toast.makeText(MainActivity.this, "Entry Removed", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(MainActivity.this, "Error Removing Entry", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }
    public void AddData()
    {
        button_add.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                boolean isInserted = timetableDB.insertData(
                        codeInput.getText().toString(),
                        dayInput.getSelectedItem().toString(),
                        timeInput.getSelectedItem().toString(),
                        durationInput.getSelectedItem().toString(),
                        sessionInput.getSelectedItem().toString(),
                        roomInput.getText().toString());


                if (isInserted = true)
                    Toast.makeText(MainActivity.this, "Module Added", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(MainActivity.this, "Error Adding Data", Toast.LENGTH_SHORT).show();
            }
        }
        );
    }

    public void displayData()
    {
        button_display.setOnClickListener(new View.OnClickListener()
                {
                @Override
                public void onClick(View v)
                    {
                        Cursor data = timetableDB.getAllData();
                        if(data.getCount() == 0)
                        {
                            //show message
                            return;
                        }

                        StringBuilder buffer = new StringBuilder();
                        while (data.moveToNext())
                        {
                            buffer.append("ID :"+ data.getString(0)+"\n");
                            buffer.append("Code :"+ data.getString(1)+"\n");
                            buffer.append("Day :"+ data.getString(2)+"\n");
                            buffer.append("Start :"+ data.getString(3)+"\n");
                            buffer.append("Duration: "+ data.getString(4)+"\n");
                            buffer.append("Type :"+ data.getString(5)+"\n");
                            buffer.append("Room :"+ data.getString(6)+"\n\n");
                        }
                    showMessage("My Timetable:", buffer.toString());
                    }
                }
        );
    }
    public void showMessage(String title, String Message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }
}

Aucun commentaire:

Enregistrer un commentaire