如何将Android应用程序连接到MySQL数据库?

时间:2015-07-26 12:56:06

标签: java android mysql

我是编程Android应用程序的新手,所以请帮助我。 我想将我的应用程序连接到MySQL数据库。

但是我收到一个错误,导致应用程序崩溃。这是LogCat中的错误:

07-26 12:32:47.785: E/AndroidRuntime(276): FATAL EXCEPTION: main
07-26 12:32:47.785: E/AndroidRuntime(276): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.massar_parent/com.example.parent.MainActivity}: java.lang.NullPointerException
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.os.Looper.loop(Looper.java:123)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.app.ActivityThread.main(ActivityThread.java:4627)
07-26 12:32:47.785: E/AndroidRuntime(276):  at java.lang.reflect.Method.invokeNative(Native Method)
07-26 12:32:47.785: E/AndroidRuntime(276):  at java.lang.reflect.Method.invoke(Method.java:521)
07-26 12:32:47.785: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-26 12:32:47.785: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-26 12:32:47.785: E/AndroidRuntime(276):  at dalvik.system.NativeStart.main(Native Method)
07-26 12:32:47.785: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
07-26 12:32:47.785: E/AndroidRuntime(276):  at com.example.massar_parent.MainActivity.onCreate(MainActivity.java:44)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-26 12:32:47.785: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

MainActivity.java中的代码

import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    //private TextView texte = null;
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        txt.setText("Connexion...");


        // Appeler la méthode pour récupérer les données JSON
        txt.setText(getServerData(strURL));
    }

    // Mettre l'adresse du script PHP
    // Attention localhost ou 127.0.0.1 ne fonctionnent pas. Mettre l'adresse IP
    // local.
    public static final String strURL = "http://localhost/massar/connection.php";

    private String getServerData(String returnString) {
        InputStream is = null;
        String result = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("NomEleve", "L"));

        // Envoie de la commande http
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        // Convertion de la requête en string
        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();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // Parse les données JSON
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                // Affichage ID_ville et Nom_ville dans le LogCat
                Log.i("log_tag", "CNE: " + json_data.getInt("CNE") + ", NomEleve: "
                        + json_data.getString("NomEleve"));
                // Résultats de la requête
                returnString += "\n\t" + jArray.getJSONObject(i);
            }

        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return returnString;
    }
}

这是代码AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.massar_parent"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <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=".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>

我希望有人可以提供帮助:/

2 个答案:

答案 0 :(得分:1)

我可以看到两个错误:

  1. TextView未初始化。你知道public class Vertex { private int v; private int label; public static void main(String[] args) { Map<Vertex, String> map = new HashMap<Vertex, String>(); Vertex vertex = new Vertex(); vertex.v = 5; vertex.label = 10; map.put(vertex, "vertex"); Vertex vertex2 = new Vertex(); vertex2.v = 5; vertex2.label = 100; System.out.println("Value:: "+ map.get(vertex2)); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + v; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vertex other = (Vertex) obj; if (v != other.v) return false; return true; } } 吗?
  2. 您已直接在主UI线程上进行了网络通话,这会导致出现问题!

答案 1 :(得分:0)

您有一个字段txt

TextView txt;

已声明,但永远不会设置为值。因此,当您尝试在此处使用它时:

txt.setText("Connexion...");

它会抛出异常,因为它仍然具有值null

如果您已在布局中声明了TextView(例如使用<TextView android:id="@+id/the_identifier_of_your_textview"),则需要在调用setContentView后立即将其指定为:

txt = (TextView)this.FindViewById(R.id.the_identifier_of_your_textview);