提问人:Ruben Meiring 提问时间:3/20/2020 最后编辑:Ruben Meiring 更新时间:7/12/2021 访问量:106
为什么我在这些元素上获得 NullPointer
Why Am i Getting a NullPointer on these elements
问:
我在我的按钮和文本视图上收到一个空指针异常,我真的不知道为什么, 对我来说,代码没有错
setcontentview 正在链接正确的布局
Java 代码
public class ClientSmart extends AppCompatActivity {
Button PostButton123;
TextView SmsText;
String email;
String clientId;
String pwd;
String URL2;
String LogoUrl;
StringRequest stringRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_smart);
PostButton123.findViewById(R.id.buttontest);
SmsText.findViewById(R.id.editTextTest);
email=getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("name", "");
clientId=getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("id", "");
pwd=getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("password", "");
Uri.Builder TimeLogUrl=new Uri.Builder();
TimeLogUrl.scheme("https")
.authority("www.jdjdjd.com")
.appendPath("jsj")
.appendQueryParameter("ClientID", clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd);
URL2=TimeLogUrl.build().toString();
PostButton123.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
RequestQueue requestQueue=Volley.newRequestQueue(ClientSmart.this);
String URL=URL2;
JSONObject jsonBody=new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", SmsText.getText().toString());
final String requestBody=jsonBody.toString();
stringRequest=new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString="";
if (response != null) {
responseString=String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Toasty.success(ClientSmart.this,stringRequest.toString(),Toasty.LENGTH_LONG).show();
}
});
}
}
XML 代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.smartpractice.myapplication.ClientSmart">
<Button
android:id="@+id/buttontest"
android:layout_width="280dp"
android:layout_height="273dp"
android:layout_marginEnd="8dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/editTextTest"
android:layout_width="512dp"
android:layout_height="422dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
app:layout_constraintBottom_toTopOf="@+id/buttontest"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
我试过了
多次重启 Android Studio
清洁项目
重建项目
完全重写代码 创建新活动并重写代码
错误日志
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.smartpractice.smartpracticesmartapp, PID: 7022
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.smartpractice.smartpracticesmartapp/com.smartpractice.myapplication.ClientSmart}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3430)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
at com.smartpractice.myapplication.ClientSmart.onCreate(ClientSmart.java:50)
at android.app.Activity.performCreate(Activity.java:7458)
at android.app.Activity.performCreate(Activity.java:7448)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
答:
1赞
Amit pandey
3/20/2020
#1
更改此项
PostButton123.findViewById(R.id.buttontest);
SmsText.findViewById(R.id.editTextTest);
到
PostButton123=findViewById(R.id.buttontest);
SmsText=findViewById(R.id.editTextTest);
请注意,您需要使用标志。=
评论