Android Studio E / AndroidRuntime:FATAL EXCEPTION:main

时间:2017-03-05 06:58:28

标签: java android nullpointerexception

在我修改这些点击侦听器之后出现了这个错误

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.apple.sqlite, PID: 31591
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apple.sqlite/com.example.apple.sqlite.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setKeyListener(android.text.method.KeyListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setKeyListener(android.text.method.KeyListener)' on a null object reference
at com.example.apple.sqlite.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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)

MainActivity.java代码

package com.example.apple.sqlite;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Calendar calendar;
private TextView dateView;
private int year, month, day;

private ListView obj;
DBHelper mydb;

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

    mydb = new DBHelper(this);
    ArrayList array_list = mydb.getAllCotacts();
    ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);

    dateView = (TextView) findViewById(R.id.SQDate);
    dateView.setKeyListener(null);
    Button dateButton = (Button)findViewById(R.id.DateButton);
    calendar = Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);
    showDate(year, month+1, day);

    dateButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            final Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day = c.get(Calendar.DAY_OF_MONTH);
            new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    String format = getString(R.string.setdate) + setDateFormat(year,month,day);
                    dateView.setText(format);
                }

            }, year,month, day).show();
        }

    });

    obj = (ListView)findViewById(R.id.listView1);
    obj.setAdapter(arrayAdapter);
    obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            // TODO Auto-generated method stub
            int id_To_Search = arg2 + 1;

            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", id_To_Search);

            Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });
}



private String setDateFormat(int year,int monthOfYear,int dayOfMonth){
    return String.valueOf(year) + "-"
            + String.valueOf(monthOfYear + 1) + "-"
            + String.valueOf(dayOfMonth);
}

public void setDate(View view) {
    showDialog(999);
    Toast.makeText(getApplicationContext(), "ca",
            Toast.LENGTH_SHORT)
            .show();
}

protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    if (id == 999) {
        return new DatePickerDialog(this,
                myDateListener, year, month, day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener myDateListener = new
        DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker arg0,
                                  int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
                // arg1 = year
                // arg2 = month
                // arg3 = day
                showDate(arg1, arg2+1, arg3);
            }
        };

private void showDate(int year, int month, int day) {
    dateView.setText(new StringBuilder().append(year).append("-")
            .append(month).append("-").append(day));
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item){
    super.onOptionsItemSelected(item);

    switch(item.getItemId()) {
        case R.id.item1:Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", 0);

            Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
            intent.putExtras(dataBundle);

            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
    }
}

DisplayContact.java代码

package com.example.apple.sqlite;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Apple on 2017/3/5.
 */

public class DisplayContact extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;

TextView date ;
TextView item;
TextView describe;
TextView money;
int id_To_Update = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_contact);
    date = (TextView) findViewById(R.id.SQDate);
    item = (TextView) findViewById(R.id.SQItem);
    describe = (TextView) findViewById(R.id.SQDescribe);
    money = (TextView) findViewById(R.id.SQMoney);

    mydb = new DBHelper(this);

    Bundle extras = getIntent().getExtras();
    if(extras !=null) {
        int Value = extras.getInt("id");

        if(Value>0){
            //means this is the view part not the add contact part.
            Cursor rs = mydb.getData(Value);
            id_To_Update = Value;
            rs.moveToFirst();

            String xdate = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_DATE));
            String xitem = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_ITEM));
            String xdescribe = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_DESCRIBE));
            String xmoney = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_MONEY));

            if (!rs.isClosed())  {
                rs.close();
            }
            Button b = (Button)findViewById(R.id.EnterButton);
            b.setVisibility(View.INVISIBLE);

            date.setText((CharSequence)xdate);
            date.setFocusable(false);
            date.setClickable(false);

            item.setText((CharSequence)xitem);
            item.setFocusable(false);
            item.setClickable(false);

            describe.setText((CharSequence)xdescribe);
            describe.setFocusable(false);
            describe.setClickable(false);

            money.setText((CharSequence)xmoney);
            money.setFocusable(false);
            money.setClickable(false);


        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    Bundle extras = getIntent().getExtras();

    if(extras !=null) {
        int Value = extras.getInt("id");
        if(Value>0){
            getMenuInflater().inflate(R.menu.display_contact, menu);
        } else{
            getMenuInflater().inflate(R.menu.main_menu, menu);
        }
    }
    return true;
}

