java 从数据库中获取数据并将其显示在android应用程序上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13908920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:24:16  来源:igfitidea点击:

get data from database and display it on android application

javaphpandroidmysqlxml

提问by Mona

I have design my database on MySQL and link it through php. how can i get it on android application by using HTTP GET method??? i used JSON Parsing for this purpose to get data from MYSQL but i fails to display:(( Now i want to get data from HTTP GET request so how can i use it?? does i upload my database on server??? how can i upload it?? and what is the method for it. i'll be thankful to you for help

我在 MySQL 上设计了我的数据库并通过 php 链接它。如何使用 HTTP GET 方法在 android 应用程序上获取它???我为此使用了 JSON 解析从 MYSQL 获取数据,但我无法显示:((现在我想从 HTTP GET 请求中获取数据,所以我该如何使用它??我是否将我的数据库上传到服务器上???我上传了??方法是什么。谢谢你的帮助

MySQL database is:

MySQL数据库是:

    <?php
// read_My_Task.php


/*
 * Following code will get single task details
 * A task_detail is identified by task id (cid)
 */
 // array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["cid"])) {
    $cid = $_GET['cid'];

    // get a task from my-task table
    $result = mysql_query("SELECT *FROM my_task WHERE cid = $cid");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);

            $my_task = array();
            $my_task["cid"] = $result["cid"];
            $my_task["cus_name"] = $result["cus_name"];
            $my_task["contact_number"] = $result["contact_number"];
            $my_task["ticket_no"] = $result["ticket_no"];
            $my_task["task_detail"] = $result["task_detail"];

            // user node
            $response["my_task"] = array();

            array_push($response["my_task"], $my_task);
            // echoing JSON response
            echo json_encode($response);         
             }            

        else {
            // no task found
            $response["success"] = 0;
            $response["message"] = "No task found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no task found
        $response["success"] = 0;
        $response["message"] = "No task found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}

?>

LogCat errors are:

LogCat 错误是:

12-17 11:00:39.180: W/System.err(10667): org.apache.http.conn.ConnectTimeoutException: Connect to /198.168.0.29:80 timed out
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-17 11:00:39.180: W/System.err(10667):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-17 11:00:39.180: W/System.err(10667):    at com.example.visit.record.JSONParser.makeHttpRequest(JSONParser.java:62)
12-17 11:00:39.180: W/System.err(10667):    at com.example.visit.record.My_Task$GetTaskDetails.doInBackground(My_Task.java:170)
12-17 11:00:39.180: W/System.err(10667):    at com.example.visit.record.My_Task$GetTaskDetails.doInBackground(My_Task.java:1)
12-17 11:00:39.180: W/System.err(10667):    at android.os.AsyncTask.call(AsyncTask.java:185)
12-17 11:00:39.180: W/System.err(10667):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-17 11:00:39.180: W/System.err(10667):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-17 11:00:39.180: W/System.err(10667):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-17 11:00:39.180: W/System.err(10667):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-17 11:00:39.190: W/System.err(10667):    at java.lang.Thread.run(Thread.java:1027)
12-17 11:00:39.190: E/Buffer Error(10667): Error converting result java.lang.NullPointerException
12-17 11:00:39.190: E/JSON Parser(10667): Error parsing data org.json.JSONException: End of input at character 0 of 
12-17 11:00:39.190: W/dalvikvm(10667): threadid=9: thread exiting with uncaught exception (group=0x400205a0)
12-17 11:00:39.200: E/AndroidRuntime(10667): FATAL EXCEPTION: AsyncTask #1
12-17 11:00:39.200: E/AndroidRuntime(10667): java.lang.RuntimeException: An error occured while executing doInBackground()
12-17 11:00:39.200: E/AndroidRuntime(10667):    at android.os.AsyncTask.done(AsyncTask.java:200)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.lang.Thread.run(Thread.java:1027)
12-17 11:00:39.200: E/AndroidRuntime(10667): Caused by: java.lang.NullPointerException
12-17 11:00:39.200: E/AndroidRuntime(10667):    at com.example.visit.record.My_Task$GetTaskDetails.doInBackground(My_Task.java:174)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at com.example.visit.record.My_Task$GetTaskDetails.doInBackground(My_Task.java:1)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at android.os.AsyncTask.call(AsyncTask.java:185)
12-17 11:00:39.200: E/AndroidRuntime(10667):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-17 11:00:39.200: E/AndroidRuntime(10667):    ... 4 more
12-17 11:00:39.510: E/WindowManager(10667): Activity com.example.visit.record.My_Task has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4054caf0 that was originally added here
12-17 11:00:39.510: E/WindowManager(10667): android.view.WindowLeaked: Activity com.example.visit.record.My_Task has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4054caf0 that was originally added here
12-17 11:00:39.510: E/WindowManager(10667):     at android.view.ViewRoot.<init>(ViewRoot.java:277)
12-17 11:00:39.510: E/WindowManager(10667):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
12-17 11:00:39.510: E/WindowManager(10667):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
12-17 11:00:39.510: E/WindowManager(10667):     at android.view.Window$LocalWindowManager.addView(Window.java:433)
12-17 11:00:39.510: E/WindowManager(10667):     at android.app.Dialog.show(Dialog.java:288)
12-17 11:00:39.510: E/WindowManager(10667):     at com.example.visit.record.My_Task$GetTaskDetails.onPreExecute(My_Task.java:149)
12-17 11:00:39.510: E/WindowManager(10667):     at android.os.AsyncTask.execute(AsyncTask.java:391)
12-17 11:00:39.510: E/WindowManager(10667):     at com.example.visit.record.My_Task.onCreate(My_Task.java:108)
12-17 11:00:39.510: E/WindowManager(10667):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
12-17 11:00:39.510: E/WindowManager(10667):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1785)
12-17 11:00:39.510: E/WindowManager(10667):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1842)
12-17 11:00:39.510: E/WindowManager(10667):     at android.app.ActivityThread.access00(ActivityThread.java:132)
12-17 11:00:39.510: E/WindowManager(10667):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038)
12-17 11:00:39.510: E/WindowManager(10667):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-17 11:00:39.510: E/WindowManager(10667):     at android.os.Looper.loop(Looper.java:143)
12-17 11:00:39.510: E/WindowManager(10667):     at android.app.ActivityThread.main(ActivityThread.java:4268)
12-17 11:00:39.510: E/WindowManager(10667):     at java.lang.reflect.Method.invokeNative(Native Method)
12-17 11:00:39.510: E/WindowManager(10667):     at java.lang.reflect.Method.invoke(Method.java:507)
12-17 11:00:39.510: E/WindowManager(10667):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-17 11:00:39.510: E/WindowManager(10667):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-17 11:00:39.510: E/WindowManager(10667):     at 

