使用SQLite:Android Studio将数据从一个活动传输到另一个活动

时间:2018-06-04 23:21:21

标签: android sqlite android-sqlite

我有一个“Track Walk”页面,用于计算用户的步数。我的目的是累积这些步骤,然后在另一个Activity中显示“Total”。 Track walk页面包含一个“End Walk”按钮。单击时将计数器重置为0会很好,然后将总计步骤添加到总计数器。

我将致力于自己的解决方案,但也希望在此处发布以获得一些指导。谢谢!

以下是Track Walk活动:

public class trackWalk extends AppCompatActivity implements SensorEventListener {

                SensorManager sensorManager;
                TextView tv_steps;
                boolean running = false;
                SQLiteDatabase db;
     @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_track_walk);

    db=openOrCreateDatabase("STEPSTAKEN", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS STEPS_TABLE(steps INTEGER);");

    tv_steps = (TextView) findViewById(R.id.steps);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);


    button = findViewById(R.id.trackWalk);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           //Reset counter and Populate Total Value in "Walk History"
        }
    });

}

        @Override
        protected void onResume() {
            super.onResume();
            running=true;
            Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
            if(countSensor != null) {
                sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
            }
            else {
                Toast.makeText(this, "Please enable Sensor!", Toast.LENGTH_SHORT).show();
            }

        }



        @Override
        protected void onPause() {
        super.onPause();
        running = false;

        // Unregistering will stop steps
       //  sensorManager.unregisterListener(this);
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
        if(running) {
            tv_steps.setText(String.valueOf(event.values[0]));
            db.execSQL("INSERT INTO STEPS_TABLE VALUES('"+tv_steps.getText()+"');");
        }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }

以下是“行走历史”页面,其中累积值应为:

package edu.phoenix.mbl402.walkmypup;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;

public class walkHistory extends AppCompatActivity {

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

3 个答案:

答案 0 :(得分:1)

您可以使用Intents执行此操作。将值与所需参数一起传递,并将其置于下一个活动中。

答案 1 :(得分:1)

我建议稍作修改,这可能会让您更好地利用数据。

这不是使用

db.execSQL("CREATE TABLE IF NOT EXISTS STEPS_TABLE(steps INTEGER);");

.........

db.execSQL("INSERT INTO STEPS_TABLE VALUES('"+tv_steps.getText()+"');");

使用

db.execSQL("CREATE TABLE IF NOT EXISTS STEPS_TABLE(steps INTEGER, timestamp TEXT DEFAULT CURRENT_TIMESTAMP);");

.........

db.execSQL("INSERT INTO STEPS_TABLE (steps) VALUES('"+tv_steps.getText()+"');");

也在改变: -

因此而不是拥有如下数据: -

enter image description here

除了两次更改之外,您将获得以下数据: -

enter image description here

  • 请注意,两者的上述数据是随机生成的,但在很短的时间内因此日期/时间相同。
例如,这可以让您非常轻松地每天提取说法。

关于将信息传递给另一个活动,基本上没有必要表格包含所有内容,因此只需查询新活动中的表格。

工作示例

以下示例基于您的代码。为了方便起见,我添加了一个模拟传感器更改的按钮和方法,当点击按钮时会添加一个随机数量的步骤。

代码中的注释希望能够解释代码。

TrackWalk **

public class TrackWalk extends AppCompatActivity implements SensorEventListener {

    //<<<<<<<<<< Use single source (constants) for DB related names
    public static final String DBNAME = "STEPSTAKEN";
    public static final String TB_STEPSTAKEN = "stepstaken";
    public static final String COL_STEPSTAKEN_STEPS = "steps";
    public static final String COl_STEPSTAKEN_TIMESTAMP = "timestamp";

    SensorManager sensorManager;
    TextView tv_steps;
    boolean running = false;
    SQLiteDatabase db;
    Button button, sensor; //<<<< Added another button to mimic sensor change
    Random rnd; //<<<<< For creating random number of steps

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

        //<<<<<<<<<< Note changes to use constants
        db=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null); //
        db.execSQL(
                "CREATE TABLE IF NOT EXISTS " +
                        TB_STEPSTAKEN +
                        "(" +
                        COL_STEPSTAKEN_STEPS + " INTEGER, " +
                        COl_STEPSTAKEN_TIMESTAMP + " TEXT DEFAULT CURRENT_TIMESTAMP" +
                        ")"
        );

        tv_steps = (TextView) findViewById(R.id.steps);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        //<<<<<<<<<< Added to mimic sensor change at button click
        sensor = this.findViewById(R.id.sensor);
        sensor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noSensor(); //<<<< Mimic sensor change

            }
        });


        button = findViewById(R.id.trackWalk);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Reset counter and Populate Total Value in "Walk History"
                Intent i = new Intent(getBaseContext(),WalkHistory.class); //<<<< ready to start activity
                startActivity(i); // start the WalkHistory Activity
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        running=true;
        Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if(countSensor != null) {
            sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
        }
        else {
            Toast.makeText(this, "Please enable Sensor!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        running = false;

        // Unregistering will stop steps
        //  sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(running) {
            tv_steps.setText(String.valueOf(event.values[0]));
            db.execSQL("INSERT INTO STEPS_TABLE VALUES('"+tv_steps.getText()+"');");
        }
    }

    //<<<<<<<<<< MIMIC SENSOR for testing >>>>>>>>>>
    public void noSensor() {
        db.execSQL("INSERT INTO " + TB_STEPSTAKEN +
                "(" + COL_STEPSTAKEN_STEPS + ")" +
                "VALUES("+String.valueOf(rnd.nextInt(10000-1 + 1)+1) +");");
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}

activity_walk_history.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".WalkHistory"
    tools:showIn="@layout/activity_walk_history">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Total Steps "
        />
    <TextView
        android:id="@+id/totalsteps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <ListView
        android:id="@+id/walkhistorylist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

WalkHistory

public class WalkHistory extends AppCompatActivity {

    Cursor mCsr;
    SQLiteDatabase mDB;
    SimpleCursorAdapter mSCA;
    ListView mLV;
    TextView mTotalSteps;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_walk_history);
        mLV = this.findViewById(R.id.walkhistorylist);
        mTotalSteps = this.findViewById(R.id.totalsteps);
        String total_steps_column_name = "total_steps";

        // As Cursor Adpaters need _id column grab an alias of thr rowid as _id
        String[] columns = new String[]{"rowid AS " + BaseColumns._ID + ",*"};

        // Get the database
        mDB = this.openOrCreateDatabase(TrackWalk.DBNAME, MODE_PRIVATE,null);

        // Extract Data (all) into a Cursor)
        mCsr = mDB.query(
                TrackWalk.TB_STEPSTAKEN,
                columns,
                null,
                null,
                null,
                null,
                TrackWalk.COl_STEPSTAKEN_TIMESTAMP + " DESC"
        );
        // Setup the Adapter for the ListView
        mSCA = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,mCsr,
                new String[]{"timestamp","steps"},
                new int[]{android.R.id.text1, android.R.id.text2},
                0
        );
        // Tie the Adapter to the Listview
        mLV.setAdapter(mSCA);

        // Get the sum of the Steps (note would use the same WHERE clause as the ListView Cursor)
        Cursor csr = mDB.query(
                TrackWalk.TB_STEPSTAKEN,
                new String[]{
                        "sum(steps) AS " + total_steps_column_name
                },
                null,
                null,
                null,
                null,
                null
        );
        // Apply the sum of the steps to the TextView
        if (csr.moveToFirst()) {
            mTotalSteps.setText(csr.getString(csr.getColumnIndex(total_steps_column_name)));
        }
    }
}

结果

以下是单击按钮转到WalkHistory活动(添加一些数据后)的结果示例。列出了条目。该列表前面是总步数。

enter image description here

可以看出,无需将TrackWalk活动中的任何信息传递给WalkHistory活动。

附加多个行走/重置计数器(排序)

如果您想保留历史记录,并且历史记录按钮是Walk Ended按钮。那么也许以下就足够了(至少可能作为一个起点)。基本上这适用于“当前行走”的概念,启动应用程序并假定“当前行走”并且在单击历史记录按钮时假定结束,此时仅显示该步行的那些步骤以及该行走的总计。

返回时(后退按钮)会假设一个新的Walk,等等。

这利用第二张桌子作为步行,其中3列id日期/时间,当开始日期/时间结束时但重要的是空白直至结束。

第一个表添加了另一个列,walk列是相应walk的id。

当应用程序启动或恢复(从WalkHistory活动返回)时,如果有任何步行(应该只有1)在walkended列中没有日期/时间,则该步行被视为当前步行。否则插入当前行走行(walkended列为空)。在这两种情况下,mCurrentWalk变量都设置为相应的 id

每条记录都包含拥有的walkid。单击“历史记录”按钮时,mCurrentlWalk值将通过一个额外的意图发送到WalkHistory活动。 WalkHistory活动获取此值并相应地设置相应的命名变量,并使用它来选择列表中显示的相应行以及确定总数时。 new是一个用当前日期时间更新walk行的调用,因此有效地将行(aka walk)标记为结束。

