在EditText中显示SQLite数据库中的单个字段

时间:2016-05-06 02:22:07

标签: android database sqlite

第一次在这里张贴,很久就潜伏了。我正在使用SQLite数据库开发一个Android应用程序来保存数据。我的第一个视图是ListView,用户可以在其中添加,更改或删除动物名称。他们还可以点击编辑按钮,将其带到第二个视图。此视图包含有关同一动物的更多详细信息,例如DOB和注释,其名称和ID从第一个视图转移。

我遇到的问题是我无法弄清楚如何让当前动物的DOB和评论从数据库中显示在各自的EditTexts中。我在这个视图的底部有一个保存按钮,它应该保存它们已经放入这些字段的任何信息,但是回到这个视图需要显示它们输入的内容。我的两个视图的代码和我的DBHelper类如下所示。谢谢!

以下是两个视图的图像。

ListView Primary View

Detail View

包含第一个视图和ListView的MainActivity:

public class MainActivity extends AppCompatActivity
{
public final static String ID_EXTRA = "com.example.josh.boergoats._ID";
public final static String NAME_EXTRA = "com.example.josh.boergoats.name";

private DBHelper dbHelper = null;
private Cursor cursor = null;
private DBAdapter adapter = null;
EditText editAnimal = null;
String animalId = null;
long idAnimal = 0;

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

        ListView listView = (ListView) findViewById(R.id.listView);
        editAnimal = (EditText) findViewById(R.id.animalEditText);

        dbHelper = new DBHelper(this);

        cursor = dbHelper.getAll();
        startManagingCursor(cursor);

        adapter = new DBAdapter(cursor);
        listView.setAdapter(adapter);

        Button addButton = (Button) findViewById(R.id.addButton);
        addButton.setOnClickListener(onSave);

        Button deleteButton = (Button) findViewById(R.id.deleteButton);
        deleteButton.setOnClickListener(onDelete);

        Button editButton = (Button) findViewById(R.id.editButton);
        editButton.setOnClickListener(onEdit);

        listView.setOnItemClickListener(onListClick);
    }
    catch (Exception e)
    {
        Log.e("ERROR", "ERROR IN CODE: " + e.toString());
        e.printStackTrace();
    }
}

@Override
protected void onDestroy()
{
    super.onDestroy();
    dbHelper.close();
}

private View.OnClickListener onSave = new View.OnClickListener()
{
    public void onClick(View v)
    {
        Button addButton = (Button) findViewById(R.id.addButton);
        if (animalId == null)
        {
            dbHelper.insert(editAnimal.getText().toString());
        }
        else
        {
            dbHelper.update(animalId, editAnimal.getText().toString());
            animalId = null;
        }
        cursor.requery();
        editAnimal.setText("");
        addButton.setText("Add Animal");
    }
};

private View.OnClickListener onDelete = new View.OnClickListener()
{
    public void onClick(View v)
    {
        if (animalId == null)
        {
            return;
        }
        else
        {
            dbHelper.delete(animalId);
            animalId = null;
        }
        cursor.requery();
        editAnimal.setText("");

        Button addButton = (Button) findViewById(R.id.addButton);
        addButton.setText("Add Animal");
    }
};

private View.OnClickListener onEdit = new View.OnClickListener()
{
    public void onClick(View v)
    {
        Button editButton = (Button) findViewById(R.id.editButton);
        editButton.setVisibility(View.INVISIBLE);

        Button addButton = (Button) findViewById(R.id.addButton);
        addButton.setText("Add Animal");

        Intent i = new Intent(MainActivity.this, DetailActivity.class);
        //i.putExtra(ID_EXTRA, String.valueOf(id));
        i.putExtra(NAME_EXTRA, String.valueOf(editAnimal.getText().toString()));
        i.putExtra(ID_EXTRA, String.valueOf(idAnimal));
        editAnimal.setText("");
        startActivity(i);
    }
};

