我正在尝试将我的android应用程序连接到mysql数据库。我一直在关注我在网上看到的一个教程,很多关于该教程的反馈说它对他们有用。但是,每当我尝试运行我的应用程序时,它都会崩溃并显示消息“不幸的是,Sample3已停止”。
这是我的.java代码
package com.example.sample3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
private String jsonResult;
private String url = "http://localhost/Try1/employee_details.php";
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
ListDrwaer(); //this is line 90
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult); //this is line 105
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("employee no");
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
这是我的.xml代码
<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="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" >
</ListView>
</RelativeLayout>
这是我的清单代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sample3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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="com.example.sample3.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
这是我的logcat错误:
01-02 01:22:49.960: E/AndroidRuntime(1140): FATAL EXCEPTION: main
01-02 01:22:49.960: E/AndroidRuntime(1140): Process: com.example.sample3, PID: 1140
01-02 01:22:49.960: E/AndroidRuntime(1140): java.lang.NullPointerException
01-02 01:22:49.960: E/AndroidRuntime(1140): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
01-02 01:22:49.960: E/AndroidRuntime(1140): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
01-02 01:22:49.960: E/AndroidRuntime(1140): at org.json.JSONObject.<init>(JSONObject.java:155)
01-02 01:22:49.960: E/AndroidRuntime(1140): at org.json.JSONObject.<init>(JSONObject.java:172)
01-02 01:22:49.960: E/AndroidRuntime(1140): at com.example.sample3.MainActivity.ListDrwaer(MainActivity.java:105)
01-02 01:22:49.960: E/AndroidRuntime(1140): at com.example.sample3.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:90)
01-02 01:22:49.960: E/AndroidRuntime(1140): at com.example.sample3.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:1)
01-02 01:22:49.960: E/AndroidRuntime(1140): at android.os.AsyncTask.finish(AsyncTask.java:632)
01-02 01:22:49.960: E/AndroidRuntime(1140): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-02 01:22:49.960: E/AndroidRuntime(1140): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
01-02 01:22:49.960: E/AndroidRuntime(1140): at android.os.Handler.dispatchMessage(Handler.java:102)
01-02 01:22:49.960: E/AndroidRuntime(1140): at android.os.Looper.loop(Looper.java:137)
01-02 01:22:49.960: E/AndroidRuntime(1140): at android.app.ActivityThread.main(ActivityThread.java:4998)
01-02 01:22:49.960: E/AndroidRuntime(1140): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 01:22:49.960: E/AndroidRuntime(1140): at java.lang.reflect.Method.invoke(Method.java:515)
01-02 01:22:49.960: E/AndroidRuntime(1140): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-02 01:22:49.960: E/AndroidRuntime(1140): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-02 01:22:49.960: E/AndroidRuntime(1140): at dalvik.system.NativeStart.main(Native Method)
我将非常感谢你的帮助。我经历了很多像这样的帖子,但解决方案并不适用于我的问题。提前谢谢。
答案 0 :(得分:1)
首先,我发现代码中的错误很少:
private String url = "http://http://localhost/Try1/employee_details.php";
通过在localhost之后添加端口修复该URL,并删除双重http://试试这个并告诉我。
答案 1 :(得分:0)
请检查网址无效:
private String url = "http://http://localhost/Try1/employee_details.php";
它应该是这样的:
private String url = "http://192.168.1.18/Try1/employee_details.php";
答案 2 :(得分:0)
将localhost更改为10.0.2.2
,然后重试。
你也放了http://
次。