php - Android 到 MYSQL 使用 php

标签 php android mysql

嗨,我正在这里学习本教程 http://fahmirahman.wordpress.com/2011/04/21/connection-between-php-server-and-android-client-using-http-and-json并且无法获得预期的结果,这是我在我的网站 techiequickie.com/food.php 上的 food.php 文件

然后这是我试图放入我的 andorid main.java 文件中的代码

    package com.connectsql.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

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

public class ConnectsqlActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



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



        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://techiequickie.com/food.php");
            List<? extends NameValuePair> nameValuePairs = null;
            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() + "\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
        int fd_id;
        String fd_name;
        try{
        JSONArray jArray = new JSONArray(result);
        JSONObject json_data=null;

        for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                fd_id=json_data.getInt("FOOD_ID");
                fd_name=json_data.getString("FOOD_NAME");
        }

        }catch(JSONException e1){
            Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
        }catch (ParseException e1){
            e1.printStackTrace();
        }

    }
}

我收到的错误是应用程序意外关闭,所以我不明白我必须做什么才能完成这项工作,因为我的 main.xml 是默认的,因为我没有在其中添加任何控件。 下面是我的 main.xml 代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.82"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>

谢谢

LOGCAT错误

01-30 16:07:12.155: D/AndroidRuntime(787): Shutting down VM
01-30 16:07:12.155: W/dalvikvm(787): threadid=1: thread exiting with uncaught exception (group=0x40015560)
01-30 16:07:12.175: E/AndroidRuntime(787): FATAL EXCEPTION: main
01-30 16:07:12.175: E/AndroidRuntime(787): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.connectsql.test/com.connectsql.test.ConnectsqlActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.os.Looper.loop(Looper.java:123)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-30 16:07:12.175: E/AndroidRuntime(787):  at java.lang.reflect.Method.invokeNative(Native Method)
01-30 16:07:12.175: E/AndroidRuntime(787):  at java.lang.reflect.Method.invoke(Method.java:507)
01-30 16:07:12.175: E/AndroidRuntime(787):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-30 16:07:12.175: E/AndroidRuntime(787):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-30 16:07:12.175: E/AndroidRuntime(787):  at dalvik.system.NativeStart.main(Native Method)
01-30 16:07:12.175: E/AndroidRuntime(787): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.ListActivity.onContentChanged(ListActivity.java:243)
01-30 16:07:12.175: E/AndroidRuntime(787):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:210)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.Activity.setContentView(Activity.java:1657)
01-30 16:07:12.175: E/AndroidRuntime(787):  at com.connectsql.test.ConnectsqlActivity.onCreate(ConnectsqlActivity.java:30)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-30 16:07:12.175: E/AndroidRuntime(787):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-30 16:07:12.175: E/AndroidRuntime(787):  ... 11 more

@Sergey logcat 错误请注意我修改后的 main.xml 代码如下