public boolean onOptionsItemSelected(MenuItem items) {
    super.onOptionsItemSelected(items);
    switch(items.getItemId()) {
        case R.id.Edit_Contact:
            Button b = (Button)findViewById(R.id.EnterButton);
            b.setVisibility(View.VISIBLE);
            date.setEnabled(true);
            date.setFocusableInTouchMode(true);
            date.setClickable(true);

            item.setEnabled(true);
            item.setFocusableInTouchMode(true);
            item.setClickable(true);

            describe.setEnabled(true);
            describe.setFocusableInTouchMode(true);
            describe.setClickable(true);

            money.setEnabled(true);
            money.setFocusableInTouchMode(true);
            money.setClickable(true);

            return true;
        case R.id.Delete_Contact:

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.deleteContact)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mydb.deleteContact(id_To_Update);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully",
                                    Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });

            AlertDialog d = builder.create();
            d.setTitle("Are you sure");
            d.show();

            return true;
        default:
            return super.onOptionsItemSelected(items);

    }
}

/*public void run(View view) {
    Bundle extras = getIntent().getExtras();
    if(extras !=null) {
        int Value = extras.getInt("id");
        if(Value>0){
            if(mydb.updateContact(id_To_Update,date.getText().toString(),
                    item.getText().toString(), describe.getText().toString(),
                    money.getText().toString())){
                Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(intent);
            } else{
                Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
            }
        } else{
            if(mydb.insertContact(date.getText().toString(), item.getText().toString(),
                    describe.getText().toString(), money.getText().toString())){
                Toast.makeText(getApplicationContext(), "done",
                        Toast.LENGTH_SHORT).show();
            } else{
                Toast.makeText(getApplicationContext(), "not done",
                        Toast.LENGTH_SHORT).show();
            }
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
        }
    }
}*/
}

DBHelper.java代码

    package com.example.apple.sqlite;

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

import java.util.ArrayList;

/**
 * Created by Apple on 2017/3/4.
 */

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_DATE = "date";
public static final String CONTACTS_COLUMN_ITEM = "item";
public static final String CONTACTS_COLUMN_DESCRIBE = "describe";
public static final String CONTACTS_COLUMN_MONEY = "money";

public DBHelper(Context context) {
    super(context, DATABASE_NAME , null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE  TABLE contacts " +
            "(_id INTEGER PRIMARY KEY  NOT NULL , " +
            "date DATETIME NOT NULL , " +
            "item VARCHAR, " +
            "describe VARCHAR," +
            "money INTEGER)"
    );
}

public boolean insertContact (String date, String item, String describe, String money) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("date", date);
    contentValues.put("item", item);
    contentValues.put("describe", describe);
    contentValues.put("money", money);
    db.insert("contacts", null, contentValues);
    return true;
}

public Cursor getData(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
    return res;
}

public int numberOfRows(){
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, "contacts");
    return numRows;
}

public boolean updateContact (Integer id, String date, String item, String describe, String money) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("date", date);
    contentValues.put("item", item);
    contentValues.put("describe", describe);
    contentValues.put("money", money);
    db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deleteContact (Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete("contacts",
            "id = ? ",
            new String[] { Integer.toString(id) });
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS contacts");
    onCreate(db);
}

public ArrayList<String> getAllCotacts() {
    ArrayList<String> array_list = new ArrayList<String>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from contacts", null );
    res.moveToFirst();

    while(res.isAfterLast() == false){
        array_list.add(res.getString(res.getColumnIndex("contacts")));
        res.moveToNext();
    }
    return array_list;
}
}

我引用了两个web并创建了这个项目 http://www.tutorialspoint.com/android/android_sqlite_database.htm https://www.tutorialspoint.com/android/android_datepicker_control.htm

我该怎么办?

activity_main.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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30sp"
        android:text="@string/DataBase" />


        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" >
        </ListView>

</RelativeLayout>

activity_display_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
    "http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
    android:id="@+id/Title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/enter"
    android:textSize="26sp"
    android:textStyle="normal" />

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/item" />
    <EditText
        android:id="@+id/SQItem"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint=""/>
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/describe" />
    <EditText
        android:id="@+id/SQDescribe"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint=""/>
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/money" />
    <EditText
        android:id="@+id/SQMoney"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint=""/>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/date" />
    <EditText
        android:id="@+id/SQDate"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint=""/>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/EnterButton"
        style="@style/AppTheme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/news" />

    <Button
        android:id="@+id/DateButton"
        style="@style/AppTheme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/choose" />

    <Button
        android:id="@+id/CancelButton"
        style="@style/AppTheme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cancel" />
</LinearLayout>

</LinearLayout>

2 个答案:

答案 0 :(得分:1)

在您的布局activity_main.xml中,是否有任何带android:id="@+id/SQDate"的TextView?

我猜你试图从另一个.xml

调用TextView

<强>编辑:

您的ID = SQDate的视图不是TextView,它是一个EditText。

在MainActivity类中,更改此内容:

private TextView dateView;

dateView = (TextView) findViewById(R.id.SQDate);

要:

private EditText dateView;

dateView = (EditText) findViewById(R.id.SQDate);

答案 1 :(得分:0)

在activity_main.xml

中将TextView Id更改为SQDate

替换:

android:id="@+id/textView"

使用:

android:id="@+id/SQDate"