如何在android的Asynctask中显示json响应[重复]
Posted
技术标签:
【中文标题】如何在android的Asynctask中显示json响应[重复]【英文标题】:How to display json response in Asynctask in android [duplicate] 【发布时间】:2013-09-20 16:39:03 【问题描述】:我正在尝试在 android 中开发登录模块,因为我在服务器端创建了表并返回返回用户 ID、用户名和密码的 json 响应。我使用 Asynctask 连接到 url 并在 doInBackground() 中从服务器读取数据.当我运行程序时,它显示登录失败消息。我不知道为什么它显示。我做了很多研发,但我没有得到解决方案。这是我的完整源代码
package com.example.tours;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends Activity implements OnClickListener
Button btnback,btnlog;
EditText e1,e2;
List<NameValuePair>nameValuePairs;
ProgressDialog progressdialog;
InputStream is=null;
JSONObject jsonobject=null;
String Json="";
String oneObjectsItem="";
String oneObjectsItem2="";
String oneObjectsItem3="";
protected void onCreate(Bundle savedInstanceState)
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
e1=(EditText)findViewById(R.id.editTextuser);
e2=(EditText)findViewById(R.id.editTextpass);
btnback=(Button)findViewById(R.id.btnback);
btnlog=(Button)findViewById(R.id.btnlogin);
btnback.setOnClickListener(this);
btnlog.setOnClickListener(this);
@Override
public void onClick(View v)
// TODO Auto-generated method stub
switch(v.getId())
case R.id.btnback:Intent i=new Intent(login.this,MainActivity.class);
startActivity(i);
break;
case R.id.btnlogin:// check username and pass so point to php file and build param
new CallAsyncTask().execute();
public class CallAsyncTask extends AsyncTask<String,String,String>
@Override
protected String doInBackground(String... arg0)
// TODO Auto-generated method stub
// code for checking user name and password
try
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://deepakg0.0fees.net/login.php");
// Build The parameter
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName",e1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("UserPass",e2.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// generate responce
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
catch(Exception e1)
Toast.makeText(getBaseContext(), "Errror"+e1.toString(), Toast.LENGTH_LONG).show();
//read the responce into string
try
BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null)
builder.append(line+"\n");
is.close();
Json=builder.toString();
catch(Exception e2 )
Log.d("Buffer","failed"+e2.toString());
// create the json object
try
jsonobject = new JSONObject(Json);
JSONArray jArray = jsonobject.getJSONArray("result");
// iterate through the array and fetch the keys
for(int i=0;i<jArray.length();i++)
// fetch the object and their keys
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
oneObjectsItem = oneObject.getString("uid");
oneObjectsItem2 = oneObject.getString("username");
oneObjectsItem3 = oneObject.getString("password");
catch(Exception e3)
Log.d("InJson","error"+e3.toString());
if((e1.getText().toString().equalsIgnoreCase(oneObjectsItem2)&&(e1.getText().toString().equalsIgnoreCase(oneObjectsItem2))))
Toast.makeText(getApplicationContext(),"Login Successfull",Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"Login Unsuccessfull",Toast.LENGTH_LONG).show();
return null;
@Override
protected void onPostExecute(String result)
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),"Output"+Json,Toast.LENGTH_LONG).show();
progressdialog.dismiss();
@Override
protected void onPreExecute()
// TODO Auto-generated method stub
super.onPreExecute();
progressdialog=new ProgressDialog(login.this);
progressdialog.setMessage("Checking username and password please wait");
//progressdialog.setIndeterminate(false);
//progressdialog.setCancelable(false);
progressdialog.show();
这是我的日志猫
09-11 18:33:50.809: E/AndroidRuntime(985): FATAL EXCEPTION: AsyncTask #1
09-11 18:33:50.809: E/AndroidRuntime(985): java.lang.RuntimeException: An error occured while executing doInBackground()
09-11 18:33:50.809: E/AndroidRuntime(985): at android.os.AsyncTask$3.done(AsyncTask.java:200)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.lang.Thread.run(Thread.java:1096)
09-11 18:33:50.809: E/AndroidRuntime(985): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
09-11 18:33:50.809: E/AndroidRuntime(985): at android.os.Handler.<init>(Handler.java:121)
09-11 18:33:50.809: E/AndroidRuntime(985): at android.widget.Toast.<init>(Toast.java:68)
09-11 18:33:50.809: E/AndroidRuntime(985): at android.widget.Toast.makeText(Toast.java:231)
09-11 18:33:50.809: E/AndroidRuntime(985): at com.example.tours.login$CallAsyncTask.doInBackground(login.java:143)
09-11 18:33:50.809: E/AndroidRuntime(985): at com.example.tours.login$CallAsyncTask.doInBackground(login.java:1)
09-11 18:33:50.809: E/AndroidRuntime(985): at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-11 18:33:50.809: E/AndroidRuntime(985): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-11 18:33:50.809: E/AndroidRuntime(985): ... 4 more
09-11 18:33:51.939: E/WindowManager(985): Activity com.example.tours.login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44ea9be0 that was originally added here
09-11 18:33:51.939: E/WindowManager(985): android.view.WindowLeaked: Activity com.example.tours.login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44ea9be0 that was originally added here
09-11 18:33:51.939: E/WindowManager(985): at android.view.ViewRoot.<init>(ViewRoot.java:247)
09-11 18:33:51.939: E/WindowManager(985): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
09-11 18:33:51.939: E/WindowManager(985): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-11 18:33:51.939: E/WindowManager(985): at android.view.Window$LocalWindowManager.addView(Window.java:424)
09-11 18:33:51.939: E/WindowManager(985): at android.app.Dialog.show(Dialog.java:241)
09-11 18:33:51.939: E/WindowManager(985): at com.example.tours.login$CallAsyncTask.onPreExecute(login.java:175)
09-11 18:33:51.939: E/WindowManager(985): at android.os.AsyncTask.execute(AsyncTask.java:391)
09-11 18:33:51.939: E/WindowManager(985): at com.example.tours.login.onClick(login.java:73)
09-11 18:33:51.939: E/WindowManager(985): at android.view.View.performClick(View.java:2408)
09-11 18:33:51.939: E/WindowManager(985): at android.view.View$PerformClick.run(View.java:8816)
09-11 18:33:51.939: E/WindowManager(985): at android.os.Handler.handleCallback(Handler.java:587)
09-11 18:33:51.939: E/WindowManager(985): at android.os.Handler.dispatchMessage(Handler.java:92)
09-11 18:33:51.939: E/WindowManager(985): at android.os.Looper.loop(Looper.java:123)
09-11 18:33:51.939: E/WindowManager(985): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-11 18:33:51.939: E/WindowManager(985): at java.lang.reflect.Method.invokeNative(Native Method)
09-11 18:33:51.939: E/WindowManager(985): at java.lang.reflect.Method.invoke(Method.java:521)
09-11 18:33:51.939: E/WindowManager(985): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-11 18:33:51.939: E/WindowManager(985): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-11 18:33:51.939: E/WindowManager(985): at dalvik.system.NativeStart.main(Native Method)
09-11 18:37:28.179: D/dalvikvm(1068): GC_FOR_MALLOC freed 3655 objects / 178624 bytes in 102ms
09-11 18:37:30.439: D/Buffer(1068): failedjava.lang.NullPointerException
09-11 18:37:30.449: D/InJson(1068): errororg.json.JSONException: End of input at character 0 of
09-11 18:40:14.559: D/dalvikvm(1095): GC_FOR_MALLOC freed 3809 objects / 182976 bytes in 96ms
09-11 18:40:16.769: D/Buffer(1095): failedjava.lang.NullPointerException
09-11 18:40:16.769: D/InJson(1095): errororg.json.JSONException: End of input at character 0 of
09-11 18:45:17.069: D/Buffer(1095): failedjava.lang.NullPointerException
09-11 18:45:17.069: D/InJson(1095): errororg.json.JSONException: End of input at character 0 of
09-11 19:07:09.619: D/dalvikvm(1095): GC_FOR_MALLOC freed 5200 objects / 195696 bytes in 98ms
09-11 19:07:09.840: D/dalvikvm(1095): GC_FOR_MALLOC freed 881 objects / 411168 bytes in 167ms
09-11 19:07:12.139: D/Buffer(1095): failedjava.lang.NullPointerException
09-11 19:07:12.139: D/InJson(1095): errororg.json.JSONException: End of input at character 0 of
09-11 19:07:12.219: D/Buffer(1095): failedjava.lang.NullPointerException
09-11 19:07:12.219: D/InJson(1095): errororg.json.JSONException: End of input at character 0 of
【问题讨论】:
【参考方案1】:您正在尝试从背景 Thread
与驻留在 UI Thread
中的 UI 组件进行交互。 doInBackGround() 在背景Thread
上执行。它的目的是让 UI Thread
在您执行长时间运行的任务(如网络交互)时保持响应。看看link 中的第 2 点。
【讨论】:
bt 我知道如何解决它我是 android 新手,你能给我最好的解决方案吗【参考方案2】:您不能通过doInBackground
方法制作 Toast,因为您只能从主线程修改 UI。在 AsyncTask 类之外创建一个方法,如下所示:
void toastFromMainThread(final String message, final int length)
runOnUiThread(new Runnable()
public void run()
Toast.makeText(getApplicationContext(),message,length).show();
);
然后,当您希望从后台线程出现 toast 时,调用此方法而不是 Toast.makeText。
【讨论】:
【参考方案3】:从doInBackground()
中删除Toast
。
如果您想与 UI 交互,请使用 onPostExecute()
例如:
public class YourClass extends AsyncTask<Void,Void,Void>
protected void onPreExecute()
super.onPreExecute();
//
@Override
protected Void doInBackground(Void... arg0)
// TODO Auto-generated method stub
//your stuff
return null;
protected void onPostExecute(Void q)
super.onPostExecute(q);
//notify user...
【讨论】:
以上是关于如何在android的Asynctask中显示json响应[重复]的主要内容,如果未能解决你的问题,请参考以下文章
在 Android 中,如何从 AsyncTask 更改 TextView? [复制]
如何使用 AsyncTask 的 onPostExecute 方法更新 Android 中的变量
Android:如何将参数传递给AsyncTask的onPreExecute()?
Android:如何将参数传递给 AsyncTask 的 onPreExecute()?