JSONObject getInt(string) 方法导致 java.lang.RuntimeException。 Android工作室
JSONObject getInt(string) method causing java.lang.RuntimeException. Android Studio
我正在尝试检查用户是否输入了正确的用户 ID 和密码以登录应用程序。我的数据库已经在线部署。一切运行顺利,直到我得到结果以检查是否允许用户继续。但问题是我没有得到任何结果。相反,我在 JSONObject 的 getInt(String) 方法上得到了一个 java.lang.RuntimeException。这是我的 LoginActivity.java
public class LoginActivity extends AppCompatActivity {
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_user_check_login = "####/android_connect/check_user_login.php?username=#### & password=#####";
int success=0;
String id="";
String password="";
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Defining onClickListener for Login Button
Button loginBtn=(Button) findViewById(R.id.login_btn);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Check credentials
EditText phone=(EditText)findViewById(R.id.phone_txt);
EditText pwd=(EditText)findViewById(R.id.password_txt);
id=phone.getText().toString();
password=pwd.getText().toString();
new CheckUserLogin().execute();
}
});
}
class CheckUserLogin extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
// Check for success tag
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("id", id));
params1.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(
url_user_check_login, "GET", params1);
// json success tag
success = json.getInt(TAG_SUCCESS);//This is the line where i am getting the exception
} catch (JSONException e) {
e.printStackTrace();
}
// }
// });
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
if (success == 1) {
Intent intent=new Intent(getApplicationContext(), RideDetailsActivity.class);
startActivity(intent);
}
}
}
}
这是我正在使用的 php 个文件。
db_connect.php
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
db_config.php
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "####"); // db user
define('DB_PASSWORD', "####"); // db password (mention your db password here)
define('DB_DATABASE', "####"); // database name
define('DB_SERVER', "###.###.###); // db server
?>
check_user_login.php
check_user_login.php
<?php
/*
* Following code will check user credentials for log in
* uid and password are used to check if the user has permission to log in
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["id"]) && isset($_GET["password"])) {
$id = $_GET['id'];
$password = $_GET['password'];
// get a product from products table
$result = mysql_query("SELECT * FROM tb_login WHERE id = $id AND password = $password");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
// success
$response["success"] = 1;
$response["message"] = "User found";
// echoing JSON response
echo json_encode($response);
} else {
// no user found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no user found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
这是异常的堆栈跟踪
FATAL EXCEPTION: AsyncTask #4
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:100)
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:59)
at android.os.AsyncTask.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
我也不知道,所以我想问我是否必须提及数据库的端口号以及数据库服务器的 IP 地址?我完全不熟悉 php 并在 android 中使用 JSON。因此,在指出任何明显的错误时,请慎重考虑。谢谢。
查看此页面。
http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html
根据您在评论中发布的教程,您使用的 JSONParser 似乎是问题所在。
这里是更新 JSONParser 的代码,如果您只想尝试将其插入您的代码并查看它是否能解决您的问题。如果您想了解更多信息,请单击 link。
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
我正在尝试检查用户是否输入了正确的用户 ID 和密码以登录应用程序。我的数据库已经在线部署。一切运行顺利,直到我得到结果以检查是否允许用户继续。但问题是我没有得到任何结果。相反,我在 JSONObject 的 getInt(String) 方法上得到了一个 java.lang.RuntimeException。这是我的 LoginActivity.java
public class LoginActivity extends AppCompatActivity {
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_user_check_login = "####/android_connect/check_user_login.php?username=#### & password=#####";
int success=0;
String id="";
String password="";
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Defining onClickListener for Login Button
Button loginBtn=(Button) findViewById(R.id.login_btn);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Check credentials
EditText phone=(EditText)findViewById(R.id.phone_txt);
EditText pwd=(EditText)findViewById(R.id.password_txt);
id=phone.getText().toString();
password=pwd.getText().toString();
new CheckUserLogin().execute();
}
});
}
class CheckUserLogin extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
// Check for success tag
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("id", id));
params1.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(
url_user_check_login, "GET", params1);
// json success tag
success = json.getInt(TAG_SUCCESS);//This is the line where i am getting the exception
} catch (JSONException e) {
e.printStackTrace();
}
// }
// });
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
if (success == 1) {
Intent intent=new Intent(getApplicationContext(), RideDetailsActivity.class);
startActivity(intent);
}
}
}
}
这是我正在使用的 php 个文件。
db_connect.php
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
db_config.php
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "####"); // db user
define('DB_PASSWORD', "####"); // db password (mention your db password here)
define('DB_DATABASE', "####"); // database name
define('DB_SERVER', "###.###.###); // db server
?>
check_user_login.php
check_user_login.php
<?php
/*
* Following code will check user credentials for log in
* uid and password are used to check if the user has permission to log in
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["id"]) && isset($_GET["password"])) {
$id = $_GET['id'];
$password = $_GET['password'];
// get a product from products table
$result = mysql_query("SELECT * FROM tb_login WHERE id = $id AND password = $password");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
// success
$response["success"] = 1;
$response["message"] = "User found";
// echoing JSON response
echo json_encode($response);
} else {
// no user found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no user found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
这是异常的堆栈跟踪
FATAL EXCEPTION: AsyncTask #4
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:100)
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:59)
at android.os.AsyncTask.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
我也不知道,所以我想问我是否必须提及数据库的端口号以及数据库服务器的 IP 地址?我完全不熟悉 php 并在 android 中使用 JSON。因此,在指出任何明显的错误时,请慎重考虑。谢谢。
查看此页面。 http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html 根据您在评论中发布的教程,您使用的 JSONParser 似乎是问题所在。
这里是更新 JSONParser 的代码,如果您只想尝试将其插入您的代码并查看它是否能解决您的问题。如果您想了解更多信息,请单击 link。
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}