简体   繁体   English

将行插入SQLite数据库时Android App不会崩溃

[英]Android App not crashing when inserting row into SQLite database

Hi I'm new to Android development and am trying to make an app that takes a users first and last name, zip code, age and sex add them to a SQLite database and then display it on the next page. 嗨,我是Android开发的新手,正在尝试制作一个将用户的名字和姓氏,邮政编码,年龄和性别都添加到SQLite数据库中的应用程序,然后将其显示在下一页上。 I have tried many tutorial for this but have had little results. 我为此尝试了许多教程,但收效甚微。 After entering the data in the EditText, pressing the submit button causes the android to crash Any help would be appreciated. 在EditText中输入数据后,按下提交按钮会导致android崩溃。不胜感激。 This is my main activity where the user enters their data 这是我输入用户数据的主要活动

package com.example.votesmart;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class Zip extends Activity {

    private static final int TIME_ENTRY_REQUEST_CODE = 1;

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.zip, menu);
        return true;
    }

    public void onSubmit(View view){
        Intent intent = new Intent(this, EditProfile.class);
        startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);

        EditText firstView = (EditText)findViewById(R.id.fname_input);
        intent.putExtra("first", firstView.getText().toString());

        EditText lastView = (EditText)findViewById(R.id.lname_input);
        intent.putExtra("last", lastView.getText().toString());

        EditText zipView = (EditText)findViewById(R.id.zipcode_input);
        intent.putExtra("zip", zipView.getText().toString());

        EditText ageView = (EditText)findViewById(R.id.age_input);
        intent.putExtra("age", ageView.getText().toString());

        EditText sexView = (EditText)findViewById(R.id.sex_input);
        intent.putExtra("sex", sexView.getText().toString());
    }


}

its layout 其布局

<LinearLayout 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=".Zip"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="First Name" />

     <EditText
        android:id="@+id/fname_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Last Name" />

     <EditText
        android:id="@+id/lname_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Zip Code" />

    <EditText
        android:id="@+id/zipcode_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Age" />

     <EditText
        android:id="@+id/age_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

     <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Sex" />

     <EditText
        android:id="@+id/sex_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/submit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:onClick="onSubmit" />

</LinearLayout>

the next page to display the data 下一页显示数据

package com.example.votesmart;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class EditProfile extends Activity {
    VSAdapter vsAdapter;

    public static final int TIME_ENTRY_REQUEST_CODE = 1;
    private DatabaseHandler databaseHelper;
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_profile);

        databaseHelper = new DatabaseHandler(this);

        ListView listView = (ListView)findViewById(R.id.list);
        vsAdapter = new VSAdapter(this, databaseHelper.getAllRecords());
        listView.setAdapter(vsAdapter); 
    }

    public void onBack (View view){
        finish();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == TIME_ENTRY_REQUEST_CODE){
            if (resultCode == RESULT_OK){

                String first = data.getStringExtra("first");
                String last = data.getStringExtra("last");
                String zip = data.getStringExtra("zip");
                String age = data.getStringExtra("age");
                String sex = data.getStringExtra("sex");

                databaseHelper.addVoter(first, last, zip, age, sex);
                //vsAdapter.changeCursor(databaseHelper.getAllRecords());

                //databaseHelper.addVoter(first, last, zip, age, sex);

            }
            }
        }
    }

my adapter 我的适配器

package com.example.votesmart;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class VSAdapter extends CursorAdapter {

    public VSAdapter(Context context, Cursor cursor){
        super(context, cursor);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // TODO Auto-generated method stub
        TextView nameTextView = (TextView) view.findViewById(R.id.first_view);
        nameTextView.setText(cursor.getString(cursor.getColumnIndex("1")));
        TextView lastTextView = (TextView) view.findViewById(R.id.last_view);
        lastTextView.setText(cursor.getString(cursor.getColumnIndex("2")));
        TextView zipTextView = (TextView) view.findViewById(R.id.zip_view);
        zipTextView.setText(cursor.getString(cursor.getColumnIndex("3")));
        TextView ageTextView = (TextView) view.findViewById(R.id.age_view);
        ageTextView.setText(cursor.getString(cursor.getColumnIndex("4")));
        TextView sexTextView = (TextView) view.findViewById(R.id.sex_view);
        sexTextView.setText(cursor.getString(cursor.getColumnIndex("5")));
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.zip_list_item,  parent, false);


        return view;
    }

}
and finally my database class
private class DatabaseOpenHelper extends SQLiteOpenHelper{
        DatabaseOpenHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            String CREATE_VOTERS_TABLE = "create table " + TABLE_NAME + "(" + KEY_ID + " integer primary key, " + KEY_FIRST + " text," + KEY_LAST + " text," + KEY_ZIP + " text," + KEY_AGE + " text," + KEY_SEX + "text" ;
            db.execSQL(
                    CREATE_VOTERS_TABLE
                    );
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

