Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在内部保存数据?_Android_Android Listview_Save - Fatal编程技术网

Android 如何在内部保存数据?

Android 如何在内部保存数据?,android,android-listview,save,Android,Android Listview,Save,我正在尝试创建一个“待办事项列表”,我已经完成了所有的事情,除了保存数据。我是个新手,不知道是否有人能告诉我如何在内部保存数据 这是我的密码: Main_ToDoList.java public class Main_ToDoList extends Activity implements OnClickListener { private Button btnAdd; private EditText et; private ListView lv; ArrayList<String&g

我正在尝试创建一个“待办事项列表”,我已经完成了所有的事情,除了保存数据。我是个新手,不知道是否有人能告诉我如何在内部保存数据

这是我的密码:

Main_ToDoList.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;
} 
}
public类Main\u ToDoList扩展活动实现OnClickListener
{
专用按钮btnAdd;
私人编辑;
私有ListView lv;
ArrayList=新建ArrayList();
阵列适配器;
最终上下文=此;
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_活动);
btnAdd=(按钮)findViewById(R.id.addTaskBtn);
btnAdd.setOnClickListener(此);
et=(EditText)findViewById(R.id.EditText);
adapter=new ArrayAdapter(这是android.R.layout.simple\u expandable\u list\u item\u 1,list);
//将lv变量设置为xml中的列表
lv=(ListView)findViewById(R.id.list);
低压设置适配器(适配器);
//设置ListView项目侦听器
lv.setOnItemClickListener(新的AdapterView.OnItemClickListener()
{
@凌驾
public void onItemClick(AdapterView父对象、视图、最终整型位置、长id)
{
AlertDialog.Builder alertDialogBuilder=新建AlertDialog.Builder(上下文);
alertDialogBuilder.setTitle(“确认删除”);
alertDialogBuilder.setMessage(“确定要删除吗?”);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(“是”,新的DialogInterface.OnClickListener()
{
@凌驾
公共void onClick(DialogInterface,inti)
{
移除(adapter.getItem(位置));
}
});
alertDialogBuilder.setNegativeButton(“否”,新的DialogInterface.OnClickListener()
{
@凌驾
公共void onClick(DialogInterface,inti)
{
dialogInterface.cancel();
}
});
AlertDialog AlertDialog=alertDialogBuilder.create();
alertDialog.show();
}
});
}
公共void onClick(视图v)
{
字符串输入=et.getText().toString();
if(input.length()>0)
{
adapter.add(输入);
et.setText(“”);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单)
{
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main\u to\u do\u列表,菜单);
返回true;
} 
}

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

您有3种方法可以做到这一点: 共享引用 文件 数据库

如果你想存储比使用数据库更多的数据,如果你想存储10-30个任务,你可以使用SharedReferences,这是最快的方法


在任何情况下,如果您熟悉写/读文件,这也是一个很好的方法,但可能需要更多的工作。

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


您可以创建一个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) {

}
}

然后在活动中保存数据

              DatabaseHandler myDbHelper;

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

希望这将有助于您或其他人……

您要保存哪些数据?抱歉,不使用数据库。我对SharedReference更感兴趣。SharedReference允许您动态创建项目吗?因为这是一个待办事项列表,每次添加一个新值时,我都需要保存它,但我也会从中删除项目。所以我不想显示我删除的项目是的,我也使用“editor.remove(KEY_to_delete);”从SharedPrefs中删除,其中KEY_to_delete是用户从ListView中选择的项目的键。为了清楚起见,首先我用上面的代码填充shared prefs,然后,所有共享的pref都会显示给用户,用户可以选择一个保存的值,也可以删除它们。密钥是随机的这一事实对我来说并不重要,因为用户从列表中选择了一个项,在这个点上我获得了密钥,然后我可以将它传递给remove函数,从共享前缀中删除它。我正在尝试保存我的数据。因此,首先我在listview中添加了几个项目(这些都发生在同一个页面上),然后当我关闭应用程序并重新启动它时,我希望我添加的数据仍然存在。现在,当我关闭并重新启动应用程序时,数据将消失。我想将listview保存到SharedReference onDestroy。这样我就可以重写保存的数据,而不必担心从SharedReference中删除
              DatabaseHandler myDbHelper;

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