你好我正在学习使用本教程将android应用程序与MYSQL连接.. Tutorial
我想登录并在我的主机中向MYSQL数据库添加一些注释。 我已正确完成所有步骤。但是当我尝试在手机中加载应用程序时,说“遗憾的是MYSQL已经停止工作”并且给了我以下错误。 有人可以帮我解决这个错误吗。谢谢....
完整错误堆栈
02-08 15:21:43.578: E/AndroidRuntime(9705): FATAL EXCEPTION: AsyncTask #1
02-08 15:21:43.578: E/AndroidRuntime(9705): java.lang.RuntimeException: An error occured while executing doInBackground()
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.lang.Thread.run(Thread.java:838)
02-08 15:21:43.578: E/AndroidRuntime(9705): Caused by: java.lang.NullPointerException
02-08 15:21:43.578: E/AndroidRuntime(9705): at lk.adspace.mysqltest.Login$AttemptLogin.doInBackground(Login.java:141)
02-08 15:21:43.578: E/AndroidRuntime(9705): at lk.adspace.mysqltest.Login$AttemptLogin.doInBackground(Login.java:1)
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-08 15:21:43.578: E/AndroidRuntime(9705): ... 4 more
02-08 15:21:43.928: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:43.985: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:44.342: D/OpenGLRenderer(9705): Flushing caches (mode 1)
02-08 15:21:44.345: D/InputMethodManager(9705): deactivate the inputconnection in ControlledInputConnectionWrapper.
02-08 15:21:44.355: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:44.363: E/WindowManager(9705): Activity lk.adspace.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41344e60 V.E..... R......D 0,0-456,144} that was originally added here
02-08 15:21:44.363: E/WindowManager(9705): android.view.WindowLeaked: Activity lk.adspace.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41344e60 V.E..... R......D 0,0-456,144} that was originally added here
02-08 15:21:44.363: E/WindowManager(9705): at android.view.ViewRootImpl.<init> (ViewRootImpl.java:409)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:70)
02-08 15:21:44.363: E/WindowManager(9705): at android.app.Dialog.show(Dialog.java:281)
02-08 15:21:44.363: E/WindowManager(9705): at lk.adspace.mysqltest.Login$AttemptLogin.onPreExecute(Login.java:110)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.AsyncTask.execute(AsyncTask.java:534)
02-08 15:21:44.363: E/WindowManager(9705): at lk.adspace.mysqltest.Login.onClick(Login.java:83)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.View.performClick(View.java:4212)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.View$PerformClick.run(View.java:17476)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Handler.handleCallback(Handler.java:800)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Handler.dispatchMessage(Handler.java:100)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Looper.loop(Looper.java:194)
02-08 15:21:44.363: E/WindowManager(9705): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-08 15:21:44.363: E/WindowManager(9705): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 15:21:44.363: E/WindowManager(9705): at java.lang.reflect.Method.invoke(Method.java:525)
02-08 15:21:44.363: E/WindowManager(9705): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-08 15:21:44.363: E/WindowManager(9705): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-08 15:21:44.363: E/WindowManager(9705): at dalvik.system.NativeStart.main(Native Method)
02-08 15:21:44.364: D/OpenGLRenderer(9705): Flushing caches (mode 0)
这是我的login.java文件
package lk.adspace.mysqltest;
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.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
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 mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://www.adspace.lk/webservice/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
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 login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
//Intent i = new Intent(Login.this, ReadComments.class);
//finish();
//startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
}
}
}
JSONParser.java文件
package lk.adspace.mysqltest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
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 jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
public JSONObject makeHttpRequest(String loginUrl, String string,
List<NameValuePair> params) {
// TODO Auto-generated method stub
return null;
}
}
清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lk.adspace.mysqltest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="lk.adspace.mysqltest.Login"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="lk.adspace.mysqltest.Register"
android:label="@string/app_name" >
</activity>
<activity
android:name="lk.adspace.mysqltest.AddComment"
android:label="@string/app_name" >
</activity>
<activity
android:name="lk.adspace.mysqltest.ReadComments"
android:label="@string/app_name" >
</activity>
</application>
</manifest>
答案 0 :(得分:0)
在onPostExecute方法上启动新活动,而不是在doInBackground
上@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);