gpt4 book ai didi

android - 尝试在空对象引用上调用虚拟方法 'java.lang.String java.lang.Object.toString()'

转载 作者:行者123 更新时间:2023-11-29 00:03:18 24 4
gpt4 key购买 nike

我是 Android 新手,这是我的第一个项目。我正在尝试制作一个从用户那里获取输入并对 mysql 数据库执行一些操作的 android 程序,我运行了该程序但出现了这些错误:

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.nada.mysqldemo.MainActivity.viewResultMessage(MainActivity.java:89)
at com.example.nada.mysqldemo.UserServiceAPI.onPostExecute(UserServiceAPI.java:83)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

谁能告诉我错误在哪里以及如何解决?我在这里附上我的代码:主 Activity .java

    import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
private EditText idEditText, nameEditText;
private ProgressDialog loadingDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

idEditText = (EditText) findViewById(R.id.et_id);
nameEditText = (EditText) findViewById(R.id.et_name);

loadingDialog = new ProgressDialog(this);
loadingDialog.setCancelable(false);
loadingDialog.setCanceledOnTouchOutside(false);
loadingDialog.setMessage("Please wait...");
}

public void selectOneButtonAction(View v) {
checkId();
loadingDialog.show();
new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute(idEditText
.getText().toString().trim(), "");
}

public void selectAllButtonAction(View v) {
loadingDialog.show();
new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute("", "");
}

public void insertButtonAction(View v) {
checkName();
loadingDialog.show();
new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute("",
nameEditText.getText().toString().trim());
}

public void deleteButtonAction(View v) {
checkId();
loadingDialog.show();
new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute(idEditText
.getText().toString().trim(), "");
}

public void updateButtonAction(View v) {
checkId();
checkName();
loadingDialog.show();
new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute(idEditText
.getText().toString().trim(), nameEditText.getText().toString()
.trim());
}

private void checkId() {
if (idEditText.getText().toString().trim().length() == 0) {
showToast("Missing id");
return;
}
}

private void checkName() {
if (nameEditText.getText().toString().trim().length() == 0) {
showToast("Missing name");
return;
}
}

private void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}

public void viewResultMessage(Object result) {
if (loadingDialog.isShowing())
loadingDialog.dismiss();
showToast(result.toString());
}

}

用户服务接口(interface)

    import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class UserServiceAPI extends AsyncTask<String, Integer, Object> {
public static final String INSERT = "insert";
public static final String UPDATE = "update";
public static final String DELETE = "delete";
public static final String SELECT_ONE = "selectone";
public static final String SELECT_ALL = "selectall";
private String action;
private MainActivity activity;
//private String url = "http://192.168.1.100/mysql_android/user_operations.php";
private String url = "http://10.0.2.2/mysql_android/user_operations.php";

public UserServiceAPI(MainActivity activity, String action) {
this.action = action;
this.activity = activity;
}

@Override
protected Object doInBackground(String... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("action", action));
nameValuePairs.add(new BasicNameValuePair("id", params[0]));
nameValuePairs.add(new BasicNameValuePair("name", params[1]));
String connRs = connect(url, nameValuePairs);
try {
if (action.equals(INSERT) || action.equals(UPDATE)
|| action.equals(DELETE)) {
JSONObject jsonObject = new JSONObject(connRs);
return jsonObject.getString("message");
} else if (action.equals(SELECT_ALL)) {
JSONArray jsonArray = new JSONArray(connRs);
if (jsonArray.length() == 0) {
return "No data found";
}
String rs = "";
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
rs += name;
}
return rs;
} else if (action.equals(SELECT_ONE)) {
JSONObject jsonObject = new JSONObject(connRs);
String user = jsonObject.getString("user");
if (user == null || user.equals("null")) {
return "No date for this id";
} else {
return jsonObject.getString("name");
}
}
} catch (Exception e) {
}
return null;
}

@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
activity.viewResultMessage(result);
}

/**
* connect to server with url and parameters
*
* @param url
* @param params
* @return
*/
public static String connect(String url, ArrayList<NameValuePair> params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);

int status = httpResponse.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity);
}
} catch (SocketTimeoutException ex) {
Log.d("RS", "SocketTimeoutException: " + ex.toString());
} catch (SocketException ex) {
Log.d("RS", "SocketException: " + ex.toString());
} catch (Exception e) {
Log.d("RS", "Connect EX: " + e.toString());
e.printStackTrace();
}
return null;
}
}

如果有人能帮上忙,我将不胜感激

最佳答案

日志信息:

    at com.example.nada.mysqldemo.MainActivity.viewResultMessage(MainActivity.java:89)

指向 viewResultMessage 中的以下行:

showToast(result.toString());

这意味着resultnullresult 从哪里来?它来自 onPostExecute 中的这个调用:

activity.viewResultMessage(result);

结果 从哪里来?根据AsyncTask documentation :

The specified result is the value returned by doInBackground(Params...).

因此,在您的 doInBackground 方法中,您将返回 null。问题可能出在这里:

} catch (Exception e) {
}
return null;

在这些行中,您将捕获可能发生的任何可能的异常,忽略异常并返回null。这会导致您观察到的行为。

要解决此问题,找出此处捕获的异常并解决该问题。在这种情况下,您还可以考虑返回 null 以外的内容。

关于android - 尝试在空对象引用上调用虚拟方法 'java.lang.String java.lang.Object.toString()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com