java - 不幸的是,<应用程序名称>已停止

标签 java android mysql eclipse

我正在尝试将我的 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>

这是我的 list 代码

<?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)

我将非常感谢您的帮助。我已经阅读了很多类似这样的帖子,但解决方案不适用于我的问题。提前致谢。

最佳答案

首先,我在代码中发现了一些错误:

private String url = "http://http://localhost/Try1/employee_details.php";

通过在 localhost 之后添加端口来修复该 URL,并删除双 http://试试这个并让我知道。

关于java - 不幸的是,<应用程序名称>已停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20877574/

相关文章:

java - Resources$NotFoundException 调用 Robolectric.buildActivity() 时

java - 如何在 Nativescript 中使用接口(interface)类型参数调用 Java 方法(自定义类)

android - Android 3.x 和 4.x 中的 java.lang.IllegalStateException ;在 2.x 上工作正常

php - 向空行添加一个字符

java - 覆盖 Bukkit API 中的类

Android 自定义 ArrayAdapter 不停留在滚动条上

安卓。使用户能够在布局中移动小部件

mysql - 如何让 Android 应用程序与外部 MySQL 数据库通信

mysql - 执行 LIKE 时忽略记录

java - 更新类类型对象的set方法