我是Android工作室的极端初学者并使用JavaScript,所以仍然学习并试图掌握整个android studio的新概念。
我正在尝试创建一个数据库,用于添加,编辑和删除用户手动输入的记录。
当我尝试从friends.xml页面添加新记录时,似乎没有在视图数据页面上找到任何记录。 它似乎没有记录数据条目?
friends.java (页面执行大部分操作)
package com.example.chris.mobileappsassignment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class friends extends AppCompatActivity {
private static final String TAG = "friends";
DatabaseHelper mDatabaseHelper;
private Button addbutton, viewdatabutton;
private EditText firstnameinput, lastnameinput, ageinput, addressinput;
/////////////////////////////////////////////////////////////////////////////
// SPINNER
/////////////////////////////////////////////////////////////////////////////
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
/////////////////////////////////////////////////////////////////////////////
//// END SPINNER
////////////////////////////////////////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friends);
// DECLARE EDIT TEXT'S
firstnameinput = (EditText) findViewById(R.id.firstnameinput);
lastnameinput = (EditText) findViewById(R.id.lastnameinput);
ageinput = (EditText) findViewById(R.id.ageinput);
addressinput = (EditText) findViewById(R.id.addressinput);
//DECLARE BUTTONS
addbutton = (Button) findViewById(R.id.addbutton);
viewdatabutton = (Button) findViewById(R.id.viewdatabutton);
//DECLARE SPINNER
spinner = (Spinner) findViewById(R.id.male_female);
mDatabaseHelper = new DatabaseHelper(this);
// ADD BUTTON
addbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean addOK = true;
int age_as_int = -1;
String firstName = firstnameinput.getText().toString();
String lastName = lastnameinput.getText().toString();
String age = ageinput.getText().toString();
String address = addressinput.getText().toString();
if (firstName.length() < 1) {
toastMessage("You must enter something in this field!");
firstnameinput.requestFocus();
addOK = false;
}
if (lastName.length() < 1) {
toastMessage("You must enter something in this field!");
lastnameinput.requestFocus();
addOK = false;
}
if (age.length() < 1) {
toastMessage("You must enter something in this field!");
ageinput.requestFocus();
addOK = false;
}
if (address.length() != 0) {
toastMessage("You must enter something in this field!");
addressinput.requestFocus();
addOK = false;
}
try {
age_as_int = Integer.parseInt(age);
} catch (NumberFormatException e) {
toastMessage("You must enter a valid Number in this field!");
ageinput.requestFocus();
addOK = false;
}
if (addOK) {
AddData(firstName,lastName,"????",age_as_int,address);
toastMessage("Friend Added!");
}
}
}); // end addbutton onclicklistener
// VIEW DATA BUTTON >>>> LINKS TO viewdata.xml (listview)
viewdatabutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(friends.this, listdata.class );
startActivity(intent);
}
});
/*
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
*/
/////////////////////////////////////////////////////////////////////////////
//SPINNER
/////////////////////////////////////////////////////////////////////////////
spinner = (Spinner)findViewById(R.id.male_female); //id of the spinner
adapter = ArrayAdapter.createFromResource(this, R.array.male_female,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+" selected",Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/////////////////////////////////////////////////////////////////////////////
//// END SPINNER
////////////////////////////////////////////////////////////////////////////
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
});
} // ON CREATE CLOSE
*// ADD DATA
public void AddData(String firstName, String lastName, String s, int age_as_int, String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Added!");
} else {
toastMessage("Something has gone wrong :(");
}
}*
/**
* customizable toast
* @param message
*/
private void toastMessage (String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
// GO TO SECOND PAGE (index.XML)
//also add on " android:onClick="gotoHome" " in the xml with the name matching the void action.
public void gotoHome (View view) {
Intent intent = new Intent(this, index.class); // go to index.class (index.xml)
startActivity(intent);
}
} // END CLASS
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "friends_table";
private static final String COL1 = "firstname";
private static final String COL2 = "lastname";
private static final String COL3 = "malefemale";
private static final String COL4 = "age";
private static final String COL5 = "address";
public DatabaseHelper (Context context) {
super(context, TABLE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID TEXT PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT)";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//
//
contentValues.put(COL1, item);
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item);
contentValues.put(COL5, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted inorrectly it will return -1
if (result == 1)
return false;
else {
return true;
}
} //end addData
/**
* Returns al data from DB
*/
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Returns ID that matches the name
* searches the DB and returns the ID associated with that name
*/
public Cursor getItemID(String name) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME + // SELECT ID FROM DB
" WHERE " + COL2 + " = '" + name + "'"; // WHERE THE LAST NAME = NAME SELECTED
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* UPDATES THE NAME
*
* UPDATE TABLE > SET LASTNNAME(COL2) = newName = WHERE id = id in Question = AND LASTNAME(COL2) = oldName (was previously) >
*/
public void updateName (String newName, int id, String oldName) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
" = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + oldName + "'";
//LOGS THE NEW NAME
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName); // NEW NAME CHANGING IT TO
db.execSQL(query); // EXECUTE QUERY
}
/**
* DELETE FROM DATABASE
* >>> DELETE FROM TABLE WHERE id = id passed AND name = name passed
*
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query); // EXECUTE QUERY
}
}
编辑:这是在logcat中发现的错误:
09-09 22:42:05.216 5846-5846/com.example.chris.mobileappsassignment E/SQLiteDatabase: Error inserting address=cht lastname=cht firstname=cht age=cht malefemale=cht
android.database.sqlite.SQLiteException: table friends_table has no column named address (code 1): , while compiling: INSERT INTO friends_table(address,lastname,firstname,age,malefemale) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.chris.mobileappsassignment.DatabaseHelper.addData(DatabaseHelper.java:57) // ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends.AddData(friends.java:168) // ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends$1.onClick(friends.java:73) // ERROR SEEMS TO APPEAR HERE
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-09 22:42:05.218 5846-5846/com.example.chris.mobileappsassignment D/DatabaseHelper: addData: Adding ffff to friends_table
09-09 22:42:05.218 5846-5846/com.example.chris.mobileappsassignment E/SQLiteLog: (1) table friends_table has no column named address
09-09 22:42:05.219 5846-5846/com.example.chris.mobileappsassignment E/SQLiteDatabase: Error inserting address=ffff lastname=ffff firstname=ffff age=ffff malefemale=ffff
android.database.sqlite.SQLiteException: table friends_table has no column named address (code 1): , while compiling: INSERT INTO friends_table(address,lastname,firstname,age,malefemale) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.chris.mobileappsassignment.DatabaseHelper.addData(DatabaseHelper.java:57) // ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends.AddData(friends.java:168) // ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends$1.onClick(friends.java:80) // ERROR SEEMS TO APPEAR HERE
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-09 22:42:05.223 5846-5846/com.example.chris.mobileappsassignment D/DatabaseHelper: addData: Adding Name to friends_table
09-09 22:42:05.223 5846-5846/com.example.chris.mobileappsassignment E/SQLiteLog: (1) table friends_table has no column named address
09-09 22:42:05.223 5846-5846/com.example.chris.mobileappsassignment E/SQLiteDatabase: Error inserting address=Name lastname=Name firstname=Name age=Name malefemale=Name
android.database.sqlite.SQLiteException: table friends_table has no column named address (code 1): , while compiling: INSERT INTO friends_table(address,lastname,firstname,age,malefemale) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.chris.mobileappsassignment.DatabaseHelper.addData(DatabaseHelper.java:57) // ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends.AddData(friends.java:168) // ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends$1.onClick(friends.java:87) // ERROR SEEMS TO APPEAR HERE
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-09 22:42:05.224 5846-5846/com.example.chris.mobileappsassignment D/DatabaseHelper: addData: Adding Name to friends_table
09-09 22:42:05.224 5846-5846/com.example.chris.mobileappsassignment E/SQLiteLog: (1) table friends_table has no column named address
09-09 22:42:05.224 5846-5846/com.example.chris.mobileappsassignment E/SQLiteDatabase: Error inserting address=Name lastname=Name firstname=Name age=Name malefemale=Name
android.database.sqlite.SQLiteException: table friends_table has no column named address (code 1): , while compiling: INSERT INTO friends_table(address,lastname,firstname,age,malefemale) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.chris.mobileappsassignment.DatabaseHelper.addData(DatabaseHelper.java:57) //ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends.AddData(friends.java:168) //ERROR SEEMS TO APPEAR HERE
at com.example.chris.mobileappsassignment.friends$1.onClick(friends.java:93) //ERROR SEEMS TO APPEAR HERE
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
如果答案尽可能简单,我仍然是初学者,那将会很棒!
任何帮助将不胜感激!谢谢!
答案 0 :(得分:1)
尝试将TEXT PRIMARY KEY更改为INTEGER PRIMARY KEY
k1 = 'AAA' and k2 = 'BBB' and c1 = '2017-09-05T16:09:00.222Z' and c2 = 'CCC'
OR
k1 = 'AAA' and k2 = 'BBB' and c1 = '2017-09-05T16:09:00.222Z' and c2 = 'XXX'
答案 1 :(得分:0)
根据日志,它说
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.chris.mobileappsassignment/com.example.chris.mobileappsassignment.friends}; have you declared this activity in your AndroidManifest.xml?
对主要节日进行评估,没有<activity android:name=".friends"></activity>
条目。
所以你需要改变: -
<activity android:name=".listdata"></activity>
<activity android:name=".EditDataActivity"></activity>
是
<activity android:name=".friends"></activity>
<activity android:name=".listdata"></activity>
<activity android:name=".EditDataActivity"></activity>
ID TEXT PRIMARY KEY AUTOINCREMENT
AUTOINCREMENT
只能用INTEGER PRIMARY KEY
编码,它会改变生成唯一rowid(长整数)的方式。 SQLite(除非您编写WITHOUT ROWID)始终创建一个唯一标识行的列。 AUTOINCREMENT说a)从不使用较低的数字或以前使用的数字,而没有。之前使用但可以使用的数字(非常不可能,因为你必须先达到9223372036854775807)。
将此更改为ID INTEGER PRIMARY KEY
或更好_id INTEGER PRIMARY KEY
原因是: -
AUTOINCREMENT
是一种特殊情况,您仍然可以使用INTEGER PRIMARY KEY
获取唯一标识符,但AUTOINCREMENT
的开销没有读取SQLite Autoincrement 以获取更多信息。 AUTOINCREMENT
只能使用INTEGER PRIMARY KEY进行编码
如果您对ListViews / Spinners使用CursorAdapters,则需要 _id 列。
对于后者,你会改变: -
super(context, TABLE_NAME, null, 1);
到
super(context, TABLE_NAME, null, 2);
日志包括: -
09-09 22:42:05.219 5846-5846/com.example.chris.mobileappsassignment E/SQLiteDatabase: Error inserting address=ffff lastname=ffff firstname=ffff age=ffff malefemale=ffff
android.database.sqlite.SQLiteException: table friends_table has no column named address (code 1): , while compiling: INSERT INTO friends_table(address,lastname,firstname,age,malefemale) VALUES (?,?,?,?,?)
这包括table friends_table has no column named address
虽然你有: -
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "friends_table";
private static final String COL1 = "firstname";
private static final String COL2 = "lastname";
private static final String COL3 = "malefemale";
private static final String COL4 = "age";
private static final String COL5 = "address";
然后使用以下命令创建表: -
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID TEXT PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT)";
这省略了许多列,而应该是: -
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY, " +
COL1 + " TEXT, " +
COL2 + " TEXT, " +
COL3 + " TEXT, " +
COL4 + " INTEGER, " +
COL5 + " TEXT)";
这样可行,但addData
方法可能不是你想要的。目前是: -
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//
//
contentValues.put(COL1, item);
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item);
contentValues.put(COL5, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted inorrectly it will return -1
if (result == 1)
return false;
else {
return true;
}
}
因此它会使所有值相同(这反映在日志中)。
应该是( was originally wrong now changed
): -
public boolean addData(String firstname, String lastname, String gender, integr age, String address) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//
//
contentValues.put(COL1, firstname);
contentValues.put(COL2, lastname);
contentValues.put(COL3, gender);
contentValues.put(COL4, age);
contentValues.put(COL5, address);
Log.d(TAG, "addData: Adding FirstName=" + firstname +
" LastName=" + lastname +
" Gender=" + gender +
" Age=" + Integer.toString(age) +
" Address=" + address +
" to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted inorrectly it will return -1
if (result == 1)
return false;
else {
return true;
}
}
但是,您还需要更改addData
使用addData(string_variable_with_name, string_variable_with_lastname, string_variable_with_gender, integer_variable_with_age, string_variable_with_address)
的任何地方
注意奇怪/长变量名称已被用于指示应该使用的内容(请参阅下面的实际用法)。
所以在 friends.java 而不是: -
addbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String firstName = firstnameinput.getText().toString();
String lastName = lastnameinput.getText().toString();
String age = ageinput.getText().toString();
String address= addressinput.getText().toString();
if (firstnameinput.length() !=0) {
AddData(firstName);
firstnameinput.setText("");
} else {
toastMessage("You must enter something in this field!");
}
if (lastnameinput.length() !=0) {
AddData(lastName);
lastnameinput.setText("");
} else {
toastMessage("You must enter something in this field!");
}
if (ageinput.length() !=0) {
AddData(age);
ageinput.setText("");
} else {
toastMessage("You must enter something in this field!");
}
if (addressinput.length() !=0) {
AddData(address);
addressinput.setText("");
} else {
toastMessage("You must enter something in this field!");
}
}
}); // end addbutton onclicklistener
你应该有类似的东西: -
addbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean addOK = true;
int age_as_int = -1;
String firstName = firstnameinput.getText().toString();
String lastName = lastnameinput.getText().toString();
String age = ageinput.getText().toString();
String address = addressinput.getText().toString();
if (firstName.length() < 1) {
toastMessage("You must enter something in this field!");
firstnameinput.requestFocus();
addOK = false;
}
if (lastName.length() < 1) {
toastMessage("You must enter something in this field!");
lastnameinput.requestFocus();
addOK = false;
}
if (age.length() < 1) {
toastMessage("You must enter something in this field!");
ageinput.requestFocus();
addOK = false;
}
if (address.length() != 0) {
toastMessage("You must enter something in this field!");
addressinput.requestFocus();
addOK = false;
}
try {
age_as_int = Integer.parseInt(age);
} catch (NumberFormatException e) {
toastMessage("You must enter a valid Number in this field!");
ageinput.requestFocus();
addOK = false;
}
if (addOK) {
addData(firstName,lastName,"????",age_as_int,address);
toastMessage("Friend Added!");
}
}
}); // end addbutton onclicklistener
最后更改: -
*// ADD DATA
public void AddData(String firstName, String lastName, String s, int age_as_int, String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Added!");
} else {
toastMessage("Something has gone wrong :(");
}
}*
要: -
// ADD DATA
public void AddData(String firstName, String lastName, String s, int age_as_int, String address) {
boolean insertData = mDatabaseHelper.addData(firstName, lastName, s,age_as_int, address);
if (insertData) {
toastMessage("Data Successfully Added!");
} else {
toastMessage("Something has gone wrong :(");
}
}
请注意!包括在//添加数据之前删除 *
,在最后 *
<之后删除 }
/ p>
请注意!在以下代码中,使用 addData
而不是 AddData
(即以小写字母a开头的那个是使用实际执行插入,在friends.java中以大写字母A开头的那个将不会被使用,因此可以删除它(AddData将显示为灰色,表示它未被使用))。 检查是否按使用小写版本: -
if (addOK) {
addData(firstName,lastName,"????",age_as_int,address); //<<<<<<<<<<<<
toastMessage("Friend Added!");
}
有很多变化,主要是使用addData
方法的更全面形式(插入时将整行添加到表中,因此您应该提供所有适用/已知值)。所以表中的1行等同于关于朋友的所有信息。
下一个主要的变化是只添加一行,所以只有1次调用AddData
一次,你的方式就是为每个有效字段添加一行,最后有多行,所有行都有相同的数据。
如果输入不正确,我已为输入项添加了requestFocus()
。这会将焦点(可能)移动到相应的字段。但是,最后一个错误的字段是焦点最终会出现的地方。您可以在 return;
之后添加addOK = false;
(或甚至替换addOK = false;
),然后会立即转到第一个无效(空)字段。
我添加了 addOK
,最初将其设置为true,任何无效字段都将其设置为false。
如果有任何错误,则不会调用addData
方法。
addOK 并且当输入字段无效时,如果您使用return;
替换所有addOk=false
,则会检查是否为真。< / p>
最后,我添加了一个年龄为有效数字的检查,同时将其转换为整数。同样,此设置 addOk 为false。