我正在编写我的Android应用程序的登录功能,它会检查我的在线sql并在登录成功时将用户显示在页面上。
但我一直有错误:
E / AndroidRuntime:FATAL EXCEPTION:AsyncTask#5在这些行:Log.d(“登录尝试”,json.toString())和类AttemptLogin扩展AsyncTask
我该如何解决?下面附有代码。提前谢谢!
JSONParser.java
special variables
Login.java
package com.test.qingyong.test;
/**
* Created by QingYong on 09/08/2015.
*/
import org.apache.http.HttpEntity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jsonObj ;
static String json = "";
// default no argument constructor for jsonpaser class
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Executing POST request & storing the response from server locally.
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 {
// Create a BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declaring string builder
StringBuilder str = new StringBuilder();
// string to store the JSON object.
String strLine = null;
// Building while we have string !equal null.
while ((strLine = reader.readLine()) != null) {
str.append(strLine + "\n");
}
// Close inputstream.
is.close();
// string builder data conversion to string.
json = str.toString();
} catch (Exception e) {
Log.e("Error", " something wrong with converting result " + e.toString());
}
// Try block used for pasrseing String to a json object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("json Parsering", "" + e.toString());
}
// Returning json Object.
return jsonObj;
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Make HTTP request
try {
// checking request method
if(method == "POST"){
// now defaultHttpClient object
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
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 str = new StringBuilder();
String strLine = null;
while ((strLine = reader.readLine()) != null) {
str.append(strLine + "\n");
}
is.close();
json = str.toString();
} catch (Exception e) {
}
// now will try to parse the string into JSON object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
}
return jsonObj;
}
}
Login.xml
package com.test.qingyong.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
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{
private EditText user, pass;
private Button bLogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://powerbankk.16mb.com/test.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
bLogin = (Button)findViewById(R.id.login);
bLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
// here we have used, switch case, because on Login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , menu than this we could also do this without switch //case.
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting for Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Login attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(Login.this,OtherActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to menu activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
test.php的
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="@+id/login"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password"
android:layout_alignRight="@+id/password"
android:layout_below="@+id/password"
android:text="login" />
<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password"
android:ems="10"
android:focusable="true"
android:hint="Enter username"
android:imeOptions="actionNext"
/>
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/username"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter Password"
android:imeOptions="actionDone"
/>
</RelativeLayout>