开始另一个活动时,空指针异常 [英] Nullpointer exception when starting another activity

查看:98
本文介绍了开始另一个活动时,空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序包含两个activities.i称为一个方法showevent第二项活动。但有错误发生,空指针exception.why是这样吗?
 我的计划包含两个activities.i称为一个方法showevent。但一个错误的第二个活动发生,空指针exception.why是这样

FirstActivity.java

 公共类FirstActivity扩展FragmentActivity实现OnItemSelectedListener {
    / **当第一次创建活动调用。 * /
    公共最后静态字符串EXTRA_MESSAGE =com.example.myfirstapp.MESSAGE;
    公共最后静态字符串EXTRA_MESSAGE1 =com.example.myfirstapp.MESSAGE;
    classdbOpenHelper eventsData;
     TextView的userSelection;
     按钮okButton;
     按钮Add按钮;     按钮change_date_but;
     TextView的日期;
     TextView中显示;
     EditText上的EditText;
      公共静态最终诠释Date_dialog_id = 1;
      私人诠释mYear;
      私人诠释mMonth;
      私人诠释MDAY;    私有静态最后的String []项目= {Yalahanka,Rajaji格尔,大行善者格尔,科拉曼加拉,RT格尔,Banashankari,Yashwanthpura,Hebbal};    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_first);
         okButton =(按钮)findViewById(R.id.button2);
         Add按钮=(按钮)findViewById(R.id.button3);         change_date_but =(按钮)findViewById(R.id.button1);
         日期=(的TextView)findViewById(R.id.textView2); // KEY_DATE
         userSelection =(的TextView)findViewById(R.id.textView1); // KEY_DESC
         的EditText =(EditText上)findViewById(R.id.editText1); // KEY_EVENT
         秀=(的TextView)findViewById(R.id.textView5);         微调my_spin =(微调)findViewById(R.id.spinner1);
        my_spin.setOnItemSelectedListener(本);
        ArrayAdapter AA =新ArrayAdapter(这一点,android.R.layout.simple_spinner_item,项目);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        my_spin.setAdapter(AA);        okButton.setOnClickListener(新答题());        eventsData =新classdbOpenHelper(本);        change_date_but.setOnClickListener(新View.OnClickListener(){                   @覆盖
                   公共无效的onClick(视图v){
                     DatePickerDialog DPD =新DatePickerDialog(
                   FirstActivity.this,mDateSetListener,mYear,mMonth,MDAY);
                                DPD.show();
               }
                  });
        最后的日历C = Calendar.getInstance();
              mYear = c.get(Calendar.YEAR);
              mMonth = c.get(的Calendar.MONTH);
              MDAY = c.get(Calendar.DAY_OF_MONTH);              updateDisplay();
    }
     @覆盖
         @德precated         在prepareDialog(INT ID,对话的对话){保护无效
          // TODO自动生成方法存根
       super.on prepareDialog(ID,对话);          ((DatePickerDialog)对话框).updateDate(mYear,mMonth,MDAY);         }         私人DatePickerDialog.OnDateSetListener mDateSetListener =新DatePickerDialog.OnDateSetListener(){       公共无效onDateSet(查看的DatePicker,年整型,诠释monthOfYear,
            INT请将dayOfMonth){
           mYear =年;
           mMonth = monthOfYear;
       MDAY =请将dayOfMonth;
           updateDisplay();
          }
         };         私人无效updateDisplay(){
       // TODO自动生成方法存根
          date.setText(新的StringBuilder()
            //月份是基于0,因此加1
         .append(mMonth + 1).append( - )。追加(MDAY).append( - )
            .append(mYear));
         }    @覆盖
    公共无效onItemSelected(适配器视图<>为arg0,ARG1观,诠释POS,长ARG3){
        userSelection.setText(项目[POS]);
    }
    @覆盖
    公共无效onNothingSelected(适配器视图<>为arg0){
        // TODO自动生成方法存根
        userSelection.setText();
    }    类唱首歌实现Button.OnClickListener {
        公共无效的onClick(视图v){
            。字符串DATEVALUE = date.getText()的toString();
            字符串Userselectvalue = userSelection.getText()的toString()。
            。字符串Userevent = edittext.getText()的toString();
            SQLiteDatabase分贝= eventsData.getWritableDatabase();            ContentValues​​ CV =新ContentValues​​();
            cv.put(classdbOpenHelper.KEY_DESC,Userselectvalue);
            cv.put(classdbOpenHelper.KEY_EVENT,Userevent);
            cv.put(classdbOpenHelper.KEY_DATE,DATEVALUE);
            db.insert(classdbOpenHelper.DATABASE_TABLE,空,CV);
            db.close();
            }         }    公共无效ShowEvent(查看视图){
        意向意图=新意图(这一点,Getclicker.class);
         日期=(的TextView)findViewById(R.id.textView2);
        。字符串DATEVALUE = date.getText()的toString();
        userSelection =(的TextView)findViewById(R.id.textView1);
        字符串Userselectvalue = userSelection.getText()的toString()。        intent.putExtra(EXTRA_MESSAGE,DATEVALUE);
        intent.putExtra(EXTRA_MESSAGE1,Userselectvalue);        startActivity(意向);
    }
}

