将android应用程序连接到服务器上的数据库?

时间:2012-03-18 11:10:44

标签: java php android mysql json

我试图在我的数据库MYSQL(使用WAMP服务器的iam)和android应用程序之间建立连接,但是当我运行应用程序引发异常时,我修复了日志cat及其指向此语句的内容 jArray = new JSONArray(result);

03-18 12:48:59.580: E/AndroidRuntime(458):  at org.json.JSONArray.<init>(JSONArray.java:87)

为什么会发生这种异常?以及我如何解决它?

感谢先进..

这是我的代码: 的 City.php:

          <?php
           mysql_connect("localhost","username","password");
           mysql_select_db("Deal");
           $sql=mysql_query("select * from City where Name like 'R%' ");
           while($row=mysql_fetch_assoc($sql))
           $output[]=$row;
           print(json_encode($output));
           mysql_close();
              ?>

java类:

public class ConnectionActivity extends ListActivity {

int ct_id;
String[] ct_name = null;
JSONArray jArray;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;

    // http post
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://localhost/city.php");
                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() + "\n");
                String line = "0";
                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());
            }

            // paring data

            try {
                jArray = new JSONArray(result);
                JSONObject json_data = null;
                ct_name = new String[jArray.length()];
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    ct_id = json_data.getInt("City_ID");
                    ct_name[i] = json_data.getString("Name");
                }
            } catch (JSONException e1) {
                Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG)
                        .show();
            } catch (ParseException e1) {
                e1.printStackTrace();
            }

            ListView lv;
            lv = getListView();
            lv.setTextFilterEnabled(true);
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ct_name);
            setListAdapter(adapter);



}
public void onListItemClick(ListView parent, View v, int position, long id)
{
        Toast.makeText(this,"You have selected " + ct_name[position],Toast.LENGTH_SHORT).show();
        }
}                      

登录

             03-18 13:28:46.923: W/ActivityThread(623): Application Com.Connection is waiting for the debugger on port 8100...
             03-18 13:28:46.973: I/System.out(623): Sending WAIT chunk
             03-18 13:28:46.983: I/dalvikvm(623): Debugger is active
             03-18 13:28:47.174: I/System.out(623): Debugger has connected
             03-18 13:28:47.183: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:47.383: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:47.583: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:47.783: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:47.993: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:48.193: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:48.403: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:48.603: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:48.803: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:49.003: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:49.203: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:49.413: I/System.out(623): waiting for debugger to settle...
             03-18 13:28:49.613: I/System.out(623): debugger has settled (1497)
             03-18 13:30:17.593: E/log_tag(623): Error in http       connectionandroid.os.NetworkOnMainThreadException
               03-18 13:30:34.315: E/log_tag(623): Error converting result java.lang.NullPointerException

1 个答案:

答案 0 :(得分:1)

当您尝试在主线程上执行HTTP连接时出现错误:

03-18 13:30:17.593: E/log_tag(623): Error in http       connectionandroid.os.NetworkOnMainThreadException

据我所知,HTTP代码是正确的,但您在UI线程上运行它。这是不允许的。您需要在后台线程上执行此类长时间操作。 Android为您提供了一个非常易于使用的工具,可以在后台执行长时间的操作,并在主(UI)线程上发布结果。其中最有用的是AsyncTask。我建议你阅读Painless Threading,因为它会帮助你很多IMO。

相关问题