我正在为我的学校开发一个Android应用程序。我在这行执行应用程序时遇到此错误::我不知道为什么会发生此错误。
conn =(HttpURLConnection)url.openConnection();
java.lang.NullPointerException:尝试调用虚方法' java.net.URLConnection java.net.URL.openConnection()'在空对象引用上
LoginPage.java
package com.example.anup.aam;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class LoginPage extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
SharedPreferenceLogin preferenceManager;
String role = "";
private EditText etEmail;
private EditText etPassword;
private CheckBox chkT, chkA, chkS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
//random bg
LinearLayout ll = (LinearLayout) findViewById(R.id.gbg);
AnimationDrawable animationDrawable = (AnimationDrawable) ll.getBackground();
animationDrawable.setEnterFadeDuration(2000);
animationDrawable.setExitFadeDuration(4000);
animationDrawable.start();
//btn bg
Button button = (Button) findViewById(R.id.signin);
AnimationDrawable animationDrawablebtn = (AnimationDrawable) button.getBackground();
animationDrawablebtn.setEnterFadeDuration(2000);
animationDrawablebtn.setExitFadeDuration(4000);
animationDrawablebtn.start();
// Get Reference to variables
etEmail = (EditText) findViewById(R.id.email);
etPassword = (EditText) findViewById(R.id.password);
//chkbox
chkT = (CheckBox) findViewById(R.id.chkT);
chkS = (CheckBox) findViewById(R.id.chkS);
chkA = (CheckBox) findViewById(R.id.chkA);
preferenceManager = new SharedPreferenceLogin(this);
if (preferenceManager.getUsername().length() > 1) {
new AsyncLogin().execute(preferenceManager.getUsername(), preferenceManager.getPassword());
}
}
//kr check bhai
// Triggers when LOGIN Button clicked
public void checkLogin(View arg0) {
// Get text from email and passord field
final String email = etEmail.getText().toString();
final String password = etPassword.getText().toString();
if (chkT.isChecked()) {
role = "Teacher";
} else if (chkS.isChecked()) {
role = "Student";
} else if (chkA.isChecked()) {
role = "Admin";
} else if (chkT.isChecked() && chkS.isChecked() && chkA.isChecked() || chkT.isChecked() && chkS.isChecked() || chkS.isChecked() && chkA.isChecked() || chkT.isChecked() && chkA.isChecked()) {
Toast.makeText(LoginPage.this, "Choose only one Role!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginPage.this, "Select your Role!", Toast.LENGTH_LONG).show();
}
toast(role);
new AsyncLogin().execute(email, password, role);
}
public void toast(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(LoginPage.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(LoginPage.this, "Loading...", Toast.LENGTH_SHORT).show();
//this method will be running on UI thread
//pdLoading.setMessage("\tAuthenticating...");
//pdLoading.setCancelable(false);
//pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
if (role.equalsIgnoreCase("Student")) {
url = new URL("http://18.188.122.100/aam/SLogin.php");
} else if (role.equalsIgnoreCase("Teacher")) {
url = new URL("http://18.188.122.100/aam/TLogin.php");
//conn = (HttpURLConnection) url.openConnection();
} else if (role.equalsIgnoreCase("Admin")) {
url = new URL("http://18.188.122.100/aam/ALogin.php");
//conn = (HttpURLConnection) url.openConnection();
}
} catch (MalformedURLException mfe) {
mfe.printStackTrace();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", params[0])
.appendQueryParameter("password", params[1]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
//toast(result);
// pdLoading.dismiss();
if (pdLoading != null && pdLoading.isShowing()) {
//pdLoading.cancel();
pdLoading.dismiss();
}
if (result.equalsIgnoreCase("true")) {
/* Here launching another activity when login successful. If you persist login state
use sharedPreferences of Android. and logout button to clear sharedPreferences.
*/
preferenceManager.putLoginDetail(etEmail.getText().toString(), etPassword.getText().toString());
if (role.equalsIgnoreCase("TEACHER")) {
Intent intent = new Intent(LoginPage.this, TeacherPage.class);
startActivity(intent);
LoginPage.this.finish();
} else if (role.equalsIgnoreCase("ADMIN")) {
Intent intent = new Intent(LoginPage.this, AdminPage.class);
startActivity(intent);
LoginPage.this.finish();
} else if (role.equalsIgnoreCase("STUDENT")) {
Intent intent = new Intent(LoginPage.this, StudentPage.class);
startActivity(intent);
LoginPage.this.finish();
}
} else if (result.equalsIgnoreCase("false")) {
// If username and password does not match display a error message
Toast.makeText(LoginPage.this, "Invalid email or password", Toast.LENGTH_LONG).show();
} else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
Toast.makeText(LoginPage.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
}
activity_login_page.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:id="@+id/activity_login_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fafafa"
tools:context="com.example.anup.aam.LoginPage">
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="200dp"
android:background="@drawable/box_radius"
android:elevation="4dp"
android:orientation="vertical"
android:padding="15dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="30dp"
android:weightSum="1">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:drawableLeft="@drawable/ic_user"
android:drawableTint="#37474f"
android:hint="User Email"
android:inputType="textEmailAddress"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_marginTop="16dp"
android:drawableLeft="@drawable/ic_lock"
android:drawableTint="#37474f"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:id="@+id/chklist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<CheckBox
android:id="@+id/chkT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Teacher"
android:textColor="#455a64" />
<CheckBox
android:id="@+id/chkS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student"
android:textColor="#455a64" />
<CheckBox
android:id="@+id/chkA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Admin"
android:textColor="#455a64" />
</LinearLayout>
<Button
android:id="@+id/signin"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_margin="22dp"
android:layout_weight="0.28"
android:background="@drawable/gradient_background"
android:onClick="checkLogin"
android:text="Sign in"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="@+id/gbg"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:background="@drawable/gradient_background"
android:orientation="vertical"
>
<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="110dp"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:src="@drawable/logoname" />
<TextView
android:id="@+id/lname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Android Attendance Manager"
android:textColor="@color/white"
android:textSize="20sp" />
</LinearLayout>
<TextView
android:id="@+id/lnamecopy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:text="\u00A9 Softlabb Innovative Solution "
android:textColor="@color/gray"
android:textSize="18sp" />
</RelativeLayout>