Getclicker.java

 包example.events1;进口android.app.ListActivity;
进口android.content.Intent;
进口android.database.Cursor;
进口android.os.Bundle;
进口android.support.v4.widget.SimpleCursorAdapter;
进口android.widget.ListView;公共类Getclicker扩展ListActivity {
    意向意图= getIntent();
    字符串DATEVALUE = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE);
    字符串Userselectvalue = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE1);
    classdbOpenHelper eventsData1;
    光标光标1;
     ListView控件的ListView;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_second); / *字符串DATEVALUE = date.getText()的toString();
        字符串Userselectvalue = userSelection.getText()的toString()。        字符串showevent = eventsData.getContact(DATEVALUE,Userselectvalue);
        show.setText(showevent); * /         光标1 = eventsData1.getContact(DATEVALUE,Userselectvalue);
         的String [] = fromColumns {classdbOpenHelper.KEY_EVENT};
         INT [] = toViews {R.id.event};
         SimpleCursorAdapter适配器=新SimpleCursorAdapter(在此,R.layout.events,光标1,fromColumns,toViews,0);
          ListView控件=(ListView控件)findViewById(android.R.id.list);
         listView.setAdapter(适配器);
        }    公共无效的onDestroy(){
        eventsData1.close();
      }}

logcat的:

 十月八日至7日:00:58.396:E / AndroidRuntime(889):致命异常:主要
10月8日至7日:00:58.396:E / AndroidRuntime(889):了java.lang.RuntimeException:无法实例活动ComponentInfo {example.events1 / example.events1.Getclicker}:显示java.lang.NullPointerException
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.os.Handler.dispatchMessage(Handler.java:99)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.os.Looper.loop(Looper.java:137)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.app.ActivityThread.main(ActivityThread.java:5041)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在java.lang.reflect.Method.invokeNative(本机方法)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在java.lang.reflect.Method.invoke(Method.java:511)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在dalvik.system.NativeStart.main(本机方法)
10月8日至7日:00:58.396:E / AndroidRuntime(889):致:显示java.lang.NullPointerException
10月8日至7日:00:58.396:E / AndroidRuntime(889):在example.events1.Getclicker<&初始化GT;(Getclicker.java:12)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在java.lang.Class.newInstanceImpl(本机方法)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在java.lang.Class.newInstance(Class.java:1319)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.app.Instrumentation.newActivity(Instrumentation.java:1054)
10月8日至7日:00:58.396:E / AndroidRuntime(889):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
10月8日至7日:00:58.396:E / AndroidRuntime(889):11 ...更多


解决方案

将这些文件:

 意向意图= getIntent();
字符串DATEVALUE = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE);
字符串Userselectvalue = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE1);

的onCreate()方法。我猜是因为意向还没有去过那里。

希望这有助于。

my program contains two activities.i called the second activity by a method showevent .but an error occured, nullpointer exception.why is this ? my program contains two activities.i called the second activity by a method showevent .but an error occured, nullpointer exception.why is this

FirstActivity.java

public class FirstActivity extends FragmentActivity implements OnItemSelectedListener {
    /** Called when the activity is first created. */
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    public final static String EXTRA_MESSAGE1 = "com.example.myfirstapp.MESSAGE";


    classdbOpenHelper eventsData;
     TextView userSelection;
     Button okButton;
     Button addButton;

     Button change_date_but;
     TextView date;
     TextView show;
     EditText edittext; 
      public static final int Date_dialog_id = 1;
      private int mYear;
      private int mMonth;
      private int mDay;

    private static final String[] items={"Yalahanka","Rajaji nagar","Sivaji Nagar","Koramangala","RT Nagar", "Banashankari","Yashwanthpura","Hebbal"};



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
         okButton = (Button)findViewById(R.id.button2);
         addButton = (Button)findViewById(R.id.button3);

         change_date_but = (Button)findViewById(R.id.button1);
         date = (TextView)findViewById(R.id.textView2);//KEY_DATE
         userSelection=(TextView)findViewById(R.id.textView1);//KEY_DESC
         edittext=(EditText)findViewById(R.id.editText1);//KEY_EVENT


         show=(TextView)findViewById(R.id.textView5);

         Spinner my_spin=(Spinner)findViewById(R.id.spinner1);
        my_spin.setOnItemSelectedListener(this);
        ArrayAdapter aa=new ArrayAdapter(this, android.R.layout.simple_spinner_item,items);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        my_spin.setAdapter(aa);

        okButton.setOnClickListener(new clicker());

        eventsData = new classdbOpenHelper(this);

