jeudi 5 mai 2016

Showing a single field from SQLite Database in an EditText

first time posting here, long time lurker. I am developing an Android app using an SQLite Database to persist data. The first view I have is a ListView where the user can add, change or delete Animal names. They can also hit an Edit Button, which brings them to a second view. This view has more details about the same animal, such as DOB and Comments, with the name and id transferred over from the first view.

The problem I am running into is I cannot figure out how to get the current animal's DOB and Comments to display in their respective EditTexts from the database. I have a save button at the bottom of this view that should save whatever info they put into these fields already, but then going back into this view needs to display whatever they have entered. My code for the two views and my DBHelper class is below. Thanks!

Here are images of what the two views look like.

ListView Primary View

Detail View

The MainActivity that contains the first view and the ListView:

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));
    }
}
}

The second activity, DetailActivity, where I am having the problem.

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);
    }
};

}

The Database Helper class, where the database is created and manipulated. Note that not all of the methods are being used, a few of them are from my experimenting.

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));
}

}

Thank you again in advance.

Aucun commentaire:

Enregistrer un commentaire