doulou1970 2012-04-01 01:17
浏览 70

从Android连接到mySQL数据库时出错

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 + "
");
                }
                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?

  • 写回答

1条回答 默认 最新

  • douhuan6065 2012-04-01 18:54
    关注

    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 + "
    ");
            }
            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());
        }
    }
       }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