我正在尝试在android studio中做一个应用。用户可以给出他的名字和姓氏年龄。 id是自动增量。用户提交的数据被插入到数据库中!当用户使用他的名字(从数据库中检索他提交的数据)的权限时,数据库将返回一些数据,但是这些数据未在表布局中显示。我在logcat中看到,每次我搜索数据库时,在db,游标和do的搜索方法中都运行2次,尽管我只插入了一个名字一次。
FirstActivity:
EditText editText4 =null;
String text_4 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity_main);
Button button2 = findViewById(R.id.Button_2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText4 = findViewById(R.id.Edit_text_4);
text_4 = editText4.getText().toString();
editText4.setText("");
if (text_4.isEmpty()) { //if search field is empty notify the user
// Toast.makeText(FirstActivity.this, "Search field is empty!", Toast.LENGTH_SHORT).show();
editText4.setError("Missing search field!");
} else { // if search field is not empty , search into db , if a result is found, go to 2nd activity
search_into_db_and_go_to2nd_activity_for_results();
}
}
});
}
protected void search_into_db_and_go_to2nd_activity_for_results() {
DBHelper info = new DBHelper(FirstActivity.this);
DBHelper dbHelper = new DBHelper(FirstActivity.this);
if (info.readData(dbHelper, text_4, FirstActivity.this).isEmpty()) {
Toast.makeText(FirstActivity.this, "The db did not return anything!", Toast.LENGTH_SHORT).show();
} else {
myitems.clear();
try {
myitems = info.readData(dbHelper, text_4, FirstActivity.this);
} catch (Exception e) {
Toast.makeText(FirstActivity.this, "error on getting data!", Toast.LENGTH_SHORT).show();
}
try { //????????????
info.close();
dbHelper.close();
} catch (Exception e) {
e.getStackTrace();
Log.d(TAG, "info close ", e);
}
Bundle bundle = new Bundle(); //create a Bundle object
try{
bundle.putSerializable("arraylist", (Serializable) myitems);
Intent intent = new Intent();
intent.setClassName("com.example.dit.hua.ergasia.firstactivity", "com.example.dit.hua.ergasia.firstactivity.SecondActivity");
intent.putExtra("data", bundle);
//myitems.clear();
startActivity(intent);
} catch (Exception e) {
e.getStackTrace();
Log.d(TAG, "intent ", e);
}
}
}
}
DataContract:
import java.io.Serializable;
public class DataContract implements Serializable {
//One of the main principles of SQL databases is the schema: a formal declaration of how the database is organized.
// The schema is reflected in the SQL statements that I use to create my database.
// This class is a companion class, known as a contract class, which explicitly specifies the layout of my schema in a systematic and self-documenting way.
int id;
String id1;
String lname;
String fname;
int age;
public DataContract() { //default constructor
}
public DataContract(int id, String lname, String fname, int age) {
this.id = id;
this.lname = lname;
this.fname = fname;
this.age = age;
}
public DataContract(String fname, String lname, int age) {
this.fname = fname;
this.lname = lname;
this.age = age;
}
//setters and getters
public int getAge() {
return age;
}
public String getFname() {
return fname;
}
public int getId() {
return id;
}
public String getLname() {
return lname;
}
public void setAge(int age) {
this.age = age;
}
public void setFname(String fname) {
this.fname = fname;
}
public void setId(int id) {
this.id = id;
}
public void setLname(String lname) {
this.lname = lname;
}
}
DBHelper
public class DBHelper extends SQLiteOpenHelper implements BaseColumns, Serializable {
public ArrayList<DataContract> readData (DBHelper dbhelper, String searchfield, Context context){ //ArrayList<String> List ArrayList<DataContract>
//To access the database, I need to instantiate my subclass of SQLiteOpenHelper:
// FeedReaderDbHelper dbHelper = new FeedReaderDbHelper(FeedReaderContract.this); //αντι για static Context getContext() Return the Context of this instrumentation's package.
SQLiteDatabase db = dbhelper.getReadableDatabase();
ArrayList<DataContract> myitems_dbHelper = new ArrayList<DataContract>();
try {
if (cursor.moveToFirst()) {
Log.e(TAG, "cursor inserted 1st if - curosr moved to first ");
if(cursor != null && cursor.getCount() > 0){//if (cursor != null) { //&& cursor.moveToFirst()
Log.e(TAG, "cursor inserted 2nd if - curosr not null ");
//myitems_dbHelper.clear();
do{
//while (cursor.moveToNext()) {
datacontract.setId(cursor.getInt(0)); //id
Log.i(TAG, "DBHelper -see inside cursor " + cursor.getInt(0));
datacontract.setFname(cursor.getString(1)); //fname
Log.i(TAG, "DBHelper -see inside cursor " + cursor.getString(1));
datacontract.setLname(cursor.getString(2)); //lname
Log.i(TAG, "DBHelper -see inside cursor " + cursor.getString(2));
datacontract.setAge(cursor.getInt(3)); //age
Log.i(TAG, "DBHelper -see inside cursor " + cursor.getInt(3));
myitems_dbHelper.add(datacontract);
}while (cursor.moveToNext());
}
} else {
//Toast.makeText(context, "cursor empty", Toast.LENGTH_LONG).show();
Log.e(TAG, "CURSOR NULL ");
}
}catch(Exception e){
Log.e(TAG, "DB HELPER CURSOR EMPTY ");
}
finally {
if (cursor != null && !cursor.isClosed())
cursor.close(); //close cursor to avoid memery leaking
Log.e(TAG, "finally ");
}
return myitems_dbHelper ;
}
}
// When reading data one should always just get a readable database.
//final SQLiteDatabase database = this.getReadableDatabase();
String[] projection = { // Define a projection that specifies which columns from the database you will actually use after this query.
BaseColumns._ID, //BaseColumns._ID, DBHelper._ID
DBHelper.FIRST_NAME,
DBHelper.LAST_NAME,
DBHelper.AGE
};
// Filter results WHERE "fname" = 'Myname'
String selection = DBHelper.FIRST_NAME + " = ?";
String[] selectionArgs = { searchfield };
//To read from a database, use the query() method, passing it your selection criteria and desired columns
//The results of the query are returned to you in a Cursor object.
Cursor cursor = null;
try {
Log.e(TAG, "DB HELPER before QUERY ");
cursor = db.query(
DBHelper.DB_NAME, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null); // The sort order
}catch(Exception e){
e.getStackTrace();
e.getMessage();
//Log.d(TAG, "DB HELPER CURSOR DB QUERY ", e);
e.getCause();
Thread.dumpStack();
}finally {
Log.e(TAG, "DB HELPER CURSOR DB QUERY ");
}
SecondActivity
Context context = SecondActivity.this;
TableLayout table_lay_out_result = null;
int id = 0;
String fname = null;
String lname = null;
int age = 0;
ArrayList<DataContract> myitems_recover = new ArrayList<DataContract> ();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
show_results_in_table_lay_out() ;
}
private void show_results_in_table_lay_out() { //retrieve the results that the 1st activity sent to the 2nd , and show it to the table lay out
table_lay_out_result = (TableLayout) findViewById(R.id.table_lay_out);
Intent myintent = getIntent();
Bundle b = myintent.getBundleExtra("data");
//myitems_recover.clear();
try {
myitems_recover = (ArrayList<DataContract>) b.getSerializable("arraylist");
} catch (Exception e) {
// Log.d(TAG, "SECOND ACTIVITY TABLE ROW", e);
// e.getStackTrace();
// e.getCause();
}
if (!(myitems_recover.isEmpty())) { // if(b!=null) {
try {
for (int i = 0; i < myitems_recover.size(); i++) { //ERROR!!
id = (int) myitems_recover.get(i).getId();
fname = (String) myitems_recover.get(i).getFname();
lname = (String) myitems_recover.get(i).getLname();
age = (int) myitems_recover.get(i).getAge();
// Create a new table row.
TableRow tableRow = new TableRow(context);
// Set new table row layout parameters.
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
tableRow.setLayoutParams(layoutParams);
// Add a TextView in the first column.
TextView textView1 = new TextView(context);
String str = String.valueOf(id);
textView1.setText(str);
tableRow.addView(textView1, 0);
// Add a TextView in the second column
TextView textView2 = new TextView(context);
textView2.setText(fname);
tableRow.addView(textView2, 1);
// Add a TextView in the third column.
TextView textView3 = new TextView(context);
textView3.setText(lname);
tableRow.addView(textView3, 2);
// Add a TextView in the fourth column.
TextView textView4 = new TextView(context);
String str_Age = String.valueOf(age);
textView4.setText(str_Age);
tableRow.addView(textView4, R.id.row1_text_view4); //3
if (tableRow.getParent() != null)
((TableLayout) tableRow.getParent()).removeView(tableRow);
table_lay_out_result.addView(tableRow);
}
myitems_recover.clear();
} catch (Exception e) {
Log.d(TAG, "SECOND ACTIVITY TABLE ROW", e);
}
} else {
Toast.makeText(SecondActivity.this, "string was null", Toast.LENGTH_SHORT).show();
}
}
我真的是使用android的新程序。任何解决我的问题的帮助将不胜感激我在databse表和insert方法中的creat工作得很好。这就是为什么我也没有发布它们的原因。
@@ Quark @Stan @sth @Minolan @AndroidDebaser @Lukas Knuth @ SBerg413 @Nikola Despotoski @ prolink007 @Fantômas@vikas kumar也许您可以帮忙!