在另一个Activity中检索数据

时间:2016-10-15 14:13:36

标签: java android sqlite android-sqlite

我有一个申请。我将数据插入数据库。我想从另一个活动中检索该数据并将其插入EditText。这是我的MainActivity.java文件:

package com.example.vaibhav.splashscr;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {


     InformationHelper mydb;



    EditText editTextName, editTextMobileNo, editTextCity, editTextAddress, editTextPin;
    RadioButton radioButtongender;
    RadioGroup radioGroup;

    Button submit, view;

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


        mydb = new InformationHelper(this);

        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextMobileNo = (EditText) findViewById(R.id.editTextMobileNumber);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        editTextCity = (EditText) findViewById(R.id.editTextCity);
        editTextAddress = (EditText) findViewById(R.id.editTextAddress);
        editTextPin = (EditText) findViewById(R.id.editTextPincode);
        submit = (Button) findViewById(R.id.submit);
        view = (Button) findViewById(R.id.view);
//Two methods
        addData();
        viewAllData();

    }

    public void addData() {
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int select = radioGroup.getCheckedRadioButtonId();
                radioButtongender = (RadioButton) findViewById(select);
                boolean isInsert = mydb.insertData(editTextName.getText().toString(), editTextMobileNo.getText().toString(),
                        radioButtongender.getText().toString(), editTextCity.getText().toString(),
                        editTextAddress.getText().toString(), editTextPin.getText().toString());

                if (isInsert = true) {
                    Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Data Not Inserted", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void viewAllData() {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor res = mydb.getAllData();
                if (res.getCount() == 0) {
                    //show error
                    showMessage("Error", "No data found");
                    return;
                }


                StringBuffer stringBuffer = new StringBuffer();
                while (res.moveToNext()) {
                    stringBuffer.append("Id :" + res.getString(0) + "\n");
                    stringBuffer.append("Name :" + res.getString(1) + "\n");
                    stringBuffer.append("Mobile NO :" + res.getString(2) + "\n");
                    stringBuffer.append("Gender :" + res.getString(3) + "\n");
                    stringBuffer.append("City :" + res.getString(4) + "\n");
                    stringBuffer.append("Address :" + res.getString(5) + "\n");
                    stringBuffer.append("Pincode :" + res.getString(6) + "\n");

                    showMessage("data", stringBuffer.toString());
                }
            }
        });
    }
//I have done it through AlertDialog. I want it on another activity
    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();
    }
}

这是我的activity_main.xml文件:

//this the xml file where i have name, address, pincode, gender and other //details

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:weightSum="2">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/editTextName"
            android:layout_weight="1"
            android:gravity="center_vertical"

            android:paddingLeft="5dp"
            android:text="Name: "

            android:textSize="20dp" />

        <EditText
            android:id="@+id/editTextName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/name"
            android:layout_weight="1"
            android:hint="First Name" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:weightSum="2">

        <TextView
            android:id="@+id/mobilenumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/editTextMobileNumber"
            android:layout_weight="1"
            android:gravity="center_vertical"

            android:paddingLeft="3dp"
            android:text="Mobile No:"

            android:textSize="20dp" />

        <EditText
            android:id="@+id/editTextMobileNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/name"
            android:layout_weight="1"
            android:hint="Mobile Number"
            android:width="145dp"/>
    </LinearLayout>




    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:weightSum="2">

        <TextView
            android:id="@+id/gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/radioGroup"
            android:layout_weight="0.1"
            android:gravity="center_vertical"
            android:text="Gender: "
            android:textSize="20dp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioGroup
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:id="@+id/radioGroup"
                android:layout_marginLeft="100dp"

                android:weightSum="1">

                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Male"
                    android:id="@+id/radioButtonMale"
                    android:layout_gravity="center_horizontal"
                    android:checked="false"
                    android:layout_marginRight="1dp"
                    android:textSize="20dp" />


                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Female"
                    android:layout_marginLeft="10dp"
                    android:id="@+id/radioButtonFemale"
                    android:layout_gravity="center_horizontal"
                    android:checked="false"

                    android:textSize="20dp"/>

            </RadioGroup>
        </LinearLayout>
    </LinearLayout>



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:weightSum="2">

        <TextView
            android:id="@+id/city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/editTextName"
            android:layout_weight="0.86"
            android:gravity="center_vertical"

            android:paddingLeft="5dp"
            android:text="City: "

            android:textSize="20dp" />

        <EditText
            android:id="@+id/editTextCity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/name"
            android:layout_weight="1.14"
            android:hint="City" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:weightSum="2">

        <TextView
            android:id="@+id/address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/editTextName"
            android:layout_weight="0.80"
            android:gravity="center_vertical"

            android:paddingLeft="5dp"
            android:text="Address: "

            android:textSize="20dp" />
        <EditText
            android:id="@+id/editTextAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/name"
            android:layout_weight="1.2"
            android:hint="Address" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:weightSum="2">

        <TextView
            android:id="@+id/pincode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/editTextName"
            android:layout_weight="0.86"
            android:gravity="center_vertical"

            android:paddingLeft="5dp"
            android:text="Pincode"
            android:textSize="20dp" />
        <EditText
            android:id="@+id/editTextPincode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/name"
            android:layout_weight="1.14"
            android:hint="Pincode" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center"
        android:paddingTop="25dp">
        <Button

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Submit"
            android:id="@+id/submit"
            android:textColor="@android:color/holo_red_dark"/>
        <Button
            android:id="@+id/view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="View "
            android:textColor="@android:color/holo_red_dark"
            android:textAlignment="center"
            android:layout_marginLeft="30dp"/>
    </LinearLayout>



