【问题标题】:How can I get data from PHP to Android TextView?如何从 PHP 获取数据到 Android TextView?
【发布时间】:2013-08-16 01:01:47
【问题描述】:

如何从 PHP 获取数据到 Android?

你能帮帮我吗?如何将 PHP 的结果显示到 android textview 这是我的 PHP 代码我应该在这个上使用 JSON...

<? php
mysql_connect("localhost","root","");

mysql_select_db("mydatabase");

$query = "SELECT SUM(OrderPrice) as total FROM tbl_user";
$result = mysql_query($query);


while($row = mysql_fetch_assoc($result))
{
$new_arr[] = $row['total'];
}
echo json_encode($new_arr);

?>

【问题讨论】:

  • 你必须在最后通过 JSON 解析数据
  • 你能给我看看代码吗?
  • 您需要与网络服务器建立一个 GET 或 POST HTTPConnection 以从您的网络服务器获取数据。然后需要在Android端使用JSON解析来解析数据。

标签: php android json


【解决方案1】:

假设这是您的 php 文件 db.php,其中包含数据库“deal”和表“city”,其中包含字段 CITY_ID 和 CITY_NAME

<?php

$con = mysql_connect('localhost', 'root', '');

if (!$con)
{
die("could not connect: " + mysql_error());
}
mysql_select_db("deal", $con);

$result=mysql_query("SELECT * FROM city ", $con);
while ($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);   
?>

【讨论】:

  • 我使用这段代码显示错误解析数据 org.json.JSONException: Value ype java.lang.String cannot be convert to JSONArray @Aditya Harsh
【解决方案2】:

