单击已编码为保存,刷新和搜索的按钮时,应用程序停止工作

时间:2019-03-06 23:27:38

标签: java android xml

我需要一些3个无法正常使用的按钮来解决问题,我不确定如何解决。 “保存”按钮用于保存我的数据库,“刷新”按钮用于清除,“搜索”按钮用于查找现有数据库。我的TextView显示注册后的现有数据库。这些是我要实现的目标。

这是我的代码文件:

XML文件:  activity_main:

        <?xml version="1.0" encoding="utf-8"?>
        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            xmlns:tools="http://schemas.android.com/tools"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_verticsl_margin"
            android:paddingBottom="@dimen/activity_verticsl_margin"
            tools:context=".MainActivity">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="30dip"
                android:gravity="center"
                android:text="Registration"/>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:weightSum="1">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtid"
                    android:hint="ID"
                    android:inputType="number"
                    android:layout_marginTop="5dip"
                    />
                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtfirstname"
                    android:hint="@string/first_name"
                    android:layout_marginTop="5dip"
                    />
                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtlastname"
                    android:hint="@string/last_name"
                    android:layout_marginTop="5dip"
                    />            
                <EditText
                    android:id="@+id/txtmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dip"
                    android:hint="@string/e_mail" />
                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtuser"
                    android:hint="@string/username"
                    android:layout_marginTop="5dip"/>
                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtpw"
                    android:hint="@string/password"
                    android:layout_marginTop="5dip"/>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <Button
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="save"
                        android:textColor="#fff"
                        android:textSize="15dip"
                        android:id="@+id/btnsave"
                        android:layout_weight="1"
                        android:layout_gravity="center_horizontal"/>

                    <Button
                        android:id="@+id/btnclear"
                        android:layout_width="212dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_weight=".30"
                        android:text="refresh"
                        android:textColor="#fff"
                        android:textSize="15dip"/>

                    <Button
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="search"
                        android:textColor="#fff"
                        android:textSize="15dip"
                        android:id="@+id/btnsearch"
                        android:layout_weight="1"
                        android:layout_gravity="center_horizontal"/>                        
                </LinearLayout>

            </LinearLayout>            

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="New Text"
                android:id="@+id/textView"/>

        </TableLayout>

Java文件StudentRegistration.java

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

        public class StudentRegistration {

            public static final String KEY_ROWID ="_id";
            public static final String KEY_FNAME = "fname";
            public static final String KEY_LNAME = "lname";
            public static final String KEY_EMAIL = "email";
            public static final String KEY_USER ="user";
            public static final String KEY_PASS ="pass";

            private static final String DATABASE_NAME = "StudentDB";
            private static final String DATABASE_TABLE = "StudentTbl";
            private static final int DATABASE_VERSION = 1;

            private DBHelper ourHelper;
            private final Context ourContext;
            private SQLiteDatabase ourDatabase;

            private static class DBHelper extends SQLiteOpenHelper {

                public DBHelper(Context context) {
                    super(context, DATABASE_NAME,
                            null, DATABASE_VERSION);
                }
                @Override
                public void onCreate(SQLiteDatabase db) {
                    db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                            KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                            KEY_FNAME + " TEXT NOT NULL, " +
                            KEY_LNAME + " TEXT NOT NULL, " +
                            KEY_EMAIL + " TEXT NOT NULL, " +
                            KEY_USER + " TEXT NOT NULL, " +
                            KEY_PASS + " TEXT NOT NULL);");
                }

                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

                    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
                    onCreate(db);

                }
            }
            public StudentRegistration(Context c) {
                ourContext = c;
            }
            public StudentRegistration open() {
                ourHelper = new DBHelper(ourContext);
                ourDatabase = ourHelper.getWritableDatabase();
                return this;
            }
            public void close() {
                ourHelper.close();
            }
            public long savedata(String fname, String lname, String email, String user, String pass) {
                ContentValues cv = new ContentValues();
                cv.put(KEY_FNAME, fname);
                cv.put(KEY_LNAME, lname);
                cv.put(KEY_EMAIL, email);
                cv.put(KEY_USER, user);
                cv.put(KEY_PASS, pass);
                return ourDatabase.insert(DATABASE_TABLE, null, cv);            
            }

            public String getData(){
                String[] refresh = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_EMAIL, KEY_USER, KEY_PASS};
                Cursor c = ourDatabase.query(DATABASE_TABLE, refresh, null, null, null, null, null);
                String result = "";

                int iRow = c.getColumnIndex(KEY_ROWID);
                int iFName = c.getColumnIndex(KEY_FNAME);
                int iLName = c.getColumnIndex(KEY_LNAME);
                int iEmail = c.getColumnIndex(KEY_EMAIL);
                int iUser = c.getColumnIndex(KEY_USER);
                int iPass = c.getColumnIndex(KEY_PASS);

                for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
                    result = result + c.getString(iRow)
                            + " " + c.getString(iFName)
                            + " " + c.getString(iLName)
                            + " " + c.getString(iEmail)
                            + " " + c.getString(iUser)
                            + " " + c.getString(iPass)
                            + "\n\n";            
                }

                return result;            
            }

            public String getFName(long l){
                String[] getfname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
                        KEY_EMAIL, KEY_USER, KEY_PASS};
                Cursor c = ourDatabase.query(DATABASE_TABLE, getfname, KEY_ROWID + "="
                        + 1, null, null, null, null);

                if(c != null){
                    c.moveToFirst();
                    String fname = c.getString(1);
                    return fname;
                }

                return null;
            }
            public String getLName(long l){

                String[] getlname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
                        KEY_EMAIL, KEY_USER, KEY_PASS};
                Cursor c = ourDatabase.query(DATABASE_TABLE, getlname, KEY_ROWID + "="
                        + 1, null, null, null, null);

                if(c != null){
                    c.moveToFirst();
                    String lname = c.getString(2);
                    return lname;
                }
                return null;
            }
            public String getEmail(long l){
                String[] getemail = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
                        KEY_EMAIL, KEY_USER, KEY_PASS};
                Cursor c = ourDatabase.query(DATABASE_TABLE, getemail, KEY_ROWID + "="
                        + 1, null, null, null, null);

                if(c != null){
                    c.moveToFirst();
                    String email = c.getString(3);
                    return email;
                }
                return null;
            }
            public String getUser(long l){
                String[] getuser = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
                        KEY_EMAIL, KEY_USER, KEY_PASS};
                Cursor c = ourDatabase.query(DATABASE_TABLE, getuser, KEY_ROWID + "="
                        + 1, null, null, null, null);

                if(c != null){
                    c.moveToFirst();
                    String user = c.getString(4);
                    return user;
                }
                return null;
            }
            public String getPass(long l){
                String[] getpass = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
                        KEY_EMAIL, KEY_USER, KEY_PASS};
                Cursor c = ourDatabase.query(DATABASE_TABLE, getpass, KEY_ROWID + "="
                        + 1, null, null, null, null);

                if(c != null){
                    c.moveToFirst();
                    String pass = c.getString(5);
                    return pass;
                }
                return null;
            }

        }

