本文介绍了返回的JSONObject总是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发一个Android应用程序,它发送的用户名和密码,MySQL数据库,并接收在登录活动响应(成功或错误)。但返回的JSONObject为空。下面是codeS
userauth.php
< PHP
//连接到MySQL数据库
包括(db.php中); //检查POST请求
//如果(使用isset($ _ POST ['标签'])及和放大器;!$ _ POST ['标签'] =''){
//获取标签
// $标签= $ _ POST ['标签'];
//}
//通过JSON充分利用Android的用户名和密码
$用户名= $ _ POST [用户名];
$密码= $ _ POST ['密码'];
//创建respose阵列
$ respose =阵列(标记=> $标签,成功=大于1,错误=大于0); 从JSON //获取数据
// $用户名='asanka102';
// $密码='asanka102'; //查询MySQL数据库对USERAUTH表用户认证
$ SQL =SELECT * FROM USERAUTH其中username ='$用户名和密码= $密码';
$ QRY =的mysql_query($的SQL);
$ fin_result = mysql_num_rows($ QRY); //当用户存在与放大器返回true;返回false当用户DOEN的存在
//如果$ fin_result> 0(){
//返回true;
//}其他{
//返回false;
//}
如果($ fin_result大于0){
//用户发现,登录应该被授予
$响应[成功] = 1;
回声json_en code($响应);
}其他{
//未找到用户,登录应和禁止
$响应[错误] = 0;
$响应[ERROR_MSG] ='无效的登录';
回声json_en code($响应);
}
?>
MainActivity.java
公共类MainActivity延伸活动{
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main); etUsername =(EditText上)findViewById(R.id.et_username);
etPass =(EditText上)findViewById(R.id.et_password); errorTxt =(的TextView)findViewById(R.id.text_invalid_input); loginButton =(按钮)findViewById(R.id.button_login);
loginButton.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根 新用户注册忘记密码()执行();
}
}); } 私有类用户注册忘记密码扩展的AsyncTask<太虚,太虚,太虚> { @覆盖
保护无效doInBackground(虚空......为arg0){ 字符串username = etUsername.getText()的toString()。
。字符串密码= etPass.getText()的toString();
UserFunctions userFunctions =新UserFunctions();
JSONObject的JSON = userFunctions.loginUser(用户名,密码); //做其他事情 返回null;
} @覆盖
保护无效onPostExecute(虚空结果){
// TODO自动生成方法存根
如果(pDialog.isShowing())
pDialog.dismiss(); } }
UserFunctions.java
公共类UserFunctions { 私人JSONParser jsonParser; 私人静态字符串LOGIN_URL =http://192.168.100.172/android/userauth.php; 公共UserFunctions(){
jsonParser =新JSONParser();
} / **
*功能使登录请求
* @参数名
* @参数密码
* * /
公众的JSONObject loginUser(字符串用户名,字符串密码){
//大厦参数
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
params.add(新BasicNameValuePair(用户名的用户名));
params.add(新BasicNameValuePair(密码,密码));
JSONObject的JSON = jsonParser.getJSONFromUrl(LOGIN_URL,则params);
//返回JSON
// Log.e(JSON,json.toString());
返回JSON;
}
}
JSONParser.java
公共类JSONParser { 静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=; //构造
公共JSONParser(){
//空的构造
} //函数得到JSON的网址
//通过HTTP POST或GET mehtod
公众的JSONObject getJSONFromUrl(字符串URL,列表和LT;&的NameValuePair GT; PARAMS){ //使HTTP请求
尝试{
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(PARAMS)); HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent(); }赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(线+的n);
}
is.close();
JSON = sb.toString();
Log.e(JSON,JSON);
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj; }}
在logcat中给出了这样的
12月2日至11日:29:10.457:E /缓存器的错误(13927):错误转换结果显示java.lang.NullPointerException:锁== NULL
12月2日至十一日:29:10.457:E / JSON解析器(13927):错误分析数据org.json.JSONException:输入结束在字符0
12月2日至十一日:29:10.457:W / dalvikvm(13927):主题ID = 11:螺纹未捕获的异常(组= 0x41ba5ba8)退出
12月2日至十一日:29:10.467:D / dalvikvm(13927):GC_FOR_ALLOC释放280K,免费17142K / 17456K,暂停10毫秒,11毫秒总额2%
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):致命异常:AsyncTask的#1
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):工艺:collector.lbfinance,PID:13927
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):了java.lang.RuntimeException:执行doInBackground发生错误()
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在android.os.AsyncTask $ 3.done(AsyncTask.java:300)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在java.util.concurrent.FutureTask.setException(FutureTask.java:222)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在java.util.concurrent.FutureTask.run(FutureTask.java:242)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:587)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在java.lang.Thread.run(Thread.java:841)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):致:显示java.lang.NullPointerException
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在collector.lbfinance.MainActivity $ GetPassword.doInBackground(MainActivity.java:102)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在collector.lbfinance.MainActivity $ GetPassword.doInBackground(MainActivity.java:1)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在android.os.AsyncTask $ 2.call(AsyncTask.java:288)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):在java.util.concurrent.FutureTask.run(FutureTask.java:237)
12月2日至十一日:29:10.477:E / AndroidRuntime(13927):... 4个
解决方案
是 $ fin_result
返回行?
请尝试以下
{尝试
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,UTF-8),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
}
is.close();
JSON = sb.toString();
Log.e(JSON,JSON);
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj;
I'm developing an android app which sends username and password to MySQL database and receives response ("success" or "error") in the login activity. But the returning JSONObject is null. Below are the codes
userauth.php
<?php
//Connecting to mysql db
include("db.php");
//Check for POST request
//if(isset($_POST['tag']) && $_POST['tag'] !=''){
//Get tag
// $tag = $_POST['tag'];
//}
//Getting username and password from android via JSON
$username = $_POST['username'];
$password = $_POST['password'];
//Creating respose array
$respose = array("tag" => $tag, "success" => 1, "error" =>0);
//Getting data from json
//$username='asanka102';
//$password='asanka102';
//Querying mysql database against userauth table for user auth
$sql = "SELECT * FROM userauth WHERE username='$username' AND password='$password'";
$qry = mysql_query($sql);
$fin_result = mysql_num_rows($qry);
//Returning true when user exists & return false when user doen's exist
//if$fin_result > 0(){
// return true;
//}else{
// return false;
//}
if($fin_result > 0){
//User found, login should be granted
$response["success"] = 1;
echo json_encode($response);
}else{
//User not found, login shold be prohibited
$response["error"] = 0;
$response["error_msg"] = 'Invalid login';
echo json_encode($response);
}
?>
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.et_username);
etPass = (EditText) findViewById(R.id.et_password);
errorTxt = (TextView) findViewById(R.id.text_invalid_input);
loginButton = (Button) findViewById(R.id.button_login);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetPassword().execute();
}
});
}
private class GetPassword extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
String username = etUsername.getText().toString();
String password = etPass.getText().toString();
UserFunctions userFunctions = new UserFunctions();
JSONObject json = userFunctions.loginUser(username, password);
//Do other things
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pDialog.isShowing())
pDialog.dismiss();
}
}
UserFunctions.java
public class UserFunctions {
private JSONParser jsonParser;
private static String login_url = "http://192.168.100.172/android/userauth.php";
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* @param username
* @param password
* */
public JSONObject loginUser(String username, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(login_url, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
// Empty constructor
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The logcat gives this
02-11 12:29:10.457: E/Buffer Error(13927): Error converting result java.lang.NullPointerException: lock == null
02-11 12:29:10.457: E/JSON Parser(13927): Error parsing data org.json.JSONException: End of input at character 0 of
02-11 12:29:10.457: W/dalvikvm(13927): threadid=11: thread exiting with uncaught exception (group=0x41ba5ba8)
02-11 12:29:10.467: D/dalvikvm(13927): GC_FOR_ALLOC freed 280K, 2% free 17142K/17456K, paused 10ms, total 11ms
02-11 12:29:10.477: E/AndroidRuntime(13927): FATAL EXCEPTION: AsyncTask #1
02-11 12:29:10.477: E/AndroidRuntime(13927): Process: collector.lbfinance, PID: 13927
02-11 12:29:10.477: E/AndroidRuntime(13927): java.lang.RuntimeException: An error occured while executing doInBackground()
02-11 12:29:10.477: E/AndroidRuntime(13927): at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-11 12:29:10.477: E/AndroidRuntime(13927): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.lang.Thread.run(Thread.java:841)
02-11 12:29:10.477: E/AndroidRuntime(13927): Caused by: java.lang.NullPointerException
02-11 12:29:10.477: E/AndroidRuntime(13927): at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:102)
02-11 12:29:10.477: E/AndroidRuntime(13927): at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:1)
02-11 12:29:10.477: E/AndroidRuntime(13927): at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-11 12:29:10.477: E/AndroidRuntime(13927): ... 4 more
解决方案
Is $fin_result
returning rows?
Try the following
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
这篇关于返回的JSONObject总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!