private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener()
{
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        animalId = String.valueOf(id);
        Cursor c = dbHelper.getById(animalId);
        c.moveToFirst();
        editAnimal.setText(dbHelper.getAnimal(c));

        Button addButton = (Button) findViewById(R.id.addButton);
        addButton.setText("Update");

        Button editButton = (Button) findViewById(R.id.editButton);
        editButton.setVisibility(View.VISIBLE);

        idAnimal = id;
    }
};


public class DBAdapter extends CursorAdapter
{
    DBAdapter(Cursor c)
    {
        super(MainActivity.this, c);
    }

    @Override
    public void bindView(View view, Context context, Cursor c)
    {
        DBHolder holder = (DBHolder) view.getTag();
        holder.populateFrom(c, dbHelper);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent)
    {
        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.row, parent, false);
        DBHolder holder = new DBHolder(row);
        row.setTag(holder);
        return(row);
    }

}

static class DBHolder
{
    private TextView name = null;

    DBHolder(View row)
    {
        name = (TextView) row.findViewById(R.id.nameTextView);
    }

    void populateFrom(Cursor c, DBHelper helper)
    {
        //name.setText(r.getName(c));
        name.setText(helper.getAnimal(c));
    }
}
}

第二个活动,DetailActivity,我遇到了问题。

public class DetailActivity extends AppCompatActivity
{

private DBHelper dbHelper = null;
//private Cursor cursor = null;
String passedName = null;
String passedID = null;
private EditText passedIdView = null;
private EditText passedNameView = null;
private EditText dobView = null;
private EditText commentsView = null;


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

    //dbHelper = new DBHelper(this);
    //cursor = dbHelper.getAllInfo();


    passedName = getIntent().getStringExtra(MainActivity.NAME_EXTRA);
    passedNameView = (EditText) findViewById(R.id.nameDetailEditText);
    passedNameView.setText(passedName);

    passedID = getIntent().getStringExtra(MainActivity.ID_EXTRA);
    passedIdView = (EditText) findViewById(R.id.idDetailEditText);
    passedIdView.setText(passedID);

    dobView = (EditText) findViewById(R.id.dobDetailEditText);
    commentsView = (EditText) findViewById(R.id.commentsDetailEditText);

    Button saveButton = (Button) findViewById(R.id.saveButton);
    saveButton.setOnClickListener(onSave);

}

private View.OnClickListener onSave = new View.OnClickListener()
{
    public void onClick(View v)
    {
        String id = passedID;


        passedID = getIntent().getStringExtra(MainActivity.ID_EXTRA);

        if (passedNameView.getText().toString() != null)
        {
            if (passedID != null)
            {
                dbHelper.update(id, passedNameView.getText().toString());
            }

        }
        if (dobView.getText().toString() != null)
        {
            dbHelper.updateDob(id, dobView.getText().toString());
        }
        if (commentsView.getText().toString() != null)
        {
            dbHelper.updateComments(id, commentsView.getText().toString());
        }


        //reset all edittext fields to blank before leaving
        passedIdView.setText("");
        passedNameView.setText("");
        dobView.setText("");
        commentsView.setText("");


        Intent i = new Intent(DetailActivity.this, MainActivity.class);
        startActivity(i);
    }
};

}

Database Helper类,用于创建和操作数据库。请注意,并非所有方法都在使用,其中一些方法来自我的实验。

public class DBHelper extends SQLiteOpenHelper