和Java文件MainActivity:

        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;

        public class MainActivity extends AppCompatActivity {

            EditText FirstName, LastName, Email, UserName, Password, ID;
            Button Save, Clear, Search;
            TextView TxtData;

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

                FirstName = (EditText)findViewById(R.id.txtfirstname);
                LastName = (EditText)findViewById(R.id.txtlastname);
                Email = (EditText)findViewById(R.id.txtmail);
                UserName = (EditText)findViewById(R.id.txtuser);
                Password = (EditText)findViewById(R.id.txtpw);
                TxtData =(TextView)findViewById(R.id.textView);

                Save =(Button)findViewById(R.id.btnsave);
                Clear=(Button)findViewById(R.id.btnclear);
                Search=(Button)findViewById(R.id.btnsearch);

                Search.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        String search = ID.getText().toString();
                        Long l= Long.parseLong(search);

                        StudentRegistration mysearch = new
                                StudentRegistration(MainActivity.this);
                        mysearch.open();
                        String returnedFname = mysearch.getFName(l);
                        String returnedLname = mysearch.getLName(l);
                        String returnedEmail = mysearch.getEmail(l);
                        String returnedUser = mysearch.getUser(l);
                        String returnedPass = mysearch.getPass(l);
                        mysearch.close();

                        FirstName.setText(returnedFname);
                        LastName.setText(returnedLname);
                        Email.setText(returnedEmail);
                        UserName.setText(returnedUser);
                        Password.setText(returnedPass);            
                    }
                });

                Save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {            

                            String fname = FirstName.getText().toString();
                            String lname = LastName.getText().toString();
                            String email = Email.getText().toString();
                            String user = UserName.getText().toString();
                            String pass = Password.getText().toString();

                            StudentRegistration save = new StudentRegistration(MainActivity.this);
                            save.open();
                           save.savedata(fname, lname, email, user, pass);

                        FirstName.setText("");
                        LastName.setText("");
                        Email.setText("");
                        UserName.setText("");
                        Password.setText("");
                        ID.setText("");
                        }            
                });

                Clear.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v){
                        StudentRegistration refresh = new StudentRegistration(MainActivity.this);
                        refresh.open();

                        String data = refresh.getData();
                        refresh.close();
                        TxtData.setText(data);

                        FirstName.setText("");
                        LastName.setText("");
                        Email.setText("");
                        UserName.setText("");
                        Password.setText("");
                        ID.setText("");

                    }
                });
            }
        }

我的清单文件:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.classifiedinformation">

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">

                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

        </application>

我如何实现我的目标?

2 个答案:

答案 0 :(得分:0)

首先,关于发生问题的一些提示会很好。

您需要像使用其他EditText一样初始化ID。
ID = findViewById(R.id.txtid);添加到您的onCreate(Bundle savedInstanceState)方法中。

点击“保存”时,我得到的第一件事是:

   java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
    at com.citiesapps.myapplication.MainActivity$2.onClick(MainActivity.java:76)
    at android.view.View.performClick(View.java:5610)
    at android.view.View$PerformClick.run(View.java:22265)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

作为stacktrace的状态,您试图在这种情况下的“ ID”上调用空对象上的方法。

答案 1 :(得分:0)

分析您的代码后,我看到您正在对未在Java类中初始化的editText执行 setText

可能的editText代码为

ID.setText("");此处的ID未使用xml文件初始化。

使用ID = findViewById(R.id.txtid);初始化ID字段

检查所有editText初始化。然后使用该editText。

谢谢:)