我是Android开发的新手,在这里我尝试使用sqlite创建一个简单的数据库应用程序 我想要做的是当用户选择搜索它将要求id并且匹配id的相应数据应该替换该特定数据的editText字段
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ashish.project.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Personal Details"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/gridLayout"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_row="0"
android:layout_column="0">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText"
android:layout_weight="1"
android:hint="First Name" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText_LastName"
android:layout_weight="1"
android:hint="Last Name" />
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/editText_number"
android:layout_row="1"
android:layout_column="0"
android:hint="Contact Number" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/editText_email"
android:layout_row="2"
android:layout_column="0"
android:hint="E-mail" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_row="3"
android:layout_column="0">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit Details"
android:id="@+id/Button_Submit"
android:layout_weight="1"
android:layout_row="4"
android:layout_column="0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Details"
android:id="@+id/button_Show_Details"
android:layout_gravity="right"
android:layout_weight="1"
android:layout_row="5"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_search"
android:layout_below="@id/Button_Submit"
android:text="search"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Table"
android:id="@+id/button_clear"
android:gravity="left|center_horizontal"
android:layout_below="@+id/button_Show_Details"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</GridLayout>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/editText_srch"
android:hint="Enter id to search"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="search"
android:id="@+id/button_show_id_result"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
MainActivity.java
package com.example.ashish.project;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button_submit,button_show_details,button_clear,button_search,button_show_id_result;
EditText firstName,lastName,number,email,editText_id_search;
String firstnameString,lastnameString,emailString,num;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_submit=(Button)findViewById(R.id.Button_Submit);
button_show_id_result=(Button) findViewById(R.id.button_show_id_result);
editText_id_search=(EditText) findViewById(R.id.editText_srch);
button_show_details=(Button)findViewById(R.id.button_Show_Details);
firstName=(EditText)findViewById(R.id.editText);
button_search=(Button) findViewById(R.id.button_search);
button_clear=(Button)findViewById(R.id.button_clear);
lastName=(EditText)findViewById(R.id.editText_LastName);
number=(EditText)findViewById(R.id.editText_number);
email=(EditText)findViewById(R.id.editText_email);
editText_id_search.setVisibility(View.GONE);
button_show_id_result.setVisibility(View.GONE);
button_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
db.clear();
}
});
button_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*
*/
editText_id_search.setVisibility(View.VISIBLE);
button_show_id_result.setVisibility(View.VISIBLE);
button_show_id_result.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String qry = editText_id_search.getText().toString();
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
db.search(qry);
}
});
}
});
button_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
firstnameString = firstName.getText().toString();
lastnameString=lastName.getText().toString();
num=number.getText().toString();
emailString=email.getText().toString();
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
db.insertData(firstnameString,lastnameString,num,emailString);
Toast.makeText(MainActivity.this,"Record Updated",Toast.LENGTH_LONG).show();
InputMethodManager input = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(email.getWindowToken(),0);
firstName.setText("");
lastName.setText("");
number.setText("");
email.setText("");
db.close();
}
});
button_show_details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,List_Result.class);
startActivity(i);
}
});
}
public void show(String string, String cString, String s, String string1) {
firstName.setText(string);
lastName.setText(cString);
number.setText(s);
email.setText(string1);
}
}
DatabaseHelper.java
package com.example.ashish.project;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by ashis on 7/21/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static int DATABASE_VERSION = 6;
private static String DATABSE_NAME="DATA";
private static String TABLE_NAME="PERSONAL_INFORMATION";
private static String COLLUMN_ID= "_ID";
private static String COLLUMN_FIRST_NAME="FIRST_NAME";
private static String COLLUMN_LAST_NAME="LAST_NAME";
private static String COLLUMN_NUMBER = "NUMBER";
private static String COLLUMN_EMAIL="EMAIL";
public DatabaseHelper(Context context)
{
super(context,DATABSE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME + "( "
+ COLLUMN_ID +" INTEGER PRIMARY KEY, "
+ COLLUMN_FIRST_NAME + " TEXT, "
+ COLLUMN_LAST_NAME + " TEXT, "
+ COLLUMN_NUMBER + " TEXT , "
+ COLLUMN_EMAIL + " TEXT"+" )";
sqLiteDatabase.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
this.onCreate(sqLiteDatabase);
}
public void insertData(String firstnameString, String lastnameString, String num, String emailString) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLLUMN_FIRST_NAME,firstnameString);
values.put(COLLUMN_LAST_NAME,lastnameString);
values.put(COLLUMN_NUMBER,num);
values.put(COLLUMN_EMAIL,emailString);
db.insertOrThrow(TABLE_NAME,null,values);
db.close();
}
public ArrayList<String> readData() {
ArrayList<String> list = new ArrayList<>();
String readQry = "SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(readQry,null);
if (c.moveToFirst())
{
do {
list.add(c.getString(0)+ ": "+c.getString(1) +" "+ c.getString(2)+","+c.getString(3)+","+c.getString(4));
}while (c.moveToNext());
}
c.close();
db.close();
return list;
}
public void clear() {
SQLiteDatabase db= this.getWritableDatabase();
String clrqry = "DROP TABLE " + TABLE_NAME;
db.execSQL(clrqry);
this.onCreate(db);
}
public void search(String srch) {
SQLiteDatabase db = this.getReadableDatabase();
MainActivity obj = new MainActivity();
String sqlqry = "SELECT * FROM "+TABLE_NAME +" WHERE "+ COLLUMN_ID + " = ?";
Cursor c= db.rawQuery(sqlqry,new String[]{srch});
if (c.moveToFirst())
{
do {
obj.show(c.getString(1),c.getString(2),c.getString(3),c.getString(4));
}
while (c.moveToNext());
}
}
}
Activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ashish.project.List_Result">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@android:color/darker_gray" />
</RelativeLayout>
Activity_list.java
package com.example.ashish.project;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class List_Result extends AppCompatActivity {
ListView listview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list__result);
listview1=(ListView) findViewById(R.id.listView2);
loadlistviewData();
}
private void loadlistviewData() {
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
ArrayList<String> list = db.readData();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,list);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
listview1.setAdapter(adapter);
}
}
这是我输入id
后点击搜索时的logcat07-25 14:27:34.033 668-668/com.example.ashish.project W/System: ClassLoader referenced unknown path: /data/app/com.example.ashish.project-2/lib/arm
07-25 14:27:34.256 668-668/com.example.ashish.project W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-25 14:27:34.541 668-668/com.example.ashish.project D/android.widget.GridLayout: vertical constraints: y4-y0>=864, y4-y3<=192, y3-y2<=91, y2-y1<=91, y1-y0<=100 are inconsistent; permanently removing: y4-y3<=192.
07-25 14:27:39.235 668-668/com.example.ashish.project D/AndroidRuntime: Shutting down VM
07-25 14:27:39.236 668-668/com.example.ashish.project E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ashish.project, PID: 668
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.example.ashish.project.MainActivity.show(MainActivity.java:103)
at com.example.ashish.project.DatabaseHelper.search(DatabaseHelper.java:108)
at com.example.ashish.project.MainActivity$2$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
任何帮助将不胜感激
答案 0 :(得分:0)
您可以通过创建新的MainActivity实例来调用 show()。因此,MainActivity的所有变量都将为null。最好你应该使这些静态,以便所有MainActivity实例的初始化相同。尝试
static EditText firstName,lastName,number,email,editText_id_search;
答案 1 :(得分:0)
不要在View小部件中使用静态。
将DatabaseHelper.java中的搜索功能替换为下面的一个:
public void search(String srch, MainActivity activity) {
SQLiteDatabase db = this.getReadableDatabase();
String sqlqry = "SELECT * FROM "+TABLE_NAME +" WHERE "+ COLLUMN_ID + " = ?";
Cursor c= db.rawQuery(sqlqry,new String[]{srch});
if (c.moveToFirst())
{
do {
activity.show(c.getString(1),c.getString(2),c.getString(3),c.getString(4));
}
while (c.moveToNext());
}
}
在MainActivity.java中,替换如下:
db.search(qry);
使用:
db.search(qry, MainActivity.this);
答案 2 :(得分:-1)
只需尝试包装即可解决问题。