大家好我想在我的MainActivity类中将屏幕更改为点击监听器内的UserLogin类,这是我的代码。
package com.example.user.appproject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
ProgressDialog progressDoalog;
EditText firstname, lastname, age,email;
Button insert, show;
RequestQueue requestQueue;
String insertUrl = "http://192.168.1.11/insertRecord.php";
String showUrl = "http://192.168.1.11/showStudents.php";
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstname = (EditText) findViewById(R.id.edtFirstname);
lastname = (EditText) findViewById(R.id.edtLastname);
age = (EditText) findViewById(R.id.edtAge);
insert = (Button) findViewById(R.id.insert);
email=(EditText) findViewById(R.id.edtEmail);
requestQueue = Volley.newRequestQueue(getApplicationContext());
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("firstname",firstname.getText().toString());
parameters.put("lastname",lastname.getText().toString());
parameters.put("email",email.getText().toString());
parameters.put("age",age.getText().toString());
return parameters;
}
};
requestQueue.add(request);
Intent intent = new Intent(MainActivity.this,UserLogin.class);
startActivity(intent);
}
});
}
}
但是,我收到错误说
FATAL EXCEPTION: main
Process: com.example.user.appproject, PID: 20311
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.appproject/com.example.user.appproject.UserLogin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.user.appproject.UserLogin.onCreate(UserLogin.java:65)
at android.app.Activity.performCreate(Activity.java:6942)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
我不明白null对象引用的位置,就好像我取出intent代码一切正常,我的userLogin类在清单文件中定义。
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".UserLogin"/>
</application>
以下是代码的xml代码。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/main">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="firstname"
android:ems="10"
android:id="@+id/edtFirstname"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="lastname"
android:ems="10"
android:id="@+id/edtLastname"
android:layout_below="@+id/edtFirstname"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="email"
android:ems="10"
android:id="@+id/edtEmail"
android:layout_below="@+id/edtLastname"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="age"
android:ems="10"
android:id="@+id/edtAge"
android:layout_below="@+id/edtEmail"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="INSERT STUDENT"
android:id="@+id/insert"
android:layout_marginBottom="138dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
非常感谢任何帮助
UserLogin的主要代码:
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class UserLogin extends AppCompatActivity {
// Creating EditText.
EditText Email, Password;
// Creating button;
Button LoginButton;
// Creating Volley RequestQueue.
RequestQueue requestQueue;
// Create string variable to hold the EditText Value.
String EmailHolder, PasswordHolder;
// Creating Progress dialog.
ProgressDialog progressDialog;
// Storing server url into String variable.
String HttpUrl = "https://192.168.1.11/userLogin.php";
Boolean CheckEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assigning ID's to EditText.
Email = (EditText) findViewById(R.id.editText_Email);
Password = (EditText) findViewById(R.id.editText_Password);
// Assigning ID's to Button.
LoginButton = (Button) findViewById(R.id.button_login);
// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(UserLogin.this);
// Assigning Activity this to progress dialog.
progressDialog = new ProgressDialog(UserLogin.this);
// Adding click listener to button.
LoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CheckEditTextIsEmptyOrNot();
if (CheckEditText) {
UserLogin();
} else {
Toast.makeText(UserLogin.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
}
// Creating user login function.
public void UserLogin() {
// Showing progress dialog at user registration time.
progressDialog.setMessage("Please Wait");
progressDialog.show();
// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String ServerResponse) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Matching server responce message to our text.
if(ServerResponse.equalsIgnoreCase("Data Matched")) {
// If response matched then show the toast.
Toast.makeText(UserLogin.this, "Logged In Successfully", Toast.LENGTH_LONG).show();
// Finish the current Login activity.
finish();
}
else {
// Showing Echo Response Message Coming From Server.
Toast.makeText(UserLogin.this, ServerResponse, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing error message if something goes wrong.
Toast.makeText(UserLogin.this, volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
// The firs argument should be same sa your MySQL database table columns.
params.put("User_Email", EmailHolder);
params.put("User_Password", PasswordHolder);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(UserLogin.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
public void CheckEditTextIsEmptyOrNot() {
// Getting values from EditText.
EmailHolder = Email.getText().toString().trim();
PasswordHolder = Password.getText().toString().trim();
// Checking whether EditText value is empty or not.
if (TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) {
// If any of EditText is empty then set variable value as False.
CheckEditText = false;
} else {
// If any of EditText is filled then set variable value as True.
CheckEditText = true;
}
}
}
UserLogin屏幕的XML代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
tools:context="com.example.user.appproject.UserLogin">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:textSize="20dp"
android:textStyle="bold"
android:text="Volley User Login System"
android:gravity="center"
android:layout_marginTop="20dp"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Email"
android:gravity="center"
android:id="@+id/editText_Email"
android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Password"
android:gravity="center"
android:id="@+id/editText_Password"
android:inputType="textPassword"
android:layout_below="@+id/editText_Email"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="CLICK HERE TO LOGIN"
android:id="@+id/button_login"
android:layout_below="@id/editText_Password"
android:layout_marginTop="20dp"/>
</RelativeLayout>
答案 0 :(得分:0)
问题是您在UserLogin活动中设置了错误的布局。
您正在设置activity_main.xml,而您需要设置UserLogin活动布局XML文件。
你这样做
setContentView(R.layout.activity_main);
相反,你需要像
那样 setContentView(R.layout.YOUR_USER_LOGIN_ACTIVITY_LAYOUT);
答案 1 :(得分:0)
您在登录活动代码中使用了main_activity.xml。使用正确的布局,你会很好。
答案 2 :(得分:0)
谢谢你,雷霆和山姆。您的两个答案都有效,我只是更改了UserLogin类中的内容视图,以与该类的XML视图而不是主活动相关联。我认为在首次创建活动时它会自动放置正确的内容视图,但无论如何。非常感谢你们!