Android无法正确连接到MySQL数据库

I'm trying to get the basics of an Android app that sends and receives data from a MySQL server (my implementation will have nothing to do with this learning example). Here's the code so far:

package com.davekelley.polling;

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.ParseException;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class Chart extends Activity {

    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;

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

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.davidjkelley.net/city.php");
            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());
        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "
");

            String line="0";
            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());
        }
        //paring data
        int ct_id;
        String ct_name;
        try{
            jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                ct_id=json_data.getInt("CITY_ID");
                ct_name=json_data.getString("CITY_NAME");
            }
        }
        catch(JSONException e1){
            Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
    }
}

And here's the code for the XML file 'chartfragment':

<?xml version="1.0" encoding="utf-8"?>
    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

<!-- <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/chartTitleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center"/>
-->

    </ListView>

And here are the LogCat problems I'm encountering:

03-26 20:34:13.782: E/log_tag(1025): Error in http connection android.os.NetworkOnMainThreadException
03-26 20:34:13.802: E/log_tag(1025): Error converting result java.lang.NullPointerException
03-26 20:34:13.802: D/AndroidRuntime(1025): Shutting down VM
03-26 20:34:13.802: W/dalvikvm(1025): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
03-26 20:34:13.832: E/AndroidRuntime(1025): FATAL EXCEPTION: main
03-26 20:34:13.832: E/AndroidRuntime(1025): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.davekelley.polling/com.davekelley.polling.Chart}: java.lang.NullPointerException
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.os.Looper.loop(Looper.java:137)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.ActivityThread.main(ActivityThread.java:4424)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at java.lang.reflect.Method.invokeNative(Native Method)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at java.lang.reflect.Method.invoke(Method.java:511)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at dalvik.system.NativeStart.main(Native Method)
03-26 20:34:13.832: E/AndroidRuntime(1025): Caused by: java.lang.NullPointerException
03-26 20:34:13.832: E/AndroidRuntime(1025):     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at org.json.JSONArray.<init>(JSONArray.java:87)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at org.json.JSONArray.<init>(JSONArray.java:103)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at com.davekelley.polling.Chart.onCreate(Chart.java:68)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.Activity.performCreate(Activity.java:4465)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-26 20:34:13.832: E/AndroidRuntime(1025):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-26 20:34:13.832: E/AndroidRuntime(1025):     ... 11 more

So obviously the network connection on main thread problem means I need to move this into an Asynctask, right? But with such a bevy of errors, I wonder if I am missing something else, that's obvious? I eventually want to be able to register user/passwords onto a database, then get queries and send responses, so this is just a warm up basically. If you goto http://www.davidjkelley.net/city.php you can see that the database is indeed properly responding to the query PHP file that I have linked inside the Android code, so that's not the problem.

Edit~ I should note that my Activity previously extended list Activity, following this tutorial: http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/ which is why my XML is just a ListView at the moment, because that helped clear up an error that said I needed a ListView component with the id 'list'.

Edit~ My php code:

<?php
mysql_connect("127.0.0.1","***","***");
mysql_select_db("***");
$sql=mysql_query("select * from CITY where CITY_NAME like 'A%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

Obviously the sets of stars are the correct information, as when you visited the link posted above, the SQL readout appears properly.

doushao8399
doushao8399 对于异步,这看起来像是一个开始的地方:vogella.de/articles/AndroidPerformance/article.html特别参见第5节。
8 年多之前 回复
drt3751
drt3751 你想解释一下吗?我问过如何为此创建一个Asynctask...
8 年多之前 回复
dongzuo7166
dongzuo7166 如果你得到NetworkOnMainThreadException,它就像它获得的那样基本。先解决这个问题。你正在使用mysqlDB访问.php页面这一事实是一个副问题。您可能甚至没有发送过SYN数据包......
8 年多之前 回复

1个回答



您如何运行数据库? 发布PHP连接的方式可能更相关。 很可能在PHP中,您没有将请求从应用程序连接到实际数据库(使用不正确的URL或数据库本身的名称)。 查看此</ a >教程。 我可以确认它工作正常,它似乎也完成了你需要的功能。 在该教程中,有关于更改代码的位置的说明,以便您可以在托管服务器而不是localhost上运行它。 </ p>
</ div>

展开原文

原文

How are your running your database? Posting how the PHP connects may be more relevant. It's very possible that in the PHP you aren't connecting the request from the app to the actual database (either with an incorrect url or the name of the database itself). Check out this tutorial. I can confirm it works fine and it seems to accomplish the functionality you need as well. In that tutorial there are notes on where to change the code so that you can run it on your hosted server instead of localhost.

duanba7653
duanba7653 一切正常。 我讨厌承认它,但我觉得我错误地在UserFunctions中添加了一行,因为当我从教程中重新复制/粘贴(并再次更新我的URL)时,它工作得很好。 解决方案:)
8 年多之前 回复
dongtuo4723
dongtuo4723 所以看起来我正在正确地纠正数据库。 在dB名称之前有一个带下划线的用户前缀,但我已经有了。 看起来我连接正常,因为当我在网页上运行city.php脚本时,它会打印出表中的数据。
8 年多之前 回复
dongwen1935
dongwen1935 对于godaddy我需要登录我创建数据库的位置并进入配置面板。 NameCheap应该有类似的东西
8 年多之前 回复
dongzhi9574
dongzhi9574 NameCheap。 我将调查一下,你知道通过CPanel找到正确URL的方法吗? 当我进入FTP时,我似乎没有任何关于db的文件结构。
8 年多之前 回复
douzhang5199
douzhang5199 你主持谁? 我遇到了类似的错误(我之所以提到php的原因),因为你无法将它连接到davidkjelly.net/city/。 在我的情况下因为我使用godaddy我需要连接到mydatabasename.db.idnumber.hostedresource.com
8 年多之前 回复
dongwaner1367
dongwaner1367 KDEx,只是想让你知道我重新创建了这个教程,差不多写了一封带有复制粘贴的字母。 我唯一改变的是在线实际服务器的本地主机IP地址。 我最终遇到了我在原始问题NetworkOnMainThreadException中遇到的同样错误。 有什么建议?
8 年多之前 回复
dragon4587
dragon4587 另外,谢谢你的链接。 一旦我掌握了这个基本方面,我就会使用它!
8 年多之前 回复
douqiao7188
douqiao7188 查看最新的更新。
8 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