it gives error:

它给出了错误:

Status Code: 404 Not Found
Accept-Ranges: bytes
Content-Language: en
Content-Type: text/html; charset=iso-8859-1
Date: Mon, 17 Dec 2012 06:40:56 GMT
Keep-Alive: timeout=5, max=100
Proxy-Connection: Keep-Alive
Server: Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
Transfer-Encoding: chunked
Vary: accept-language,accept-charset


Method: POST
URL: http://192.168.0.29/mobile/read_mytask.php?cid=1
Body: 
cid=cid &
cus_name=c
& contact_no=n
& ticket_no=t
& taskdetail=td

回答by Anup Cowkur

I'll give you an overview on how client-server data retrieval works in Android. You can tailor it to your specific requirements from there since your question indicates large foundational knowledge gaps to me.

我将概述客户端-服务器数据检索在 Android 中的工作原理。您可以从那里根据您的特定要求定制它,因为您的问题表明我存在很大的基础知识差距。

You'll have to create REST API's (by writing server side code using a language like PHP, Ruby, Python etc) that your Android app can consume to obtain the data from your MySQL database.

您必须创建 REST API(通过使用 PHP、Ruby、Python 等语言编写服务器端代码),您的 Android 应用程序可以使用这些 API 从您的 MySQL 数据库中获取数据。