        change_date_but.setOnClickListener(new View.OnClickListener() {



                   @Override
                   public void onClick(View v) {
                     DatePickerDialog DPD = new DatePickerDialog(
                   FirstActivity.this, mDateSetListener, mYear, mMonth,mDay);
                                DPD.show();
               }
                  });
        final Calendar c = Calendar.getInstance();
              mYear = c.get(Calendar.YEAR);
              mMonth = c.get(Calendar.MONTH);
              mDay = c.get(Calendar.DAY_OF_MONTH);

              updateDisplay();
    }
     @Override
         @Deprecated

         protected void onPrepareDialog(int id, Dialog dialog) {
          // TODO Auto-generated method stub
       super.onPrepareDialog(id, dialog);

          ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);

         }

         private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

       public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
           mYear = year;
           mMonth = monthOfYear;
       mDay = dayOfMonth;
           updateDisplay();
          }
         };

         private void updateDisplay() {
       // TODO Auto-generated method stub
          date.setText(new StringBuilder()
            // Month is 0 based so add 1
         .append(mMonth + 1).append("-").append(mDay).append("-")
            .append(mYear));
         }







    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
        userSelection.setText(items[pos]);
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
        userSelection.setText("");
    }



    class clicker implements Button.OnClickListener {
        public void onClick(View v) {
            String datevalue = date.getText().toString();
            String Userselectvalue = userSelection.getText().toString();
            String Userevent = edittext.getText().toString();
            SQLiteDatabase  db = eventsData.getWritableDatabase();

            ContentValues cv = new ContentValues();
            cv.put(classdbOpenHelper.KEY_DESC, Userselectvalue);
            cv.put(classdbOpenHelper.KEY_EVENT, Userevent);
            cv.put(classdbOpenHelper.KEY_DATE,datevalue);
            db.insert(classdbOpenHelper.DATABASE_TABLE, null, cv);
            db.close();
            }

         }

    public void ShowEvent(View view){
        Intent intent = new Intent(this, Getclicker.class);
         date = (TextView)findViewById(R.id.textView2);
        String datevalue = date.getText().toString();
        userSelection=(TextView)findViewById(R.id.textView1);
        String Userselectvalue = userSelection.getText().toString();

        intent.putExtra(EXTRA_MESSAGE, datevalue);
        intent.putExtra(EXTRA_MESSAGE1, Userselectvalue);

        startActivity(intent);
    }
}

Getclicker.java

package example.events1;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ListView;

public class Getclicker  extends ListActivity {
    Intent intent = getIntent();
    String datevalue = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE);
    String Userselectvalue = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE1);
    classdbOpenHelper eventsData1;
    Cursor cursor1;
     ListView listView ; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);                       /*String datevalue = date.getText().toString();
        String Userselectvalue = userSelection.getText().toString();

        String showevent = eventsData.getContact(datevalue,Userselectvalue);
        show.setText(showevent);*/

         cursor1 = eventsData1.getContact(datevalue,Userselectvalue);
         String[] fromColumns = {classdbOpenHelper.KEY_EVENT};
         int[] toViews = {R.id.event};
         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.events, cursor1, fromColumns, toViews,0 );
          listView = (ListView) findViewById(android.R.id.list); 
         listView.setAdapter(adapter);
        }

    public void onDestroy() {
        eventsData1.close();
      }

}

logcat :

08-07 10:00:58.396: E/AndroidRuntime(889): FATAL EXCEPTION: main
08-07 10:00:58.396: E/AndroidRuntime(889): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{example.events1/example.events1.Getclicker}: java.lang.NullPointerException
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.os.Looper.loop(Looper.java:137)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.app.ActivityThread.main(ActivityThread.java:5041)
08-07 10:00:58.396: E/AndroidRuntime(889):  at java.lang.reflect.Method.invokeNative(Native Method)
08-07 10:00:58.396: E/AndroidRuntime(889):  at java.lang.reflect.Method.invoke(Method.java:511)
08-07 10:00:58.396: E/AndroidRuntime(889):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-07 10:00:58.396: E/AndroidRuntime(889):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-07 10:00:58.396: E/AndroidRuntime(889):  at dalvik.system.NativeStart.main(Native Method)
08-07 10:00:58.396: E/AndroidRuntime(889): Caused by: java.lang.NullPointerException
08-07 10:00:58.396: E/AndroidRuntime(889):  at example.events1.Getclicker.<init>(Getclicker.java:12)
08-07 10:00:58.396: E/AndroidRuntime(889):  at java.lang.Class.newInstanceImpl(Native Method)
08-07 10:00:58.396: E/AndroidRuntime(889):  at java.lang.Class.newInstance(Class.java:1319)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-07 10:00:58.396: E/AndroidRuntime(889):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-07 10:00:58.396: E/AndroidRuntime(889):  ... 11 more

解决方案

Move these:

Intent intent = getIntent();
String datevalue = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE);
String Userselectvalue = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE1);

into the onCreate() method. I guess the because Intent havent been there yet.

Hope this helps.

这篇关于开始另一个活动时,空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