Excepción en la página de inicio de sesión en Android

I want to create a login page like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:background="#000000" >
    <TextView
        android:id="@+id/Lbl_Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/Title"
        android:layout_margin="0dp" 
        android:padding="10dp"
        android:textColor="#FFFFFF"
        android:paddingRight="0dp"/>
    <EditText
        android:id="@+id/usrNameTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="@string/username"
       android:layout_marginBottom="20dp"
       android:typeface="serif" 
        android:layout_alignParentLeft="true"

        android:layout_below="@id/Lbl_Title"/>
 <EditText
        android:id="@+id/usrPassTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:inputType="text"
        android:hint="@string/password"

        android:typeface="serif" 
        android:layout_alignParentLeft="true"
        android:layout_below="@id/usrPassTxt" 
         />

     <Button
        android:id="@+id/Btn_exit_app"
        android:layout_width="65dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/usrPassTxt"
         android:text="@string/Exit" 
        android:layout_alignParentRight="true"
        />
      <Button
        android:id="@+id/Btn_Login"
         android:layout_width="65dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/usrPassTxt"
        android:layout_toLeftOf="@id/Btn_exit_app"
         android:layout_alignBottom="@id/Btn_exit_app"
        android:text="@string/Login" />



</RelativeLayout>

And here is my code,when the user logins with the right password goes into the main activity and if the password is invalid the user should be leaded to the Errorpage,the secon part I mean the Errorpage orks well but the first part doesn't work and will stop unexpectedly.I'll appreciate any suggestions.

package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.test.Buy;
import com.example.test.ErrorPage;


public class MyClass extends Activity {
    private EditText uName;
    private EditText uPass;
    private Button loginBtn;
    private Button Btn_Exit;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpViews();
        this.Btn_Exit=(Button)this.findViewById(R.id.Btn_exit_app);
       Btn_Exit.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {

            //  android.os.Process.killProcess(android.os.Process.myPid());
                Intent _Intent =new Intent(Intent.ACTION_MAIN);
                _Intent.addCategory(Intent.CATEGORY_HOME);
                _Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(_Intent);


            }
        });


    }
    @Override
    protected void onResume() {
        super.onResume();
        uName.setText("Enter User Name");
        uName.setTextColor(Color.parseColor("#888888"));
        uPass.setText("Enter Password");
        uPass.setInputType(InputType.TYPE_CLASS_TEXT);
        uPass.setTextColor(Color.parseColor("#888888"));
    }
    private void setUpViews() {
         uName=(EditText)findViewById(R.id.usrNameTxt);
         uPass=(EditText)findViewById(R.id.usrPassTxt);
        uName.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if(uName.getText().toString().equalsIgnoreCase("Enter User Name")){
                    if(hasFocus){
                        uName.setTextColor(Color.parseColor("#000000"));
                        uName.setText("");
                    }
                }
                else if(uName.getText().toString().equalsIgnoreCase("")){
                    uName.setTextColor(Color.parseColor("#888888"));
                    uName.setText("Enter User Name");
                }
            }
        });
        uPass.setOnFocusChangeListener(new View.OnFocusChangeListener(){

            public void onFocusChange(View v, boolean hasFocus) {
                if(uPass.getText().toString().equalsIgnoreCase("Enter Password")){
                    if(hasFocus){
                        uPass.setInputType(InputType.TYPE_CLASS_TEXT| InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        uPass.setTextColor(Color.parseColor("#000000"));
                        uPass.setText("");
                    }
                }
                else if(uPass.getText().toString().equalsIgnoreCase("")){
                        uPass.setInputType(InputType.TYPE_CLASS_TEXT);
                        uPass.setTextColor(Color.parseColor("#888888"));
                        uPass.setText("Enter Password");
                }
            }
        });
        loginBtn=(Button)findViewById(R.id.Btn_Login);

        //loginBtn.setFocusableInTouchMode(true);
        loginBtn.requestFocus();
        loginBtn.setOnClickListener(new OnClickListener() {
            private String pass;
            private String name;
            Intent myIntent;

            public void onClick(View v) {
                name=uName.getText().toString();
                pass=uPass.getText().toString();
                if(name.equalsIgnoreCase("so") && pass.equalsIgnoreCase("so"))
                {
                    myIntent=new Intent(MyClass.this,Main.class);
                    System.out.println("---IF---");
                }
                else if(name.equalsIgnoreCase("so")){
                    myIntent=new Intent(MyClass.this,ErrorPage.class);
                    myIntent.putExtra("user", "ok");
                    System.out.println("---ELSE IF---");
                }
                else{
                    myIntent=new Intent(MyClass.this,ErrorPage.class);
                    System.out.println("---ELSE---");
                }
                myIntent.putExtra("value", name);
                startActivity(myIntent);
            }
        });
    }
}

