Android Error with Websocket
<p>Im working on Websocket android application. I want to create Register and Login application with websocket. I am able to connect to websocket server with <a href="https://github.com/elabs/mobile-websocket-example/tree/master/android/WebsocketExampleClientProject" rel="nofollow">websocket android project</a>. I have created Register,Login activity with online reference.In register Activity, when I'm storing Registered data to Server using "send" method of websocketclient Java Class I'm getting <strong><em>"java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference"</em></strong> Error on my Log-cat window.</p>

<p>here is my Main Activity:</p>

<pre><code>package org.asperohgedgetws.a7.hgadgetws;
import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;

public class MainActivity extends Activity implements View.OnClickListener {
Button bLogout;
UserLocalStore userLocalStore;
private WebSocketClient mWebSocketClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bLogout = (Button) findViewById(R.id.bLogout);
    bLogout.setOnClickListener(this);
    userLocalStore = new UserLocalStore(this);
    connectWebSocket();
}
@Override
protected void onStart() {
    super.onStart();
    if (authenticate()== true){
        displayUserDetails();
    } else{
        Toast.makeText(getApplicationContext(), "Not Registered User :(", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(MainActivity.this,Login.class));
    }
}

private boolean authenticate(){
    return userLocalStore.getUserLoggedIn();
}

private void displayUserDetails(){
    User user = userLocalStore.getLoggedInUser();
}

@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.bLogout:
            startActivity(new Intent(this,Login.class));
            userLocalStore.clearUserData();
            userLocalStore.setUserLoggedIn(false);
            Toast.makeText(getApplicationContext(), "Logout :)", Toast.LENGTH_SHORT).show();
            break;

    }
}

private void connectWebSocket() {
    URI uri;
    try {
        uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }

    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");
            //mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
            mWebSocketClient.send("{\"1512BD002\":\"SO@0\":\"2\"}");
        }

        @Override
        public void onMessage(String s) {
            final String message = s;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //TextView textView = (TextView)findViewById(R.id.messages);
                    //textView.setText(textView.getText() + "\n" + message);
                }
            });
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };
    mWebSocketClient.connect();
}

public void sendMessage(View view) {
 //   EditText editText = (EditText)findViewById(R.id.message);
   // mWebSocketClient.send(editText.getText().toString());
    //editText.setText("");
}
}
</code></pre>

<p>RegisterActivity</p>

<pre><code>package org.asperohgedgetws.a7.hgadgetws;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import org.java_websocket.client.WebSocketClient;

public class Register extends AppCompatActivity implements View.OnClickListener {

Button bRegister;
EditText etName, etAge, etUsername, etPassword;
WebSocketClient nwebsocket;

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

    etName = (EditText) findViewById(R.id.etName);
    etAge = (EditText) findViewById(R.id.etAge);
    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);
    bRegister = (Button) findViewById(R.id.bRegister);
    bRegister.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.bRegister:
            // Toast.makeText(getApplicationContext(), "Register", Toast.LENGTH_SHORT).show();

            String name = etName.getText().toString();
            int age = Integer.parseInt(etAge.getText().toString());
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();

            User user = new User(name, age, username, password);
            registerUser(user);

            break;
    }
}

private void registerUser(User user) {
    String strtosend = "";
    JSONObject object = new JSONObject();
    try {
        // Add the id to the json
        object.put("name", user.name);
        object.put("age", user.age);
        object.put("username", user.username);
        object.put("password", user.password);
        strtosend = object.toString();

    } catch (JSONException e) {
        // Handle impossible error
        e.printStackTrace();
    }
    Toast.makeText(getApplicationContext(), strtosend, Toast.LENGTH_SHORT).show();
    nwebsocket.send("Hi!");
    Intent loginIntent = new Intent(Register.this, Login.class);
    startActivity(loginIntent);
}
}
</code></pre>

<p>Logcat Output:</p>

<pre><code>05-27 11:49:54.331 19459-19459/org.asperohgedgetws.a7.hgadgetws       E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: org.asperohgedgetws.a7.hgadgetws, PID: 19459
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference
                                                                                   at org.asperohgedgetws.a7.hgadgetws.Register.registerUser(Register.java:73)
                                                                                  at org.asperohgedgetws.a7.hgadgetws.Register.onClick(Register.java:51)
                                                                                  at android.view.View.performClick(View.java:4780)
                                                                                  at android.view.View$PerformClick.run(View.java:19866)
                                                                                  at android.os.Handler.handleCallback(Handler.java:739)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:135)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code></pre>

<p>Do I have to use again below code in Registered activity?</p>

<pre><code>private void connectWebSocket() {
    URI uri;
    try {
        uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }

    nWebsocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");
        }

        @Override
        public void onMessage(String s) {
            final String message = s;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
            });
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };
    nWebsocketClient.connect();
}
</code></pre>