mardi 27 janvier 2015

User Profile - Adding Data to Database SQL Lite - Android?

I've got a user profile I am making for my app and need some assistance. I've got 2 classes UserProfile.java which houses all the key functions for my user profile along with its respective xml file (activity_user_profile) which has 4 "Edit Text Fields". My question is how to get it add data when I click the save button. I was following an online tutorial and got some errors as I've changed my approach. If you could help me figure these out please.


UserProfile.Java: *This class has no errors


public class UserProfile extends ActionBarActivity {



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


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_user_profile, 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.
switch (item.getItemId()) {
case R.id.homescreen:
homescreenItem();
return true;
case R.id.dashboard:
dashboardItem();
return true;
case R.id.about:
aboutItem();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

private void homescreenItem(){
startActivity(new Intent(UserProfile.this, Home.class));
}

private void dashboardItem(){
startActivity(new Intent(UserProfile.this, Dashboard.class));
}

private void aboutItem(){
new AlertDialog.Builder(this)
.setTitle("About")
.setMessage("Welcome to Save Me! An interactive and intuitive way to protect yourself during emergency situations and keep your location privacy. Made for a Dissertation and Developed by Ankhit Sharma")
.setNeutralButton("OK" , new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
}).show();
}


}


SaveProfile.Java: *errors in class



import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
* Created by Ankhit on 27/01/15.
*/
public class SaveProfile extends Activity {


DBAdapter db = new DBAdapter(this);

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

}
public void addAssignment(View v)
{
Log.d("test", "adding");
//get data from form
EditText firstTxt = (EditText)findViewById(R.id.ediFirsttname);
EditText lastTxt = (EditText)findViewById(R.id.editLastname);
EditText addressTxt = (EditText)findViewById(R.id.editAddress);
EditText commentsTxt = (EditText)findViewById(R.id.editComments);

db.open();
long id = db.insertRecord(firstTxt.getText().toString(), lastTxt.getText().toString(), addressTxt.getText().toString(), commentsTxt.getText().toString());
db.close();

firstTxt.setText("");
lastTxt.setText("");
addressTxt.setText("");
commentsTxt.setText("");
Toast.makeText(SaveProfile.this, "Profile Saved", Toast.LENGTH_LONG).show();

}



try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

DBAdapter db = new DBAdapter(this);


//---add an assignment---

db.open();
long id = db.insertRecord("John", "Doe", "Surrey,United Kingdom", "First Android Project");
id = db.insertRecord("Bob", "Johnson", "Brooklyn,New Jersey", "Android");
db.close();


//---get all Records---
/*
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
*/


//---get a Record---
db.open();
Cursor c = db.getRecord(1);
if (c.moveToFirst())
DisplayRecord(c);
else
Toast.makeText(this, "No User Profile Found", Toast.LENGTH_LONG).show();
db.close();



//---update Record---
/*
db.open();
if (db.updateRecord(1, "Hello Android", "2/19/2012", "DPR 224", "First Android Project"))
Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
db.close();
*/

/*
//---delete a Record---
db.open();
if (db.deleteRecord(1))
Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show();
db.close();
*/
}

private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>

@Override
public int getCount() {

return 0;
}

@Override
public Object getItem(int arg0) {

return null;
}

@Override
public long getItemId(int arg0) {

return 0;
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {

return null;
}

}

public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}

public void DisplayRecord(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Firstname:" + c.getString(1) + "\n" +
"Lastname: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}

public void addAssignment(View view)
{

Intent i = new Intent("");
startActivity(i);
Log.d("TAG", "Clicked");
}

}



}


DBAdapter.java: *errors in class



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
* Created on 27/01/15.
*/
public class DBAdapter {

public static final String KEY_ROWID = "id";
public static final String KEY_FIRSTNAME = "firstname";
public static final String KEY_LASTNAME = "lastname";
public static final String KEY_ADDRESS = "address";
public static final String KEY_COMMENTS = "comments";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "ProfileDB";
private static final String DATABASE_TABLE = "userprofiletable";
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "firstname VARCHAR not null, lastname VARCHAR not null, address VARCHAR not null, comments VARCHAR not null );";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

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

@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}

//---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}

//---closes the database---
public void close() {
DBHelper.close();
}

//---insert a record into the database---
public long insertRecord(String firstname, String lastname, String address, String comments) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_FIRSTNAME, firstname);
initialValues.put(KEY_LASTNAME, lastname);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_COMMENTS, comments);
return db.insert(DATABASE_TABLE, null, initialValues);
}

//---deletes a particular record---
public boolean deleteContact(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

//---retrieves all the records---
public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_FIRSTNAME,
KEY_LASTNAME, KEY_ADDRESS, KEY_COMMENTS}, null, null, null, null, null);
}

//---retrieves a particular record---
public Cursor getRecord(long rowId) throws SQLException {
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[]{KEY_ROWID,
KEY_FIRSTNAME, KEY_LASTNAME, KEY_ADDRESS, KEY_COMMENTS},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

//---updates a record---
public boolean updateRecord(long rowId, String firstname, String lastname, String address, String comments) {
ContentValues args = new ContentValues();
args.put(KEY_FIRSTNAME, firstname);
args.put(KEY_LASTNAME, lastname);
args.put(KEY_ADDRESS, address);
args.put(KEY_COMMENTS, comments);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}


activity_user_profile.xml



<EditText
android:id="@+id/ediFirsttname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/firstname" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editLastname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/lastname"
android:inputType="date"
android:layout_below="@+id/ediFirsttname"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<EditText
android:id="@+id/editAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/address"
android:layout_below="@+id/editLastname"
android:layout_alignRight="@+id/viewprofile"
android:layout_alignEnd="@+id/viewprofile" />

<EditText
android:id="@+id/editComments"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/comments"
android:inputType="textMultiLine" android:lines="6"
android:layout_below="@+id/editAddress"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:id="@+id/saveprofile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/saveprofile"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:id="@+id/editprofile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/editprofile"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/viewprofile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/viewprofile"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/editComments"
android:layout_alignEnd="@+id/editComments" />

</RelativeLayout>

Aucun commentaire:

Enregistrer un commentaire