There are other options that avoid REST API's as well. See:

还有其他选项可以避免 REST API。看:

How to get from a MySql server to an Android app?

如何从 MySql 服务器到 Android 应用程序?

See here for a beginners tutorial on REST:

有关 REST 的初学者教程,请参见此处:

http://net.tutsplus.com/tutorials/other/a-beginners-introduction-to-http-and-rest/

http://net.tutsplus.com/tutorials/other/a-beginners-introduction-to-http-and-rest/

Once you have your API's written. You can query them using HTTP GET request and parse the result. If you are returning the data in JSON format, here's a tutorial on how to parse it:

一旦你编写了 API。您可以使用 HTTP GET 请求查询它们并解析结果。如果您以 JSON 格式返回数据,这里有一个关于如何解析它的教程:

http://www.vogella.com/articles/AndroidJSON/article.html

http://www.vogella.com/articles/AndroidJSON/article.html

Now you can store the parsed data on your local database using the native android methods. See db tutorial here:

现在,您可以使用原生 android 方法将解析后的数据存储在本地数据库中。请参阅此处的数据库教程:

http://www.vogella.com/articles/AndroidSQLite/article.html

http://www.vogella.com/articles/AndroidSQLite/article.html

Once all this is over. You can do CRUD operations on your local database to read/manipulate your data and display them to the user using the XML based Android UI.

一旦这一切结束。您可以在本地数据库上执行 CRUD 操作以读取/操作您的数据并使用基于 XML 的 Android UI 将它们显示给用户。

回答by Virendra Parihar

public class JsonHelper 
{
    static String response = null;
    String jsonRes = "";
    public JSONObject JObj=null;
    public final static int GET = 1;
    public final static int POST = 2;

//  public final static String fullUrl = "http://10.0.2.2/fluentcmsonline/";

public JsonHelper()
    {

    }

    public JSONObject MakeJsonCall(String Url,int method)
    {
        return this.MakeJsonCall(Url, method, null);
    }

    public JSONObject MakeJsonCall(String Url,int method, List<NameValuePair> params)
    {
        try
        {
            DefaultHttpClient HttpClient = new DefaultHttpClient();
            HttpEntity httpentity = null;
            HttpResponse httprespo = null;
            if(method==POST)
            {
                 HttpPost httppost = new HttpPost(fullUrl+Url);
                //HttpPost httppost = new HttpPost(Url);
                if(params != null)
                {
                    httppost.setEntity(new UrlEncodedFormEntity(params));
                }

                httprespo = HttpClient.execute(httppost);
            }
            else
            {
                if(params != null)
                {
                    String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);

                    Url += "?"+paramString;     
                }

                 HttpGet httpget = new HttpGet(fullUrl+Url);
                //HttpGet httpget = new HttpGet(Url);

                httprespo = HttpClient.execute(httpget);
            }
            httpentity = httprespo.getEntity();

            if(httpentity != null)
            {
                InputStream is = httpentity.getContent();
                BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);

                StringBuilder Sb = new StringBuilder();
                String Line = null;

                while((Line = buffer.readLine())!=null)
                {
                    Sb.append(Line+"\n");
                }
                is.close();
                jsonRes = Sb.toString();

            }

        }
         catch (UnsupportedEncodingException e) {
                e.toString();
        } catch (ClientProtocolException e) {
            e.toString();
        } catch (IOException e) {
                e.toString();
        }

        try
        {
            JObj = new JSONObject(jsonRes);
            Log.e("Data", jsonRes);
        }
        catch(JSONException e)
        {
            e.printStackTrace();
        }

        return JObj;
    }

}