        public void addVoter(String first, String last, String zip, String age, String sex){
            //public void addVoter{Voter voter){
            ContentValues values = new ContentValues();
            values.put(KEY_FIRST, first);
            values.put(KEY_LAST, last);
            values.put(KEY_ZIP, zip);
            values.put(KEY_AGE, age);
            values.put(KEY_SEX, sex);

            db.insert(TABLE_NAME, null, values);

                //return db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[] {String.valueOf(voter.getId()) });
            }
        public Cursor getAllRecords(){
            return db.rawQuery(
                    "select * from " + TABLE_NAME,
                    null
                    );
        }
}

Once again any help is greatly appreciated, Thanks! 再次感谢您的任何帮助,谢谢!

There are a few issues with this, 这有一些问题,

public void onSubmit(View view){
        Intent intent = new Intent(this, EditProfile.class);


        EditText firstView = (EditText)findViewById(R.id.fname_input);
        intent.putExtra("first", firstView.getText().toString());

        EditText lastView = (EditText)findViewById(R.id.lname_input);
        intent.putExtra("last", lastView.getText().toString());

        EditText zipView = (EditText)findViewById(R.id.zipcode_input);
        intent.putExtra("zip", zipView.getText().toString());

        EditText ageView = (EditText)findViewById(R.id.age_input);
        intent.putExtra("age", ageView.getText().toString());

        EditText sexView = (EditText)findViewById(R.id.sex_input);
        intent.putExtra("sex", sexView.getText().toString());
        startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
    }

You need to add the data before sending it. 您需要先添加数据,然后再发送数据。 The method in which you are using onActivityResult is also wrong, 您使用onActivityResult的方法也是错误的,

In your oncreate method of the EditProfile class, put the following 在EditProfile类的oncreate方法中,放入以下内容

Intent data = getIntent().getExtras();

String first = data.getStringExtra("first");
String last = data.getStringExtra("last");
String zip = data.getStringExtra("zip");
String age = data.getStringExtra("age");
String sex = data.getStringExtra("sex");

databaseHelper.addVoter(first, last, zip, age, sex); databaseHelper.addVoter(first,last,zip,age,sex);

Ideally this should be on a thread but yeah. 理想情况下,这应该在线程上,但是。

In this block of code: 在此代码块中:

public void onSubmit(View view){
        Intent intent = new Intent(this, EditProfile.class);
        startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);

you are starting your activity in the 3rd line, but then after that you are "adding data" to the intent... the intent was consumed with "startActivity". 您在第三行开始活动,但是之后您将“添加数据”到该意图中……该意图已被“ startActivity”消耗。 Put that at the bottom of that block. 将其放在该块的底部。

And you don't get the intent data in the other Activity's "onResult" - that is where you set the activity's results before you destroy it. 而且,您不会在另一个活动的“ onResult”中获得意图数据-在销毁活动之前,您要在其中设置活动的结果。 The intent data collected needs be before the activity is displayed - onCreate, onStart or onResume. 收集的意图数据需要在显示活动之前-onCreate,onStart或onResume。 OnCreate will do it once. OnCreate将执行一次。 The others are for situations where you might want to recycle the activity (like add another voter after it has already started). 其他选项则用于您可能希望回收活动的情况(例如在启动后添加另一个选民)。 But you need to check for dupes. 但是您需要检查是否有欺骗。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM