如何连接使用一个异步任务的android到PHP? [英] How to connect to php in android using an async task?

查看:103
本文介绍了如何连接使用一个异步任务的android到PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个Android应用程序检索从我的服务器上的PHP文件中的数据。我一直在寻找2天工作示例和所有我能找到是这样的:

I want to retrieve data from a php file on my server from an android application. I have been searching for a working example for 2 days now and all I can found is this:

HTTP://www.androidaspect。 COM / 2013/05 /如何对连接功能的Andr​​oid与 - php.html
<一href=\"http://fahmirahman.word$p$pss.com/2011/04/21/connection-between-php-server-and-android-client-using-http-and-json/\" rel=\"nofollow\">http://fahmirahman.word$p$pss.com/2011/04/21/connection-between-php-server-and-android-client-using-http-and-json/

我也看了一下对这样类似的问题有很大的数字,但我试图重新创建此是徒劳无益的。所以,请原谅我,如果你觉得我的问题是重复的。

I have also looked at a great number of similar questions on SO, but my attempts to recreate this have been futile. So please excuse me if you think my question as a duplicate.

我基本上要检索PHP脚本这样的呼应PHP数据:

I basically want to retrieve echoed php data on a php script like this:

<?php
echo "Hello PHP";
?>

在一个TextView显示出来。

and display it in a TextView.

下面是我的主要活动code称为Home_Activity.java

Here is my Main activity code called Home_Activity.java

package com.example.httppost;


import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // TextView to display result
    TextView textView = (TextView) findViewById(R.id.text_display);
    new GetData(textView).execute("");
}

private class GetData extends AsyncTask<String, Void, String> {
private TextView display;

GetData(TextView view){
    this.display = view;
}

 protected String doInBackground(String... message) {
    HttpClient httpclient;
    HttpGet request;
    HttpResponse response = null;
    String result = "error";
    // TextView to display result

    // Try to connect using Apache HttpClient Library
    try {
        httpclient = new DefaultHttpClient();
        request = new HttpGet("http://10.0.2.2:8080/food.php");
        response = httpclient.execute(request);
    }

    catch (Exception e) {
        // Code to handle exception
        result = "error";
    }

    // response code
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {

            // Appending result to textview
            result = result + line ;
        }
    } catch (Exception e) {
        // Code to handle exception
        result = "error";
    }
    return result;
}

protected void onPostExecute(String result) {
    this.display.setText(result);
}

}}

错误日志看起来像天书。该程序执行一下后,我得到了可怕的不幸的是home_automation已停止。
我认为这与我试图设置异步任务中的TextView的做,但我不知道如何解决,或是否不是我的code发送HTTP请求是正确的。
我所知道的是,PHP和服务器上的东西是正确的。
所有教程演示如何在主线程中执行此操作。当我这样做,我一直得到上​​主胎面错误信息的事情网络。这是使用HTTP请求和异步任务,我的第一个应用程序。
我边衬的疯狂。通过展示我哪里出了错,并且由于事先请帮帮忙!

The error log looks like hieroglyphics. The program executes briefly and then I get the dreaded "Unfortunately home_automation has stopped." I think it has to do with me attempting to set the textView within the Async task but I have no idea how to fix that or whether or not my code for sending the http request is correct. What I do know is that the php and server stuff is correct. All tutorials show how to do this within the main thread. When i did that i kept getting a Network on main tread error message thing. This is my first app using http requests and Async tasks. I am border lining insanity. Please help by showing me where i went wrong and thanks in advance!

编辑:
这里是我的堆栈跟踪:

Here is my stacktrace:

 FATAL EXCEPTION: main
 java.lang.NullPointerException
at com.example.httppost.MainActivity$GetData.onPostExecute(MainActivity.java:69)
at com.example.httppost.MainActivity$GetData.onPostExecute(MainActivity.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

我99%肯定,问题出在了 textView.setText(结果);
我已经编辑我的code,但我仍然得到空指针异常

I am 99% sure that the problem lies in the the textView.setText(result); I have edited my code but I'm still getting the NullPointer exception

推荐答案

对不起家伙,我觉得像这样的小白。必须小心删除了

Sorry guys i feel like such a noob. Must have accidentally deleted the

setContentView(R.layout.activity_main);

这解释了为什么该应用程序是pmaturely停止$ P $。
我还忘了实例化我异步类的TextView这也解释了空指针。谢谢大家的意见和帮助!

Which explains why the application was stopping prematurely. I also forgot to instantiate the TextView in my Async class which explains the null pointer. Thank you all for the comments and help!

这篇关于如何连接使用一个异步任务的android到PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