问题在于您是直接在您的设备上读取 php,还是从您的网络服务器请求它。你可以做第一个,但你必须在你的设备上安装一个网络服务器,也许是 apache,cos“localhost 和 127.0.0.1”可能在没有网络服务器的情况下工作,你可以使用以下类或库从中获取数据,它可能是 dam !第二个很简单,把你的 php 放在你的服务器上,客户端应用程序通过 http/https 等调用它:

  1. 简单连接:

    public static class Connector extends AsyncTask<String, Object, Object> {
    private static final int   DEFAULT_CNN_TIME_OUT = 1000 * 20;
    private static String      USER_AGENT;
    private static final int[] LOCK                 = new int[1];
    private String             mUrl;
    private byte[]             mBody;
    
    public Connector( Context _cxt ) {
        super();
        if( TextUtils.isEmpty( USER_AGENT ) ) {
            // Without this, the default provided by API will be like "Dalvik/1.6.0 (Linux; U; Android 4.0.4; BASE_Lutea_3 Build/IMM76D)" .
            USER_AGENT = new WebView( _cxt ).getSettings().getUserAgentString();
        }
    }
    
    /*
     * Convenient function to execute the connecting task.
     */
    public void submit( String _url ) {
        this.execute( _url );
    }
    
    @Override
    protected Object doInBackground( String... _params ) {
        mUrl = _params[0];
        Object ret = null;
        HttpURLConnection conn = null;
        try {
            synchronized( LOCK ) {
                InputStream in = null;
                conn = connect( mUrl );
                // if we don't do conn.setRequestProperty( "Accept-Encoding", "gzip" ), the wrapper GZIPInputStream can be removed.
                onConnectorInputStream( in = new GZIPInputStream( conn.getInputStream() ) );
                in.close();
                in = null;
            }
        }
        catch( Exception _e ) {
            ret = _e;
        }
        finally {
            if( conn != null ) {
                conn.disconnect();
                conn = null;
            }
        }
        return ret;
    }
    
    @Override
    protected void onPostExecute( Object _result ) {
        if( _result instanceof SocketTimeoutException ) {
            onConnectorConnectTimout();
        } else if( _result instanceof ConnectorPostConnectException ) {
            onConnectorError( ((ConnectorPostConnectException) _result).getStatus() );
        } else if( _result instanceof Exception ) {
            onConnectorInvalidConnect( (Exception) _result );
        } else if( _result == null ) {
            onConnectorFinished();
        }
        handleEstablishedConnection();
    }
    
    /*
     * Internal help and test function.
     */
    private static void handleEstablishedConnection() {
        try {
            Log.v( TAG, "Connection is established." );
            CookieStore cs = CookieManager.getInstance().getCookieStore();
            if( cs != null ) {
                Log.v( TAG, "------------cookies------------" );
                List<Cookie> list = cs.getCookies();
                if( list != null && list.size() > 0 ) {
                    StringBuilder cookieBuilder = new StringBuilder();
                    for( Cookie c : list ) {
                        cookieBuilder
                                .append( c.getName().trim() )
                                .append( "=>" )
                                .append( c.getValue().trim() )
                                .append( "=>" )
                                .append( c.getDomain() );
                        Log.v( TAG, cookieBuilder.toString() );
                        cookieBuilder.delete( 0, cookieBuilder.length() - 1 );
                    }
                    cookieBuilder = null;
                } else {
                    Log.v( TAG, "Empty cookies." );
                }
                cs = null;
                list = null;
            }
        }
        catch( Exception _e ) {
            Log.e( TAG, "Error in handleEstablishedConnection: " + _e.getMessage() );
        }
        finally {
        }
    }
    
    private HttpURLConnection connect( String _urlStr ) throws Exception {
        URL url = null;
        HttpURLConnection conn = null;
        try {
            try {
                url = new URL( _urlStr );
            }
            catch( MalformedURLException e ) {
                throw new IllegalArgumentException( "Invalid url: " + _urlStr );
            }
            conn = preConnect( url );
            doConnect( conn );
            conn = postConnect( conn );
        }
        catch( Exception _e ) {
            throw _e;
        }
        finally {
            url = null;
        }
        return conn;
    }
    
    private HttpURLConnection preConnect( URL url ) throws Exception {
        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches( false );
        // http://www.aswinanand.com/2009/01/httpurlconnectionsetfollowredirects-bug/comment-page-1/#comment-13330
        // see the url to learn more about the problem of redirect
        conn.setInstanceFollowRedirects( false );
        conn.setDoOutput( true );// allows body
        mBody = getBody();
        if( hasBody() ) {
            conn.setFixedLengthStreamingMode( mBody.length );
        }
        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Connection", "Keep-Alive" );
        conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8" );
        conn.setRequestProperty( "User-Agent", USER_AGENT );
        conn.setRequestProperty( "Accept-Encoding", "gzip" );// force server to send in Content-Encoding: gzip .
        String cookies = onCookie();
        if( !TextUtils.isEmpty( cookies ) ) {
            conn.setRequestProperty( "Cookie", onCookie() );
            cookies = null;
        }
        conn.setConnectTimeout( onSetConnectTimeout() );
        return conn;
    }
    
    /*
     * Convenient function to check the exiting of body.
     */
    private boolean hasBody() {
        return mBody != null && mBody.length > 0;
    }
    
    private void doConnect( HttpURLConnection conn ) throws Exception {
        OutputStream out; // the outgoing stream
        out = conn.getOutputStream();
        if( hasBody() ) {
            out.write( mBody );
        }
        out.close();
        out = null;
    }
    
    private HttpURLConnection postConnect( HttpURLConnection conn ) throws Exception {
        int status = conn.getResponseCode();
        if( status != HttpURLConnection.HTTP_OK ) {
            throw new ConnectorPostConnectException( status );
        } else {
            CookieManager.getInstance().put( conn.getURL().toURI(), conn.getHeaderFields() );
            return conn;
        }
    }
    
    private byte[] getBody() {
        byte[] body = null;
        String bodyString = onSetBody();
        if( !TextUtils.isEmpty( bodyString ) ) {
            body = bodyString.getBytes();
        }
        return body;
    }
    
    // ------------------------------------------------
    // Overrides methods here
    // ------------------------------------------------
    
    protected int onSetConnectTimeout() {
        return DEFAULT_CNN_TIME_OUT;
    }
    
    protected String onCookie() {
        return null;
    }
    
    protected String onSetBody() {
        return null;
    }
    
    protected void onConnectorConnectTimout() {
        Log.e( TAG, "Handling connector timeout gracefully." );
    }
    
    protected void onConnectorError( int _status ) {
        Log.e( TAG, "Handling connector error(responsed) gracefully: " + _status );
    }
    
    protected void onConnectorInvalidConnect( Exception _e ) {
        Log.e( TAG, "Handling connector invalid connect(crash) gracefully: " + _e.toString() );
    }
    
    /*
     * Read data here. The function runs in thread. To hook on UI thread use onConnectorFinished()
     */
    protected void onConnectorInputStream( InputStream _in ) {
    }
    
    /*
     * Last handler for a success connection
     */
    protected void onConnectorFinished() {
    }
    }
    
  2. 使用 Volley 获得响应:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java

  3. 使用jsoup获取“原始html”:http://jsoup.org/

【讨论】:

    【解决方案3】:

    恐怕我无法发表评论,但本教程一定会对您有所帮助。简而言之,您使用HttpUrlConnection 读取JSON 页面,然后使用org.json.JSONObject 进行解析。

    http://ihofmann.wordpress.com/2012/08/09/restful-web-services-with-json-in-android/

    【讨论】:

      【解决方案4】:

      您好,您可以使用这些链接:

      parse JSON in android, Android JSON Parsing Tutorial

      【讨论】:

        猜你喜欢
        • 2012-11-27
        • 2012-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多