0

I am very new at programming Android applications, So please help me. I want to connect my application to a MySQL database.

But I get an error that crashes the application. Here is the error in 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)

And the code in 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;
    }
}

And here is the code 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>

I hope someone can help :/

2 Answers 2

1

There are two mistakes I can see:

  1. TextView is not initialized. Do you know findViewById()?
  2. You have made a web call directly on main UI thread which would cause an issue!
Sign up to request clarification or add additional context in comments.

Comments

0

You have a field txt:

TextView txt;

which is declared, but it is never set to a value. Therefore, when you try to use it here:

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

it throws an exception because it still has the value null.

If you have declared the TextView in your layout (e.g. with <TextView android:id="@+id/the_identifier_of_your_textview"), you need to assign it like this, immediately after calling setContentView:

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

4 Comments

but it give me the error: 'layout\activity_main.xml:11: error: Error: No resource found that matches the given name (at 'id' with value '@string/connexion').'
Can you post the contents of activity_main.xml?
xmlns:android="schemas.android.com/apk/res/android" xmlns:tools="schemas.android.com/tools" android:layout_width="match_parent" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.massar_parent.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@string/hello_world" />
Replace android:id="@string/hello_world" with android:id="@+id/the_identifier_of_your_textview" (or choose a more meaningful identifier). You cannot use @strings as ids.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.