Android HttpResponse之后不执行代码
我刚开始使用Web服务。我只是在教程中采用了代码形式,并尝试在我的项目中实现它。以下是我的代码,但它并没有按照我想要的方式工作 LoginScreen.javaAndroid HttpResponse之后不执行代码,android,json,web-services,Android,Json,Web Services,我刚开始使用Web服务。我只是在教程中采用了代码形式,并尝试在我的项目中实现它。以下是我的代码,但它并没有按照我想要的方式工作 LoginScreen.java public class LoginScreen extends Activity implements OnClickListener { EditText edittextloginusername; EditText e
public class LoginScreen extends Activity implements OnClickListener
{
EditText edittextloginusername;
EditText edittextloginpassword;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//PHP Login script location
private static final String LOGIN_URL = "http://xxx.xxx.x.xxx/Json_Login/login.php";
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
initialize();
}
//Initialization of components
private void initialize() {
//Getting the reference of font from assets folder
String fontPath = "Font/Arsenal-Regular.otf";
Typeface tf = Typeface.createFromAsset(getAssets(),fontPath);
//Getting the reference of EditText
edittextloginusername=(EditText)findViewById(R.id.editTextLoginusername);
edittextloginpassword=(EditText)findViewById(R.id.editTextLoginpassword);
//Getting references of buttons
Button buttonlogin=(Button)findViewById(R.id.buttonlogin);
//set on click listener on buttons
buttonlogin.setOnClickListener(this);
}//end of Initialization
//on click method
@Override
public void onClick(View v) {
if(v.getId()==R.id.buttonlogin){
new AttemptLogin().execute();
Intent intent=new Intent(LoginScreen.this,MenuScreen.class);
startActivity(intent);
finish();
}
}//end of on click
@Override
public void onBackPressed(){
finish();
super.onBackPressed();
}
//AsyncTask is a separate thread than the thread that runs the GUI
//Any type of networking should be done with asynctask.
public class AttemptLogin extends AsyncTask<String, String, String>
{
//three methods get called, first preExecture, then do in background, and once do
//in back ground is completed, the onPost executer method will be called.
// Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(LoginScreen.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args)
{
// Check for success tag
int success;
String username = edittextloginusername.getText().toString();
String password = edittextloginpassword.getText().toString();
try{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userPassword", password));
Log.d("request!", "starting");
// getting login details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
// check your log for json response
Log.d("Login attempt", "Login attempt: "+json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
Log.d("Log in background","success"+success);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginScreen.this, MenuScreen.class);
finish();
startActivity(i);
return json.getString("Login Successful");
}else{
Log.d("Login Failure!","Login Fail...");
return "Fail";
}
}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 product deleted
pDialog.dismiss();
Toast.makeText(getApplicationContext(),file_url,Toast.LENGTH_SHORT).show();
}
}
}
公共类LoginScreen扩展活动实现OnClickListener
{
EditText edittextloginusername;
编辑文本编辑文本登录密码;
//进度对话框
私人对话;
//JSON解析器类
JSONParser JSONParser=新的JSONParser();
//PHP登录脚本位置
私有静态最终字符串登录\u URL=”http://xxx.xxx.x.xxx/Json_Login/login.php";
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u login\u屏幕);
初始化();
}
//组件的初始化
私有void初始化(){
//从资产文件夹中获取字体的引用
字符串fontPath=“Font/arsen Regular.otf”;
Typeface tf=Typeface.createFromAsset(getAssets(),fontPath);
//获取EditText的引用
edittextloginusername=(EditText)findViewById(R.id.edittextloginusername);
edittextloginpassword=(EditText)findViewById(R.id.edittextloginpassword);
//获取按钮的引用
Button buttonlogin=(Button)findViewById(R.id.buttonlogin);
//单击按钮设置侦听器
buttonlogin.setOnClickListener(此);
}//初始化结束
//点击法
@凌驾
公共void onClick(视图v){
if(v.getId()==R.id.buttonlogin){
新建AttemptLogin().execute();
Intent Intent=newintent(LoginScreen.this,MenuScreen.class);
星触觉(意向);
完成();
}
}//点击结束
@凌驾
public void onBackPressed(){
完成();
super.onBackPressed();
}
//AsyncTask是一个独立于运行GUI的线程的线程
//任何类型的网络都应该使用asynctask完成。
公共类AttemptLogin扩展异步任务
{
//调用三个方法,首先是preexecute,然后在后台执行,一次执行
//在后台完成后,将调用onPost executer方法。
//在启动后台线程显示进度对话框之前
@凌驾
受保护的void onPreExecute()
{
super.onPreExecute();
pDialog=newprogressdialog(LoginScreen.this);
setMessage(“正在尝试登录…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…args)
{
//检查成功标签
成功;
字符串用户名=edittextloginusername.getText().toString();
字符串密码=edittextloginpassword.getText().toString();
试一试{
//建筑参数
List params=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
添加(新的BasicNameValuePair(“用户密码”,password));
Log.d(“请求!”,“启动”);
//通过发出HTTP请求获取登录详细信息
JSONObject json=jsonParser.makeHttpRequest(登录URL,“GET”,参数);
//检查日志中的json响应
d(“登录尝试”,“登录尝试:+json.toString());
//json成功标记
success=json.getInt(TAG_success);
Log.d(“登录后台”,“成功”+成功);
如果(成功==1){
Log.d(“登录成功!”,json.toString();
意图i=新意图(LoginScreen.this,MenuScreen.class);
完成();
星触觉(i);
返回json.getString(“登录成功”);
}否则{
Log.d(“登录失败!”,“登录失败…”);
返回“失败”;
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
//完成后台任务后,关闭“进度”对话框
受保护的void onPostExecute(字符串fil
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
Log.d("Log in background","4.1");
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
Log.d("Log in background","4.2");
url += "?" + paramString;
Log.d("Log in background","4.3");
HttpGet httpGet = new HttpGet(url);
Log.d("Log in background","4.4");
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("Log in background","4.5");
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();
} 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;
}
}