简体   繁体   中英

Error when connecting to mySQL db from Android

I've been following this tutorial . I've been very careful to follow the instructions exactly as given. Everything I've done is identical to what the person is doing, except that in my php file I give the my host, username, password, and database. In my database I've created the exact same table as in the tutorial (same field types names, everything. I ran the same script), and I have the exact same code in Eclipse.

Here is my code. It is identical to what is given but my HttpPost link is mine.

package com.heatscore.pregame;

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.os.Bundle;
import android.util.Log;

public class AlertsActivity extends Activity
{
    JSONArray jArray;
     String result = null;
     InputStream is = null;
     StringBuilder sb=null;


    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        // Uses the scores xml layout
        setContentView(R.layout.alerts);

        String result = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","1980"));

        //http post
        try
        {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://<EXCLUDED FOR QUESTION>/getAllPeopleBornAfter.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

        //convert response to 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 json data
        try
        {
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++)
            {
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","id: "+json_data.getInt("id")+
                            ", name: "+json_data.getString("name")+
                            ", sex: "+json_data.getInt("sex")+
                            ", birthyear: "+json_data.getInt("birthyear"));
            }
        }
        catch(JSONException e)
        {
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
    }
}

Unfortunately, when I run my app, the LogCat shows errors:

04-01 00:01:18.483: E/log_tag(5218): Error converting result java.lang.NullPointerException
04-01 00:01:18.483: E/log_tag(5218): Error parsing data org.json.JSONException: End of input at character 0 of 

I've also added the correct permissions to the manifest file. And yes, the line is after the application closing tag.

<uses-permission android:name="android.permission.INTERNET"/>

I ping the host to make sure it was not a network issue. The results were successful. Additionally, I am runing the app on my phone, not emulator. The program does not crash, however the error is there in the log.

So if almost everthing is identical to the example, then why is mine not working? Has anyone else had this issue and what did you do? Is there any way of figuring this out?

Figured it out! The "is" variable (InputStream) was in a different try catch block and was really null in the next block.

The following code fixes everything. Note I got rid of one of the try catches and moved the code from it up to the previous.

Hope this helps someone.

package xxx.xxx.xxx;

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.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AlertsActivity extends Activity
{
JSONArray jArray;
String result;
InputStream is;
StringBuilder sb;

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alerts);

    String result = "";
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("year","1980"));

    //http post
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://xxx/getAllPeopleBornAfter.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();

        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 in http connection " + e.toString());
    }

    //parse json data
    try
    {
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++)
        {
            JSONObject json_data = jArray.getJSONObject(i);
            Log.i("log_tag","id: " + json_data.getInt("id")+
                    ", name: " + json_data.getString("name")+
                    ", sex: " + json_data.getInt("sex")+
                    ", birthyear: " + json_data.getInt("birthyear"));    
        }
    }
    catch(JSONException e)
    {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
}
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM