如何在活动之间传递数据库

时间:2014-12-18 00:06:17

标签: android sqlite android-activity

我试图在多个活动中使用我的数据库,并已阅读此处发布的问题,但要么让我感到困惑,要么他们通过意图传递文本而不是传递整个SQLiteDatabase。我听说使用内容提供商很好但是android声明不使用它来在同一个应用程序中的活动之间传递数据库

“在开始构建提供程序之前,请执行以下操作:

决定是否需要内容提供商。如果要提供以下一项或多项功能,则需要构建内容提供程序:

您希望向其他应用程序提供复杂的数据或文件。

您希望允许用户将应用中的复杂数据复制到其他应用中。

您希望使用搜索框架提供自定义搜索建议。

如果使用完全在您自己的应用程序中,则不需要提供程序来使用SQLite数据库。

如果我知道从哪里开始或有代码我会发布但我不知道从哪里开始。我正在创建一个短信应用程序,需要将数据库从主活动传递到对话活动。感谢所有帮助。

package com.swavey.testing;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;


public class MainActivity extends Activity {

    SharedPreferences prefs;
    SimpleCursorAdapter adapter;
    private ArrayList<smsDatabase> dbs;
    private SMSList<SMS> smsList;
    private ArrayList<String> smsAddressList;
    private final String firstRun = "initRun";

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


        prefs = getPreferences(MODE_PRIVATE);
        //check if first run to try and run initsync or upgrade
        if (!prefs.contains(firstRun)) {
            Sync();
            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putBoolean(firstRun, true);
        }

        populateThreads();


    }


    public void Sync() {
    }

    private void upgradeSync(Cursor cursor) {

    }


    private void initialSync(Cursor c) {

    }

    private SMS addText(Cursor c) {
        SMS txt = new SMS();
        txt.setDate(c.getString(c.getColumnIndex("date")));
        txt.set_id(c.getString(c.getColumnIndex("_id")));
        txt.setBody(c.getString(c.getColumnIndex("body")));
        txt.setType(c.getString(c.getColumnIndex("type")));
        txt.setAddress(c.getString(c.getColumnIndex("address")));
        txt.setRead(c.getString(c.getColumnIndex("read")));
        txt.setSeen(c.getString(c.getColumnIndex("seen")));
        txt.setSubject(c.getString(c.getColumnIndex("subject")));
        txt.setThread_id(c.getString(c.getColumnIndex("thread_id")));
        txt.setPerson(c.getString(c.getColumnIndex("person")));
        txt.setProtocol(c.getString(c.getColumnIndex("protocol")));
        txt.setServiceCenter(c.getString(c.getColumnIndex("service_center")));
        return txt;
    }

    public void populateThreads() {
        /*number of threads is number of smsAddressList
        first line is from addressList
        second is form first "date dsc" text of respective database
        left is pic
         */
        ArrayAdapter<String> adapter1 = new MainListAdapter();
        ListView list = (ListView) findViewById(R.id.threads);
        list.setAdapter(adapter1);



    }

    private class MainListAdapter extends ArrayAdapter<String> {
        public MainListAdapter() {
            super(MainActivity.this, R.layout.sms_listview_layout, smsAddressList);
        }

        public View getView (int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            if (itemView == null) {
                itemView = getLayoutInflater().inflate(R.layout.sms_listview_layout, parent, false);
            }

            // assigns address
            String currentAddress = smsAddressList.get(position);
            TextView bigView = (TextView) itemView.findViewById(R.id.firstLine);
            bigView.setText(currentAddress);

            //assigns subject
            dbs.get(position).open();
            String subject = dbs.get(position).getSubject();
            dbs.get(position).close();
            TextView lilView = (TextView) itemView.findViewById(R.id.secondLine);
            lilView.setText(subject);

            //assigns picture


            return itemView;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        } if (id == R.id.action_sync) {
            Sync();
        }
         if (id == R.id.loadtexts) {
            populateThreads();
        }
        return super.onOptionsItemSelected(item);
    }
}

package com.swavey.testing;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.security.KeyChain;

import java.util.Date;

/**
 * Created by Adrian on 11/5/2014.
 */
public class smsDatabase  {

    private static final String KEY_ID = "_id";
    private static final int COLUMN_ID =0;

