我是 android 的新手,我正在尝试使用在后台服务上运行的 socket.io 创建一个应用程序,但是我收到一个错误并且无法在互联网上找到解决方案或者我不太了解这个问题因为我缺乏使用 android(和对象)的经验。
mSocket.on("start tracking", new Emitter.Listener() {
@Override
public void call(final Object... args) {
timer.scheduleAtFixedRate(new TimerTask() {
long t0 = System.currentTimeMillis();
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String id;
try {
id = data.getString("id");
} catch (JSONException e) {
return;
}
//cancel();
if (System.currentTimeMillis() - t0 > 60 * 1000) {
cancel();
} else {
//do my stuff
String deviceId = Settings.System.getString(getContentResolver(),
Settings.System.ANDROID_ID);
if(id == deviceId){
mSocket.emit("emmitting location", deviceId, latitude, longitude);
}
}
}
}, 0, 1000);
}
});
编辑: 我没有意识到我没有通过我的服务器传递 JSON 对象。感谢@cybersam 清理一切并耐心解释整个情况。 :)
最佳答案
String
不是从 JSONObject
派生的。因此,您需要将 String
实例转换为新的 JSONObject
实例。
试试这个:
mSocket.on("start tracking", new Emitter.Listener() {
@Override
public void call(final Object... args) {
timer.scheduleAtFixedRate(new TimerTask() {
long t0 = System.currentTimeMillis();
@Override
public void run() {
JSONObject data;
String id;
try {
data = new JSONObject((String) args[0]);
id = data.getString("id");
} catch (JSONException e) {
return;
}
//cancel();
if (System.currentTimeMillis() - t0 > 60 * 1000) {
cancel();
} else {
//do my stuff
String deviceId = Settings.System.getString(getContentResolver(),
Settings.System.ANDROID_ID);
mSocket.emit("emmitting location", deviceId, latitude, longitude);
}
}
}, 0, 1000);
}
});
[编辑]
另一方面,如果您的输入数据只是一个 String
而不是 JSON 字符串,请执行以下操作:
mSocket.on("start tracking", new Emitter.Listener() {
@Override
public void call(final Object... args) {
timer.scheduleAtFixedRate(new TimerTask() {
long t0 = System.currentTimeMillis();
@Override
public void run() {
String id = (String) args[0];
//cancel();
if (System.currentTimeMillis() - t0 > 60 * 1000) {
cancel();
} else {
//do my stuff
String deviceId = Settings.System.getString(getContentResolver(),
Settings.System.ANDROID_ID);
mSocket.emit("emmitting location", deviceId, latitude, longitude);
}
}
}, 0, 1000);
}
});
注意:您实际上从未在任何地方使用 id
...
关于android - java.lang.String 无法转换为 org.json.JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32281782/