Y aquí está mi logcat:

    12-23 14:14:57.716: D/AndroidRuntime(226): Shutting down VM
12-23 14:14:57.726: W/dalvikvm(226): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-23 14:14:57.726: E/AndroidRuntime(226): Uncaught handler: thread main exiting due to uncaught exception
12-23 14:14:57.736: E/AndroidRuntime(226): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Main}: java.lang.NullPointerException
1
12-23 14:14:57.736: E/AndroidRuntime(226):  at dalvik.system.NativeStart.main(Native Method)
12-23 14:14:57.736: E/AndroidRuntime(226): Caused by: java.lang.NullPointerException
12-23 14:14:57.736: E/AndroidRuntime(226):  at com.exampletest.Main.onCreate(Main.java:52)
12-23 14:14:57.736: E/AndroidRuntime(226):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-23 14:14:57.736: E/AndroidRuntime(226):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)

Here is Main.java:

package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class Main extends Activity {

    private Button btn_Buy;
    private Button btn_BuyExperience;
    private Button btn_Change_Password;


    Bundle myValues;
    private TextView welcomeMsg;
    //private Button backButton;

    public void onCreate(Bundle savedInstanceState) 
    {
        ///-----------------
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.btn_Buy=(Button)this.findViewById(R.id.Btn_Buy);
        this.btn_BuyExperience=(Button)this.findViewById(R.id.btn_Buy_Experience);
        this.btn_Change_Password=(Button)this.findViewById(R.id.btn_Change_Password);

        myValues=getIntent().getExtras();




        btn_Buy.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                Intent Frm_Buy=new Intent(Main.this,Buy.class);
                startActivity(Frm_Buy);
            }
        });

        btn_BuyExperience.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                Intent Frm_Buyexperience=new Intent(Main.this,current_cart.class);
                startActivity(Frm_Buyexperience);
            }
        });

        btn_Change_Password.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                startActivity(new Intent(Main.this,Change_Password.class));

            }
        });
        setUpViews();
    }
      private void setUpViews() {

        welcomeMsg=(TextView)findViewById(R.id.msg);
        welcomeMsg.setText("WelcomePage : "+myValues.getString("value"));
        Button LogoutButton=(Button)findViewById(R.id.Btn_Logout);
        LogoutButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                finish();
            }
        });
    }
    @Override
    public void onAttachedToWindow() {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
        super.onAttachedToWindow();

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
       if(keyCode == KeyEvent.KEYCODE_HOME)
           Toast.makeText(getBaseContext(),
                    "Please Log Out !", Toast.LENGTH_LONG).show();
     return false;
    }

}

principal.xml

 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    android:background="#000000"
     >

<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


<TableLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/btn_Buy_Experience"
   android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
     >
 <TableRow android:id="@+id/tableRowWelcome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <TextView
        android:id="@+id/msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/welcome"
        android:textStyle="bold"
        android:typeface="serif" />

    </TableRow>
    <TableRow
        android:id="@+id/tablerowBuy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <Button
         android:id="@+id/Btn_Buy"
        android:layout_height="wrap_content"
       android:layout_weight="1"
    android:text="@string/Shop"
     android:drawableRight="@drawable/shopcartnew"
    />

    </TableRow>

    <TableRow
        android:id="@+id/tableRowCart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       >
        <Button
       android:id="@+id/btn_Buy_Experience"
       android:layout_height="wrap_content"
       android:layout_marginTop="20dp"
      android:layout_weight="1"
      android:text="@string/ShoppingCart"
      android:drawableRight="@drawable/shopcartico2"/>
    </TableRow>

    <TableRow
        android:id="@+id/tableRowPass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
          android:layout_centerHorizontal="true"

         >
        <Button
        android:id="@+id/btn_Change_Password"
    android:layout_height="wrap_content"
android:layout_marginTop="20dp"
        android:layout_weight="1"
        android:text="@string/ChangePassword" 
        android:drawableRight="@drawable/passchange2"/>
    </TableRow>

    <TableRow
        android:id="@+id/tableRowLogout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
         <Button
        android:id="@+id/Btn_Logout"
         android:layout_height="wrap_content"
       android:layout_marginTop="20dp"
        android:text="@string/logout"
         android:drawableRight="@drawable/exiticon" 
        />
    </TableRow>


</TableLayout>

</RelativeLayout>
</ScrollView>

preguntado el 23 de diciembre de 12 a las 09:12

this.btn_BuyExperience=(Button)this.findViewById(R.id.btn_Buy_Experience); There's no button with name btn_Buy_Experience in main.xml -

