我正在使用Websocket android應用程序。我想用websocket創建註冊和登錄應用程序。我可以通過websocket android project連接到websocket服務器。我使用在線參考創建了註冊,登錄活動。在註冊活動中,當我使用websocketclient Java類的「send」方法將註冊數據存儲到服務器時我得到「java.lang.NullPointerException:試圖調用虛擬方法'void org.java_websocket.client.WebSocketClient.send(java.lang.String)'null對象引用「我的日誌貓窗口上出現錯誤。Android錯誤與Websocket
這裏是我的主要活動:
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\":\"[email protected]\":\"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("");
}
}
RegisterActivity
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);
}
}
logcat的輸出:
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)
我必須在註冊活動,下面的代碼再次使用?
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();
}
可能重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix - 我) – 1615903
我得到了什麼是NPE,但在我的情況3我該如何解決它?我在mainActivity中打開websocket連接,如何使用發送功能在已註冊的活動中發送註冊數據。我是Android/Java編碼的新手,所以需要了解。請不要介意。 –