如何在内部保存数据?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在内部保存数据?相关的知识,希望对你有一定的参考价值。

我正在尝试创建一个“待办事项列表”,除了保存数据外,我已经完成了所有工作。我很新,想知道是否有人可以告诉我如何在内部保存数据。

这是我的代码:

main_to do list.Java

public class Main_ToDoList extends Activity implements OnClickListener
{
private Button btnAdd;
private EditText et;
private ListView lv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;

final Context context = this;

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

    btnAdd = (Button)findViewById(R.id.addTaskBtn);
    btnAdd.setOnClickListener(this);
    et = (EditText)findViewById(R.id.editText);
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);

    // set the lv variable to your list in the xml
    lv=(ListView)findViewById(R.id.list);
    lv.setAdapter(adapter);

    // set ListView item listener
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
        {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
            alertDialogBuilder.setTitle("Confirm Delete");
            alertDialogBuilder.setMessage("Sure you want to delete?");
            alertDialogBuilder.setCancelable(false);
            alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {
                    adapter.remove(adapter.getItem(position));
                }
            });
            alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {
                    dialogInterface.cancel();
                }
            });
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
    });
}
public void onClick(View v)
{
    String input = et.getText().toString();
    if(input.length() > 0)
    {
        adapter.add(input);
        et.setText("");
    }
}
@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__to_do_list, menu);
    return true;
} 
}

我如何保存我输入的数据?谢谢!

答案

您有3种方法可以执行此操作:SharedPreferences文件数据库

如果你想存储大量数据而不是使用dataBase,如果你想存储让我们说10-30个任务你可以使用SharedPreferences,这是最快的方法。

在任何情况下,如果您熟悉写入/读取文件,它也将是一条好路径,但可能需要更多工作。

另一答案

您可以创建一个DatabaseHandler类

        package com.connection;

         import java.io.File;
         import java.io.FileOutputStream;
         import java.io.IOException;
         import java.io.InputStream;
         import java.io.OutputStream;
         import java.util.ArrayList;
         import android.content.ContentValues;
         import android.content.Context;
          import android.database.Cursor;
         import android.database.sqlite.SQLiteDatabase;
         import android.database.sqlite.SQLiteOpenHelper;
         import android.database.sqlite.SQLiteStatement;
            import android.util.Log;

        public class DatabaseHandler extends SQLiteOpenHelper {



// ====================== String Variables ======================
// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.example/databases/"; // Package name
private static final String DATABASE_NAME = "test"; // Database Name

// ++++++++++++++++++++++ int Variables ++++++++++++++++++++++
private static final int DATABASE_VERSION = 1; // Database Version

// = = = = = = = = = = = Other Variables = = = = = = = = = = ==
private SQLiteDatabase myDataBase;
private final Context myContext;
SQLiteDatabase db;





public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = context;



}
public void db_open()
{
    db = this.getWritableDatabase();
}
/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public void createDataBase() throws IOException {
    boolean dbExist = databaseExist();

    if (dbExist) {
        // do nothing - database already exist
    } else {
        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gone a be able to overwrite that
        // database with our database.
        this.getReadableDatabase();
        try {
            copyDataBase(); // call method to copy database
            db = this.getWritableDatabase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

/**
 * Mrthod to check database is exist or not
 * @return
 */
public boolean databaseExist()
{
    File dbFile = new File(DB_PATH + DATABASE_NAME);
    return dbFile.exists();
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException {
    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DATABASE_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}


/**
 * Close Database
 */
@Override
public synchronized void close() {



    if (myDataBase != null)
        myDataBase.close();
    super.close();
}

public void DB_close()
{
    if(db!=null)
        db.close();
}


/**
 * Method to add data

 */
public  boolean addData(int vno,String content1,String content2){
    boolean status=false;

    ContentValues values = new ContentValues();
    String checkEntry = "select id from yourtable where id="+vno;// +"' AND userid="+userid;

    Cursor magazinecursor = db.rawQuery(checkEntry, null);
    if (magazinecursor.moveToFirst()) {

    } else {

        values.put("id", vno);
        values.put("content1", content1);
        values.put("content2", content2);




        long check = db.insert("yourtable", null, values);
        if (check > -1) {
            Log.i("inserstatus", "yourtable insert successfull");
            status = true;
        } else {
            Log.i("insertstatus", "yourtable insert unsuccessful");
        }
    }

    return status;
}





@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

然后在您要保存数据的Activity中

              DatabaseHandler myDbHelper;

            myDbHelper = new DatabaseHandler(MainActivity.this);
            myDbHelper.db_open();
            myDbHelper.addData(1,"sample",sample);

希望这会帮助你或其他....

另一答案

我有一些类似的东西,我想存储少量数据,但不想使用内容提供商或文件所以我使用SharePreferences。 (ps我在键的末尾使用了随机数,只是为了使它唯一,但是用户稍后从列表中选择它,所以我知道了值)

SharedPreferences sp = this.getPreferences( Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sp.edit();
Random rand = new Random();
int randomNum = rand.nextInt( 1000 );
editor.putString( "EQUATION_KEY_" + String.valueOf( randomNum ), textToSave);
editor.commit();

以上是关于如何在内部保存数据?的主要内容,如果未能解决你的问题,请参考以下文章

在内部片段类中使用ListView

如何从 cordova 应用程序将文件保存在内部存储中?

如何使用 Hibernate 在内部保存带有集合的实体?

java.io.FileNotFoundException 在内部存储中保存/加载android

保存在内部存储中捕获的​​图片?

如何在内部存储android java中下载和保存媒体文件