01-31 00:39:20.625: E/log_tag(424): Error in http connectionjava.net.UnknownHostException: techiequickie.com
01-31 00:39:20.625: E/log_tag(424): Error converting result java.lang.NullPointerException
01-31 00:39:20.625: D/AndroidRuntime(424): Shutting down VM
01-31 00:39:20.625: W/dalvikvm(424): threadid=1: thread exiting with uncaught exception (group=0x40015560)
01-31 00:39:20.665: E/AndroidRuntime(424): FATAL EXCEPTION: main
01-31 00:39:20.665: E/AndroidRuntime(424): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysql/com.mysql.MysqlconActivity}: java.lang.NullPointerException
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.os.Looper.loop(Looper.java:123)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-31 00:39:20.665: E/AndroidRuntime(424):  at java.lang.reflect.Method.invokeNative(Native Method)
01-31 00:39:20.665: E/AndroidRuntime(424):  at java.lang.reflect.Method.invoke(Method.java:507)
01-31 00:39:20.665: E/AndroidRuntime(424):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-31 00:39:20.665: E/AndroidRuntime(424):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-31 00:39:20.665: E/AndroidRuntime(424):  at dalvik.system.NativeStart.main(Native Method)
01-31 00:39:20.665: E/AndroidRuntime(424): Caused by: java.lang.NullPointerException
01-31 00:39:20.665: E/AndroidRuntime(424):  at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
01-31 00:39:20.665: E/AndroidRuntime(424):  at com.mysql.MysqlconActivity.onCreate(MysqlconActivity.java:66)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-31 00:39:20.665: E/AndroidRuntime(424):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-31 00:39:20.665: E/AndroidRuntime(424):  ... 11 more
01-31 00:39:28.775: I/Process(424): Sending signal. PID: 424 SIG: 9
01-31 00:43:37.995: E/log_tag(473): Error in http connectionjava.net.UnknownHostException: techiequickie.com
01-31 00:43:37.995: E/log_tag(473): Error converting result java.lang.NullPointerException
01-31 00:43:37.995: D/AndroidRuntime(473): Shutting down VM
01-31 00:43:37.995: W/dalvikvm(473): threadid=1: thread exiting with uncaught exception (group=0x40015560)
01-31 00:43:38.036: E/AndroidRuntime(473): FATAL EXCEPTION: main
01-31 00:43:38.036: E/AndroidRuntime(473): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysql/com.mysql.MysqlconActivity}: java.lang.NullPointerException
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.os.Looper.loop(Looper.java:123)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-31 00:43:38.036: E/AndroidRuntime(473):  at java.lang.reflect.Method.invokeNative(Native Method)
01-31 00:43:38.036: E/AndroidRuntime(473):  at java.lang.reflect.Method.invoke(Method.java:507)
01-31 00:43:38.036: E/AndroidRuntime(473):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-31 00:43:38.036: E/AndroidRuntime(473):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-31 00:43:38.036: E/AndroidRuntime(473):  at dalvik.system.NativeStart.main(Native Method)
01-31 00:43:38.036: E/AndroidRuntime(473): Caused by: java.lang.NullPointerException
01-31 00:43:38.036: E/AndroidRuntime(473):  at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
01-31 00:43:38.036: E/AndroidRuntime(473):  at com.mysql.MysqlconActivity.onCreate(MysqlconActivity.java:61)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-31 00:43:38.036: E/AndroidRuntime(473):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-31 00:43:38.036: E/AndroidRuntime(473):  ... 11 more

修改了 main.xml,我在下面附上了屏幕截图,因为我添加了 ListView ,并且从您的代码中,您引用 test_text 字段的最后一行说“tv.setText(fd_id+”“+fd_name);”但试图理解这一行。tks 付出了所有的努力。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/test_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>

最佳答案

您必须将以下内容添加到您的布局中,因为您正在扩展 ListActivity

<ListView android:id="@android:id/list"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             />

否则我可以在本示例中使用 HttpGet。

编辑: 布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/test_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello" />

    <ListView android:id="@android:id/list"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                />

</LinearLayout>

代码:

import org.apache.http.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.client.methods.HttpGet;

import android.widget.TextView;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class ConnectsqlActivity extends ListActivity {

       @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String result = null;
        InputStream is = null;
        StringBuilder sb=null;

        try{
            DefaultHttpClient httpclient = new DefaultHttpClient();
        //    setProxy(httpclient,"yourproxyorIP",9090,"username","password"); //use your proxy's port

            HttpGet httppost = new HttpGet("http://techiequickie.com/food.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());
        }
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            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());
        }
        System.out.println(result);
        //paring data
        int fd_id=0;
        String fd_name=null;
        try{
        JSONArray jArray = new JSONArray(result);
        JSONObject json_data=null;

        for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                fd_id=json_data.getInt("FOOD_ID");
                fd_name=json_data.getString("FOOD_NAME");
        }

        }catch(JSONException e1){
            Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
        }catch (ParseException e1){
            e1.printStackTrace();
        }
        setContentView(R.layout.test);
        TextView tv = (TextView)findViewById(R.id.test_text);
        tv.setText(fd_id+" "+fd_name);

    }

private static void setProxy (DefaultHttpClient httpClient,
                String proxy,int port,String username,String password)
{
    HttpParams params = httpClient.getParams();
    params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
            new HttpHost( proxy,port));
    if(username!=null&&password!=null){
    httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(proxy, port),
                new UsernamePasswordCredentials(username, password)
        );
    }
    httpClient.setParams(params);
}


}

关于php - Android 到 MYSQL 使用 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066684/

相关文章:

php - 数据库中的图像未加载 PHP PDO

php - 如何在 Laravel 的 Controller 重定向时显示成功消息?

java - Android 和 Guice - 注入(inject)通用类型类?

mysql - 连接到 azure 的Mysql服务器

php - sql 中具有 'type' 列的每个日期的金额总和

mysql - 选择 NULL,否则每组的最新日期

php - 如何传递数组/函数来查看页面? [超频]

php - sql left join 不工作

java - 按下后退按钮时不加载新首选项

android - 比从res加载声音更好的方法来在android游戏中加载声音