    // database info
    public static final String DATABASE_NAME = "texts";
    public static final String DATABASE_TABLE = "mainTable";
    public static final int DATABASE_VERSION = 4;

    // list of fields
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_BODY = "body";
    private static final String KEY_DATE = "date";
    private static final String KEY_READ = "read";
    private static final String KEY_THREADID = "thread_id";
    private static final String KEY_TYPE = "type";
    private static final String KEY_SEEN = "seen";

    //list of field numbers
    private static final int COL_ADDRESS = 1;
    private static final int COL_BODY = 2;
    private static final int COL_DATE = 3;
    private static final int COL_READ = 4;
    private static final int COL_THREADID = 5;
    private static final int COL_TYPE = 6;
    private static final int COL_SEEN = 7;

    //create string array of all fields;
    public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_ADDRESS, KEY_BODY, KEY_DATE,
         KEY_READ, KEY_THREADID, KEY_TYPE, KEY_SEEN};


    private static final String DATABASE_CREATE_SQL = "create table " + DATABASE_TABLE
            + " (" + KEY_ID + " integer primary key autoincrement, "
            +KEY_ADDRESS + " text not null, "
            +KEY_BODY + " text not null, "
            +KEY_DATE + " text not null, "
            +KEY_READ+ " text not null, "
            +KEY_THREADID+ " text not null, "
            +KEY_TYPE+ " text not null, "
            +KEY_SEEN+ " text not null"
            + ");";

    private final Context context;

    private DatabaseHelper dbHelper;
    private SQLiteDatabase db;

    public smsDatabase (Context cxt) {
        this.context = cxt;
        dbHelper = new DatabaseHelper(context);
    }

    //open database
    public smsDatabase open() {
        db = dbHelper.getWritableDatabase();
        return this;
    }
    //close database
    public void close() {
        dbHelper.close();
    }

    //returns a cursor with all rows loaded
    public Cursor getAllRows() {
        String where = null;
        Cursor cursor = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null,
        null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    /*
    LEARN HOW OT FIND NUMBER OF THREAD IDS. CREATE NUMBER OF THREAD IDS DIFFERENT DATABASES
    USE ARRAY LIST TO KNOW ADDRESSS OF DIFFERENT THREADS
    DISPLAY ARRAY LIST IN LISTVIEW
    USER OPENS CONVO WHICH READS FROM THAT DATABASE

     */

    // insert sms into table
    public long insertSMS (SMS sms) {
        ContentValues iv = new ContentValues();
        iv.put(KEY_ADDRESS, sms.getAddress());
        iv.put(KEY_BODY, sms.getBody());
        iv.put(KEY_DATE, sms.getDate());
        iv.put(KEY_READ, sms.getRead());
        iv.put(KEY_THREADID, sms.getThread_id());
        iv.put(KEY_TYPE, sms.getType());
        iv.put(KEY_SEEN, sms.getSeen());




        return db.insert(DATABASE_TABLE, null, iv);
    }

    public Cursor getLast() {
        SMS txt = new SMS();
        String where = null;
        Cursor c = db.query(true, DATABASE_TABLE,ALL_KEYS, where, null, null, null, null, null);
        c.moveToLast();
        return c;
    }

    public String getSubject() {
        Cursor c = getLast();
        String sub = c.getString(c.getColumnIndex("body"));
        if (sub.length() > 30) {
            sub = sub.substring(0, 30) + "...";
            return sub;
        }
        sub = sub +  "...";
        return sub;
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);
        }


        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            _db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_TABLE);
            onCreate(_db);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您需要的是一个sqlite数据库。您可以从所有活动中访问它。但是,您可以通过意图传递文本/数据。比方说,例如,您有一个名为FirstActivity的活动,询问用户他的名字,然后您可以将他的名字传递给MainActivity以显示他的名字。您可以使用sqlite数据库存储“大量”数据。

答案 1 :(得分:0)

问你为什么不在另一个Activity中实例化smsDatabase?

我不太了解这个建议。确实,ContentProvider在某种程度上是一种矫枉过正,但它将提供现成的解决方案,该解决方案将应用程序中的所有活动都可以使用sql封装。您可以将ContentProvider保密,这样就不会有任何数据暴露给外部。

相关问题