2013-09-18 2 views
0

Вы видите, что что-то не так с моим кодом? Я попытался создать диалоговое окно при нажатии кнопки. я не вижу что-то здесь не так, Но LogCat показывает java.lang.NullPointerException в этой строке «agree.setOnClickListener (новый OnClickListener() {»java.lang.NullPointerException on onClickListener

package com.sociyo; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.pm.ActivityInfo; 
import android.os.Bundle; 
import android.support.v4.view.ViewPager; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.Window; 
import android.widget.Button; 

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Lock Orientation 
     requestWindowFeature(Window.FEATURE_NO_TITLE); //Hide Action menu 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); //Load main activity 

     //viewPager default page 
     ViewPagerAdapter adapter = new ViewPagerAdapter(); 
     ViewPager myPager = (ViewPager) findViewById(R.id.pager); 
     myPager.setAdapter(adapter); 
     myPager.setCurrentItem(0); 

     //textView clickable 
     Button agree = (Button)findViewById(R.id.btnTerms); 

     agree.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       AlertDialog.Builder tpDialog = new AlertDialog.Builder(null); 

       tpDialog.setTitle("Terms and Policy"); 

       tpDialog.setMessage(R.string.action_settings) 
         .setCancelable(false) 
         .setPositiveButton("OK", new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         // TODO Auto-generated method stub 
         MainActivity.this.finish(); 
        } 
       }); 
      } 
     }); 



    } 

    @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); 
     return true; 
    } 



} 

И это полный журнал кошка:

E/AndroidRuntime(13076): FATAL EXCEPTION: main 

    E/AndroidRuntime(13076): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sociyo/com.sociyo.MainActivity}: java.lang.NullPointerException 

    E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070) 

    E/AndroidRuntime(13076): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095) 

    E/AndroidRuntime(13076): at android.app.ActivityThread.access$600(ActivityThread.java:137) 

    E/AndroidRuntime(13076): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206) 

    E/AndroidRuntime(13076): at android.os.Handler.dispatchMessage(Handler.java:99) 

    E/AndroidRuntime(13076): at android.os.Looper.loop(Looper.java:213) 

    E/AndroidRuntime(13076): at android.app.ActivityThread.main(ActivityThread.java:4793) 

    E/AndroidRuntime(13076): at java.lang.reflect.Method.invokeNative(Native Method) 

    E/AndroidRuntime(13076): at java.lang.reflect.Method.invoke(Method.java:511) 

    E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 

    E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 

    E/AndroidRuntime(13076): at dalvik.system.NativeStart.main(Native Method) 

    **E/AndroidRuntime(13076): Caused by: java.lang.NullPointerException** 

    E/AndroidRuntime(13076): at com.sociyo.MainActivity.onCreate(MainActivity.java:34) 

    E/AndroidRuntime(13076): at android.app.Activity.performCreate(Activity.java:5008) 

    E/AndroidRuntime(13076): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 

    E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034) 

    E/AndroidRuntime(13076): ... 11 more 

My activity_main.xml 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:background="@drawable/background" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

    <android.support.v4.view.ViewPager 
     android:id="@+id/pager" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentTop="true" > 
    </android.support.v4.view.ViewPager> 

</RelativeLayout> 

И мой activity_register.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:background="@android:color/transparent" 
    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" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/tvRegisterTitle" 
     style="@style/title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:text="@string/register_text" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <EditText 
     android:id="@+id/etNameReg" 
     style="@style/textfield" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/spMlmList" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="15dp" 
     android:ems="10" 
     android:hint="@string/name_hint" 
     android:inputType="textPersonName" > 

     <requestFocus /> 
    </EditText> 

    <EditText 
     android:id="@+id/etEmailReg" 
     style="@style/textfield" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/etNameReg" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="15dp" 
     android:ems="10" 
     android:hint="@string/email_hint" 
     android:inputType="textEmailAddress" /> 

    <EditText 
     android:id="@+id/etPasswordReg" 
     style="@style/textfield" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/etEmailReg" 
     android:layout_below="@+id/etEmailReg" 
     android:layout_centerVertical="true" 
     android:layout_marginTop="15dp" 
     android:ems="10" 
     android:hint="@string/password_hint" 
     android:inputType="textPassword" /> 

    <Spinner 
     android:id="@+id/spMlmList" 
     style="@style/textfield" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/tvRegisterTitle" 
     android:layout_below="@+id/tvRegisterTitle" 
     android:layout_marginTop="15dp" 
     android:entries="@array/mlm_list" /> 

    <Button 
     android:id="@+id/btnRegister" 
     style="@style/buttonBlue" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/etPasswordReg" 
     android:layout_below="@+id/chkAgree" 
     android:layout_marginTop="15dp" 
     android:text="@string/register_text" /> 

    <CheckBox 
     android:id="@+id/chkAgree" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/etPasswordReg" 
     android:text="@string/agree_text" 
     android:layout_marginTop="15dp" 
     style="@style/checkbox"/> 

    <Button 
     android:id="@+id/btnTerms" 
     android:background="@android:color/transparent" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/chkAgree" 
     android:layout_alignBottom="@+id/chkAgree" 
     android:layout_toRightOf="@+id/tvRegisterTitle" 
     android:layout_marginLeft="10dp" 
     android:text="@string/terms_policy" 
     style="@style/smallLink"/> 

</RelativeLayout> 
+0

, пожалуйста, покажите свой код xml. –

+0

какой код в вашей строке номер 34 ..? –

+0

Привет, это «согласен.setOnClickListener (новый OnClickListener()» {on line 34 –

ответ

1
// Before Replace 
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null); 

// After Replace 
AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this); 
+0

Сделал ли я в этом что-то не так? –

+0

AlertDialog.Builder tpDialog = new AlertDialog.Builder (null); вы устанавливаете значение null, так что оно дало вам исключение null-указателя во время выполнения –

+0

Извините, но с той же ошибкой. –

3

Да кнопка оленья кожа существовать в таком случае.

Ваш R.id.btnTermsR.id.btnУсловия определяется в файле activity_register.xml, но этот макет никогда не накачивается. или недоступны в этой точке :)

Его кнопка, которая имеет проблему, а не OnClickListener. Нулевой указатель внутри слушателя появится в тот момент, когда вы нажмете кнопку, а не при ее прикреплении.

+0

Привет, Даниэль, я помещаю Activity_register.xml в viewPager вместе с другим xml. И поместите viewPager в свой ActivityMain. Поэтому я не могу получить доступ к кнопке? –

+1

вы запрашиваете действие для кнопки, вам нужно будет спросить конкретный вид, который на самом деле содержит его. Попробуйте использовать if (agree == null) sysout («button null») - я предполагаю, что он появится в logcat :) –

+0

Да, я не могу найти идентификатор btnTerms. Есть ли способ получить доступ к этой кнопке из активности viewPager? –

0
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null); 

change this line too 

AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this); 
Смежные вопросы