</LinearLayout>

这是我的InformationHelper.java文件:

// this is the logic to insert the data in database

package com.example.vaibhav.splashscr;

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

/**
 * Created by vaibhav on 15-10-2016.
 */
public class InformationHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "Details_Database";
    private static final String TABLE_NAME = "Information";
    private static final int DATABASE_VERSION = 1;
    private static final String UID = "_id";
    private static final String NAME = "Name";
    private static final String MOBILE_NO = "Mobile_no";
    private static final String GENDER = "Gender";
    private static final String CITY = "City";
    private static final String ADDRESS = "Address";
    private static final String PINCODE = "Pincode";

    private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " VARCHAR(50), " +
            "" + MOBILE_NO + " VARCHAR(10), " + GENDER + " VARCHAR(7), " + CITY + " VARCHAR(30), " +
            "" + ADDRESS + " VARCHAR(50), " + PINCODE + " VARCHAR(9));";

    private static final String DROP_TABLE = "DROP TABLE" + TABLE_NAME + "IF EXISTS";

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


    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        //CREATING THE DATABASE FOR THE FIRST TIME

        db.execSQL(CREATE_TABLE);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE);
        onCreate(db);
    }

    public boolean insertData(String name, String mobile, String gender, String city, String address, String pincode) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put(NAME, name);
        contentValues.put(MOBILE_NO, mobile);
        contentValues.put(GENDER, gender);
        contentValues.put(CITY, city);
        contentValues.put(ADDRESS, address);
        contentValues.put(PINCODE, pincode);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1) {
            return false;
        } else
            return true;
    }

//i have done it throught alertDialog. i want it to retrieve on another activity 
//using editText or TextView


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

有关如何实现这一目标的任何建议吗?

1 个答案:

答案 0 :(得分:1)

首先,在getAllData()中添加以下代码:

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();

    return this.database.query(TABLE_NAME, new String[] {UID, NAME, MOBILE_NO, GENDER, CITY, ADDRESS, PINCODE}, null, null, null, null, null);
}

在您的主要活动中,在onCreate()函数中插入以下代码:

InformationHelper db = new InformationHelper(this);
Cursor cursor = db.getAllData();

if (cursor.moveToFirst()) {
    editTextName.setText(cursor.getString(1));
    editTextMobileNo.setText(cursor.getString(2));
    editTextCity.setText(cursor.getString(4));
    editTextAddress.setText(cursor.getString(5));
    editTextPin.setText(cursor.getString(6));
}

表格中的所有数据都将打印在您设置的EditText中。它可以打印表格中的每一个条目,因为您没有任何功能只能从特定行检索某些数据。