所以这里改变了 TrackWalk 活动“: -

public class TrackWalk extends AppCompatActivity implements SensorEventListener {

    //<<<<<<<<<< Use single source (constants) for DB related names
    public static final String DBNAME = "STEPSTAKEN";
    public static final String TB_STEPSTAKEN = "stepstaken";
    public static final String COL_STEPSTAKEN_STEPS = "steps";
    public static final String COl_STEPSTAKEN_TIMESTAMP = "timestamp";
    public static final String COL_STEPSTAKEN_WALK = "walk";
    public static final String TB_WALKS = "walks";
    public static final String COL_WALKID = "walkid";
    public static final String COL_WALKSTARTED = "walkstarted";
    public static final String COL_WALKENDED = "walkended";

    // used for passing data
    public static final String INTENTEXTRA_WALKID = "ie_walkid";

    SensorManager sensorManager;
    TextView tv_steps;
    boolean running = false;
    SQLiteDatabase db;
    Button button, sensor; //<<<< Added another button to mimic sensor change
    Random rnd; //<<<<< For creating random number of steps
    long mCurrentWalk;

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

        //<<<<<<<<<< Note changes to use constants
        db=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null); //
        db.execSQL(
                "CREATE TABLE IF NOT EXISTS " +
                        TB_STEPSTAKEN +
                        "(" +
                        COL_STEPSTAKEN_STEPS + " INTEGER, " +
                        COl_STEPSTAKEN_TIMESTAMP + " TEXT DEFAULT CURRENT_TIMESTAMP," +
                        COL_STEPSTAKEN_WALK + " INTEGER " + //<<<< ADDED FOR multiple walks
                        ")"
        );

        // Create a Walks table
        String crt_walks_table = "CREATE TABLE IF NOT EXISTS " +
                TB_WALKS +
                "(" +
                COL_WALKID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL_WALKSTARTED + " TEXT DEFAULT CURRENT_TIMESTAMP, " +
                COL_WALKENDED + " TEXT DEFAULT ''" +
                ")";
        db.execSQL(crt_walks_table);

        tv_steps = (TextView) findViewById(R.id.steps);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        //<<<<<<<<<< Added to mimic sensor change at button click
        sensor = this.findViewById(R.id.sensor);
        sensor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noSensor(); //<<<< Mimic sensor change
            }
        });

        button = findViewById(R.id.trackWalk);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Reset counter and Populate Total Value in "Walk History"
                Intent i = new Intent(getBaseContext(),WalkHistory.class); //<<<< ready to start activity
                i.putExtra(INTENTEXTRA_WALKID,mCurrentWalk);
                startActivity(i); // start the WalkHistory Activity
            }
        });
        setCurrentWalk(); //<<<< Set the current walk (utilises last if not ended)
    }

    @Override
    protected void onResume() {
        super.onResume();
        running=true;
        Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if(countSensor != null) {
            sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
        }
        else {
            Toast.makeText(this, "Please enable Sensor!", Toast.LENGTH_SHORT).show();
        }
        setCurrentWalk();
    }

    @Override
    protected void onPause() {
        super.onPause();
        running = false;

        // Unregistering will stop steps
        //  sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(running) {
            tv_steps.setText(String.valueOf(event.values[0]));
            db.execSQL("INSERT INTO STEPS_TABLE VALUES('"+tv_steps.getText()+"');");
        }
    }

    //<<<<<<<<<< MIMIC SENSOR for testing >>>>>>>>>>
    public void noSensor() {
        db.execSQL("INSERT INTO " + TB_STEPSTAKEN +
                "(" +
                COL_STEPSTAKEN_STEPS +
                "," +
                COL_STEPSTAKEN_WALK +
                ")" +
                "VALUES(" +
                String.valueOf(rnd.nextInt(10000-1 + 1)+1)
                +
                "," +
                String.valueOf(mCurrentWalk) +
                ");");
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    private void setCurrentWalk() {
        mCurrentWalk = -1;
        String whereclause = "length(" + COL_WALKENDED + ") < 1"; // Only walks that haven't been ended
        // Is there an unfished walk?? if so use that
        Cursor csr = db.query(TB_WALKS,null,whereclause,null,null,null,COL_WALKID + " DESC");
        if (csr.moveToFirst()) {
            mCurrentWalk = csr.getLong(csr.getColumnIndex(COL_WALKID)); //<<<< use incomplete walk
        }
        csr.close();
        // If there is no unfinished walk then create a new walk
        if (mCurrentWalk < 1) {
            String insrtsql = "INSERT INTO " + TB_WALKS +
                    " (" +
                    COL_WALKID +
                    ") VALUES(null)";
            db.execSQL(insrtsql);
            mCurrentWalk = DatabaseUtils.longForQuery(db,"SELECT last_insert_rowid()",null);
        }
    }
}

