简体   繁体   中英

the button returns null when getting it from another activity : Android Studio

The problem is when i get sendBtn from my second activity (called :ClientInterFace) , it always returns null . and even when i want to pass something from my mainActivity(called:loginPage) to the constructor of the second activity , it also returns null!

public class LoginPage extends ActionBarActivity {

Button exitNow;
EditText Username;
TextView conStatus;
EditText Password;
Button LoginBtn;
ProgressBar progressBar;

static String serverAddress = "192.168.1.4";// Set
static int serverPort = 8081;// Set
static String user = "";// received from GUI
static String password = "";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new             StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

        exitNow = (Button) findViewById(R.id.exitbtn);
        Username = (EditText) findViewById(R.id.username);
        conStatus = (TextView) findViewById(R.id.connectionStatus);
        Password = (EditText) findViewById(R.id.password);
        LoginBtn = (Button) findViewById(R.id.loginBtn);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setEnabled(false);
        exitNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                System.exit(0);
            }
        });
        LoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    Runnable r = new Runnable() {
                        @Override
                        public void run(){
                            try {
                                user = Username.getText().toString();
                                password = Password.getText().toString();
                                theRest();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };

                    Handler h = new Handler();
                    h.postDelayed(r, 1500);




                }

            }


        });


}

 public void theRest() throws Exception {
 final ClientNetworkInterface Connection = new       ClientNetworkInterface(serverAddress, serverPort, user, password);
    if (Connection.isConnected()) {
        Toast.makeText(getApplicationContext(), "Congrats ! You Are    channeled through the ClientInterface !", Toast.LENGTH_LONG).show();
        final ClientInterFace SecondFrame = new ClientInterFace(user);//this    passes "user" to the constructor of ClientInterFace and it gets null .

        startActivity(new Intent(LoginPage.this, ClientInterFace.class));
        conStatus.setText("Connected!");
        progressBar.setVisibility(View.INVISIBLE);
        SecondFrame.getSendBtn().setOnClickListener(new     View.OnClickListener() {// this is where i get null pointer    


            @Override
            public void onClick(View v) { ...}    

// here is second activity , ClientInterFace.

public class ClientInterFace extends ActionBarActivity {
public Button sendBtn;
public EditText Commands;
public Button orm;
public ExtractEditText result;
public String message="";
public String User="";

public ClientInterFace(String user) {
    this.User=user;

}
public  ClientInterFace(){

}

    @Override
    protected void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.client_layout);
        setTitle("Welcome " + User + " !");
    TextView textView3=(TextView)findViewById(R.id.textView3);
    textView3.setText("Welcome to " + User + " Client Page !");
    sendBtn = (Button) findViewById(R.id.sendbtn);
        orm=(Button) findViewById(R.id.ORM);
        result=(ExtractEditText) findViewById(R.id.extractEditText);
        Commands=(EditText) findViewById(R.id.editText);
                }

public EditText getTextArea() {
    return Commands;
}

public Button getSendBtn() {
    return sendBtn;
}



public ExtractEditText getTextArea_1() {
    return result;
}

//here is my manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kooshan.cli" >
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="kooshan.finalap.cli.LoginPage"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="kooshan.finalap.cli.ClientInterFace"
        android:screenOrientation="portrait" />


</application>

</manifest>

//here is main_layout (login_layout)

<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"    android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"      tools:context="kooshan.finalap.cli.LoginPage"
android:id="@+id/rel">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout"
    android:weightSum="1"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Username :"
        android:id="@+id/textView"
        android:layout_gravity="center_horizontal" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/username"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Password :"
        android:id="@+id/textView2"
        android:layout_gravity="center_horizontal" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/password"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="exit now ! "
        android:id="@+id/exitbtn"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/connectionStatus"
        android:layout_weight="0.38"
        android:editable="false"
        android:gravity="center" />

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_gravity="center_horizontal"
        android:indeterminate="false"
        android:visibility="invisible" />

</LinearLayout>



<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Log in now !"
    android:id="@+id/loginBtn"
    android:layout_gravity="center_horizontal"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/linearLayout"
    android:layout_alignEnd="@+id/linearLayout"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

</RelativeLayout>

//here is client_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/secpage"
android:orientation="horizontal"
tools:context="kooshan.finalap.cli.ClientInterFace">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frame2">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ORM Page"
        android:id="@+id/ORM"
        android:layout_gravity="left|top" />

    <EditText
        android:layout_width="272dp"
        android:layout_height="177dp"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/editText"
        android:layout_gravity="left|center_vertical"
        android:text="SQL>"
        android:gravity="top" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="93dp"
        android:layout_height="159dp"
        android:text="Send Command"
        android:id="@+id/sendbtn"
        android:layout_gravity="right|center_vertical" />

    <android.inputmethodservice.ExtractEditText
        android:layout_width="302dp"
        android:layout_height="181dp"
        android:text="The Result"
        android:id="@+id/extractEditText"
        android:layout_gravity="left|bottom"
        android:inputType="textMultiLine"
        android:gravity="top" />

    <TextView
        android:layout_width="155dp"
        android:layout_height="137dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/textView3"
        android:layout_gravity="center_horizontal|top"
        android:gravity="bottom|center" />
    </FrameLayout>
</LinearLayout>

You might have not quite grasped how Activity works in Android. At the moment you are using them like normal Java classes, when they actually differ quite a lot. They might not exist when you normally would suppose a class would exist, which results in the null s you see. Read up on Activity life cycles .

The correct way to pass variables between Activity classes is using Intents . There is a method called putExtra(..) that you can use to add data that is received by another Activity . Check out the API .

Edit: for example, I am pretty sure this is not a good way to create an activity and will most likely have no effect when you start the Activity with startActivity() :

final ClientInterFace SecondFrame = new ClientInterFace(user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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