{

private static final String dbPath = "/data/data/com.example.josh.boergoats/";
private static final String dbName = "animals.db";
private static final int schemaVersion = 1;

public DBHelper(Context context)
{
    super(context, dbName, null, schemaVersion);
    //this.myContext = context;
}

@Override
public void onCreate(SQLiteDatabase db)
{
    db.execSQL("CREATE TABLE Animals (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, dob TEXT, comments TEXT);");
}

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

public void insert(String animal)
{
    ContentValues cv = new ContentValues();
    cv.put("name", animal);
    getWritableDatabase().insert("Animals", "name", cv);
}

public void update(String id, String animal)
{
    ContentValues cv = new ContentValues();
    String[] args = {id};
    cv.put("name", animal);
    getWritableDatabase().update("Animals", cv, "_id=?", args);
}

public void updateDob(String id, String dob)
{
    ContentValues cv = new ContentValues();
    String[] args = {id};
    cv.put("dob", dob);
    getWritableDatabase().update("Animals", cv, "_id=?", args);
}

public void updateComments(String id, String comment)
{
    ContentValues cv = new ContentValues();
    String[] args = {id};
    cv.put("comments", comment);
    getWritableDatabase().update("Animals", cv, "_id=?", args);
}

public void delete(String id)
{
    getWritableDatabase().delete("Animals", "_id=?", new String[] {id});
}
public Cursor getAll()
{
    return(getReadableDatabase().rawQuery("SELECT _id, name FROM Animals", null));
}

public Cursor getAllInfo()
{
    return(getReadableDatabase().rawQuery("SELECT _id, name, dob, comments FROM Animals", null));
}

public String getAnimal(Cursor c)
{
    return(c.getString(1));
}

public String getDob(Cursor c)
{
    return(c.getString(2));
}

public String getComments(Cursor c)
{
    return(c.getString(3));
}

public Cursor getById(String id)
{
    String[] args = {id};
    return(getReadableDatabase().rawQuery("SELECT _id, name FROM Animals WHERE _id=?", args));
}

}

提前再次感谢你。

1 个答案:

答案 0 :(得分:0)

我所做的,使用相同的活动来添加或编辑(我相信你正在尝试做的事情),是通过Intent Extra传递相应的选项,然后设置代码各自的价值观。这是一个例子: -

        String caller = getIntent().getStringExtra("Caller");

        if(getIntent().getStringExtra("Caller").equals("ShopListByCursorActivityUpdate")) {
            ((EditText) findViewById(R.id.ase_storename_input)).setText(getIntent().getStringExtra("ShopName"));
            ((EditText) findViewById(R.id.ase_storeorder_input)).setText(getIntent().getStringExtra("ShopOrder"));
            ((EditText) findViewById(R.id.ase_storestreet_input)).setText(getIntent().getStringExtra("ShopStreet"));
            ((EditText) findViewById(R.id.ase_storecity_input)).setText(getIntent().getStringExtra("ShopCity"));
            ((EditText) findViewById(R.id.ase_storestate_input)).setText(getIntent().getStringExtra("ShopState"));
            ((EditText) findViewById(R.id.ase_storephone_input)).setText(getIntent().getStringExtra("ShopPhone"));
            ((EditText) findViewById(R.id.ase_storenotes_input)).setText(getIntent().getStringExtra("ShopNotes"));
            setTitle(getResources().getString(R.string.title_activity_shop_edit));
        }

第二行检查更新模式(即Intent Extra中名为来电者的内容(提取到来电者))然后设置各自在Intent Extras中的值。我不需要第一行用于调试目的。

请注意,当“添加”设置为 ShopListByCursorActivity 时,“编辑”而非“添加”调用时,意图额外Caller设置为 ShopListByCursorActivityUpdate

PS您可能在第一个活动中遇到问题而没有显示已更改/保存的数据,因为它不会显示您刷新数据。简而言之,如果这是一个问题。您需要重建光标(即重做查询),然后让适配器通过changeCursorSwapCursornotifyDataSetChanged使用新的/修改过的光标。例如: -

Cursor csr = shopperdb.getShopsAsCursor();
currentsca.swapCursor(csr);

关于评论

  

你走在正确的轨道上,但我实际上无法将我需要的信息输入Intent Extra。由于我的第一个活动中没有DOB或注释字段,因此我需要从我的数据库中提取该信息并以某种方式将其放入Intent Extra中。这两个字段是在我的DBHelper类中创建的。此外,根据如何从数据库中提取它们,如果它们可以直接放入我的EditTexts中,它们甚至可能不需要放入Intent Extra。

然后使用SELECT * FROM Animals获取getAll中的所有列,然后所有列都将在返回的Cursor中可用。