这是改变后的 WalkHistory 活动: -

public class WalkHistory extends AppCompatActivity {

    Cursor mCsr;
    SQLiteDatabase mDB;
    SimpleCursorAdapter mSCA;
    ListView mLV;
    TextView mTotalSteps;
    long mCurrentWalk;

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

        // Get the current walk id
        mCurrentWalk =  this.getIntent().getLongExtra(TrackWalk.INTENTEXTRA_WALKID,-1);

        mLV = this.findViewById(R.id.walkhistorylist);
        mTotalSteps = this.findViewById(R.id.totalsteps);
        String total_steps_column_name = "total_steps";

        // As Cursor Adpaters need _id column grab an alias of thr rowid as _id
        String[] columns = new String[]{"rowid AS " + BaseColumns._ID + ",*"};

        // Get the database
        mDB = this.openOrCreateDatabase(TrackWalk.DBNAME, MODE_PRIVATE,null);

        // Set the current walk as ended
        setCurrentWalkEnded();

        String whereclause = TrackWalk.COL_STEPSTAKEN_WALK + "=?";
        String[] whereargs = new String[]{String.valueOf(mCurrentWalk)};

        // Extract Data for this walk
        mCsr = mDB.query(
                TrackWalk.TB_STEPSTAKEN,
                columns,
                whereclause,
                whereargs,
                null,
                null,
                TrackWalk.COl_STEPSTAKEN_TIMESTAMP + " DESC"
        );
        // Setup the Adapter for the ListView
        mSCA = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,mCsr,
                new String[]{"timestamp","steps"},
                new int[]{android.R.id.text1, android.R.id.text2},
                0
        );
        // Tie the Adapter to the Listview
        mLV.setAdapter(mSCA);

        // Get the sum of the Steps (note would use the same WHERE clause as the ListView Cursor)
        Cursor csr = mDB.query(
                TrackWalk.TB_STEPSTAKEN,
                new String[]{
                        "sum(steps) AS " + total_steps_column_name
                },
                whereclause,
                whereargs,
                null,
                null,
                null
        );
        // Apply the sum of the steps to the TextView
        if (csr.moveToFirst()) {
            mTotalSteps.setText(csr.getString(csr.getColumnIndex(total_steps_column_name)));
        }
    }

    /**
     * Set the current walk as ended, but only if some records exist
     */
    private void setCurrentWalkEnded() {

        String whereclause1 = TrackWalk.COL_STEPSTAKEN_WALK + "=?";
        String[] whereargs = new String[]{String.valueOf(mCurrentWalk)};
        Cursor csr = mDB.query(TrackWalk.TB_STEPSTAKEN,null,whereclause1,whereargs,null,null,null);
        String whereclause2 = TrackWalk.COL_WALKID + "=?";
        if (csr.getCount() > 0 ) {
            String updtsql = "UPDATE " + TrackWalk.TB_WALKS + " SET " + TrackWalk.COL_WALKENDED + " = datetime('now') WHERE " + whereclause2;
            mDB.execSQL(updtsql, whereargs);
        }
        csr.close();
    }
}
  • 注意这尚未经过广泛测试,并且非常简陋。

答案 2 :(得分:0)

您可以使用意图来实现此目的,如上面的评论中所述。 但是,您也可以通过SQLite检索数据。

因此,当结束步行按钮结束时,您可以开始新的活动:

Intent intent = new Intent(trackWalk.this,walkHistory.class);
startActivity(intent); 

然后在处理SQLite的类上:

public Cursor fetchData() {
    Cursor c = this.database.query(SQLiteHelper.YOUR_TABLE_NAME,new String[]{SQLiteHelper.YOR_COLUMN}, null, null, null, null, null);
    if (c != null) {
         c.moveToFirst();
    }

    return c;
}

您可以使用此功能检索首选课程的数据。

使用意图可能会像:

Intent intent = new Intent(trackWalk.this,walkHistory.class);
intent.putExtra("MYDATA",//your data here);
startActivity(intent);

on onCreate上的walkHistory类:

//(or another type of variable, it also works for integers)
String steps = getIntent().getStringExtra("MYDATA");
//manage your data here