Thanks ,but the problem is somewhere else!Not solved! -

Why don't you debug the code instead? -

Update your code, clean it and run. If it doesn't run just post your updated xml, code & logcat and post it here. -

4 Respuestas

Hay algo mal con tu setUpViews(). The error occurs at:

E/AndroidRuntime(218): at com.example.test.Main.setUpViews(Main.java:53) 12-23 12:24:17.109: 

Replace your setUpViews() with this code:

    private void setUpViews() {
        this.btn_Buy=(Button)this.findViewById(R.id.Btn_Buy);
        this.btn_BuyExperience=(Button)this.findViewById(R.id.btn_Buy_Experience);
        this.btn_Change_Password=(Button)this.findViewById(R.id.btn_Change_Password);


        welcomeMsg=(TextView)findViewById(R.id.msg);
        welcomeMsg.setText("WelcomePage : "+myValues.getString("value"));
        Button LogoutButton=(Button)findViewById(R.id.Btn_Logout);
        LogoutButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                finish();
            }
        });

You were trying to setOnClick listener to buttons before initiating them.

Respondido el 23 de diciembre de 12 a las 10:12

Thanks a lot, but would you please help me to find the wrong expression in this method!?I' going to put the code of Main.java in my question. - user1831490

call the new setUpViews() just after setContentView() method. - Yauraw Gadav

Please post your Main.xml and Main.Java. - Yauraw Gadav

as after seen your main.xml file you have no Button with id btn_Buy_Experience so add a button in main.xml as :

<Button
        android:id="@+id/btn_Buy_Experience"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
 ...../>

Respondido el 23 de diciembre de 12 a las 11:12

@ShadiS : well now post latest log - ρяσѕρєя K

@ShadiS : i see your whole code and log link as you have posted here you have three packages in you have com.example.nfc.Main, in given code you have com.example.test.Main and in this question log you have com.exampletest.Main so plz make sure you are starting right Activity by passing full class name in intent - ρяσѕρєя K

Thanks,Actually I only have this package com.example.test.Main and I made a mistake in pasting the codes. - user1831490

Hay un error en tu Main.java

Note you call setupviews() antes

   this.btn_Buy=(Button)this.findViewById(R.id.Btn_Buy);
    this.btn_BuyExperience=(Button)this.findViewById(R.id.btn_Buy_Experience);
    this.btn_Change_Password=(Button)this.findViewById(R.id.btn_Change_Password);

But you try to set onClickListeners for them in setupviews()

They are null at this point and hence cause NullPointer

poner setUpViews at the end of onCreate. It should work.

 @Override
public void onCreate(Bundle savedInstanceState) 
{
    ///-----------------
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myValues=getIntent().getExtras();

    this.btn_Buy=(Button)this.findViewById(R.id.Btn_Buy);
    this.btn_BuyExperience=(Button)this.findViewById(R.id.btn_Buy_Experience);
    this.btn_Change_Password=(Button)this.findViewById(R.id.btn_Change_Password);

    setUpViews();
}

Hay un error en main.XML or an error in your code.

The error is caused because you try to convert btn_Buy_Experience to a button when it is clearly mentioned as a TableLayout en la main.xml.

You have to cast it to tableLayout not to a button.

To help with tableLayouts and buttons you might want to check this question out OnClickListener y diseño de tabla

contestado el 23 de mayo de 17 a las 12:05

I did it,and I've put the edited code in my question,but I still get the null exception.Any suggestions?Thanks in Advance - user1831490

Update the logcat too please. Show us which line is giving the error now. And please only post lines relevant to YOUR app. I.e. anything containing your package name - cjds

@ShadiS : where is main.xml plz post main.xml also - ρяσѕρєя K

@ρяσѕρєя K :I've pasted it - user1831490

comprobar esta

if(name.equalsIgnoreCase("so") && pass.equalsIgnoreCase("so"))
                {
                    myIntent=new Intent(MyClass.this,Main.class);
                    System.out.println("---IF---");
                }
                else if(name.equalsIgnoreCase("so")){
                    myIntent=new Intent(MyClass.this,ErrorPage.class);
                    myIntent.putExtra("user", "ok");
                    System.out.println("---ELSE IF---");
                }
                else{
                    myIntent=new Intent(MyClass.this,ErrorPage.class);
                    System.out.println("---ELSE---");
                }

Seems like you never created myIntent object, because all the conditions fails, and you get NullPointerException.

myIntent.putExtra("value", name);

Respondido el 23 de diciembre de 12 a las 12:12

Note the error does not occur there. It is clearly seen in his logcat at the onCreate of main. Plus the else would mean that one codepath must be taken - cjds

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.