【问题标题】:How to return data from php to eclipse?如何将数据从php返回到eclipse?
【发布时间】:2013-01-09 02:03:17
【问题描述】:

您好,我正在使用 php 从 mysql 数据库中获取数据,并在成功接收数据后调用一个新的活动,我需要在其中打印数据。

这是我的代码:

public class RecoProd extends Activity {
    EditText pd;
    TextView error;

    ArrayList<NameValuePair> postParameters;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recomain);
        pd = (EditText) findViewById(R.id.name);

        error = (TextView) findViewById(R.id.myTableLayout);

        pd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("product", pd
                        .getText().toString()));


                // String valid = "1";

                DownloadWebPageTask dw = new DownloadWebPageTask();
                dw.execute("");

            }
        });
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = null;
            for (String url : urls) {
                try {
                    response = CustomHttpClient.executeHttpPost("http://10.0.2.2/abc/check2.php", postParameters);  
                    String res = response.toString();
                    // res = res.trim();
                    res = res.replaceAll("\\s+", "");
                    // error.setText(res);
                    if(res.equals("1")){     ***<<--------------I think the error is here***
                        Intent loginintent = new Intent(RecoProd.this, RecoProd1.class);
                        startActivity(loginintent);
                    }
                    else
                        error.setText("Sorry!! ");





                } catch (Exception e) {


                }
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
        }
    }
}

这是我的 php 代码:

<?php
$pd=$_POST['name'];

//connect to the db
$user = "root";
$pswd = "";
$db = "mylogin";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);

$query = "SELECT * FROM recoprod  ";
$result = mysql_query("SELECT * FROM recoprod");
while($row = mysql_fetch_array($result))
  {
  $output[]=$row;
  }
/*
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens  
if(mysql_num_rows($result) > 0)  
echo 1;  // for correct login response  
else  
echo 0; // for incorrect login response */
?>

当我执行它时,我得到了一个力关闭。

EDITED CODE





package com.androidhive.googleplacesandmaps;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class RecoProd extends Activity {
    EditText pd;
    TextView error;

    ArrayList<NameValuePair> postParameters;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        try {
            Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
                    .getContextClassLoader());

            Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread
                    .currentThread().getContextClassLoader());

            Class<?> threadPolicyBuilderClass = Class.forName("android.os.StrictMode$ThreadPolicy$Builder", true,
                    Thread.currentThread().getContextClassLoader());

            Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);

            Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
            Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
            Method buildMethod = threadPolicyBuilderClass.getMethod("build");

            Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
            Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();

            Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);

            obj = penaltyMethod.invoke(obj);
            Object threadPolicyObject = buildMethod.invoke(obj);
            setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);

        } catch (Exception ex) {
            String TAG = null;
            Log.w(TAG, ex);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recomain);
        pd = (EditText) findViewById(R.id.name);

        error = (TextView) findViewById(R.id.showresult);

        pd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("product", pd
                        .getText().toString()));


                // String valid = "1";

                DownloadWebPageTask dw = new DownloadWebPageTask();
                dw.execute("");

            }
        });
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = null;
            for (String url : urls) {
                try {
                    response = CustomHttpClient.executeHttpPost("http://10.0.2.2/abc/check2.php", postParameters);  
                    String res = response.toString();
                    // res = res.trim();
                    res = res.replaceAll("\\s+", "");
                    // error.setText(res);
                    try{
                        res = "";
                  JSONArray jArray = new JSONArray(res);
                        for(int i=0;i<jArray.length();i++){
                                JSONObject json_data = jArray.getJSONObject(i);
                                Log.i("prod_id","id: "+json_data.getInt("prod_id")+
                                        ", prod_name: "+json_data.getString("prod_name")+
                                        ", prod_category: "+json_data.getInt("prod_category")+
                                        ", prod_cost: "+json_data.getInt("prod_cost")
                                );
                                //Get an output to the screen
                                res += "\n" + json_data.getString("prod_id") + " -> "+ json_data.getInt("prod_name");
                        }
                }
                catch(JSONException e){
                        Log.e("log_tag", "Error parsing data "+e.toString());
                }

                try{
                 error.setText(res);
                }
                catch(Exception e){
                 Log.e("log_tag","Error in Display!" + e.toString());;          
                }   
           }
                 catch (Exception e) {
            Log.e("log_tag","Error in http connection!!" + e.toString());     
           }
            }
            return response;

               }
        @Override
        protected void onPostExecute(String result) {
        }
    }
}

这是我的 php 代码:

<?php
$pd = $_POST['name'];

//connect to the db
$user = "root";
$pswd = "";
$db = "mylogin";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);

$query = "SELECT * FROM recoprod  ";
$result = mysql_query("SELECT * FROM recoprod");
while($row = mysql_fetch_array($result)) {
    $output[] = $row;
}
print(json_encode($output));
mysql_close();
/*
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens  
if(mysql_num_rows($result) > 0)  
echo 1;  // for correct login response  
else  
echo 0; // for incorrect login response */
?>

您好,我对上面编辑的代码进行了一些更改。

我只有 2 行,每行包含 4 个数据。

【问题讨论】:

  • 我没有任何 logcat 错误我认为错误出现在我认为我没有正确执行的数据的 php 文件中。
  • 尝试在服务器控制台或本地主机中回显您的结果。并在您的代码周围加上 try catch 以在执行 Asyntask 时获取异常
  • 您正在尝试获取 recoprod 表中的所有行并循环它们。如果您的表有更多的记录,那么“while”循环将需要更多时间来完成执行。因此,您必须通过更改 php.ini 文件中的“最大执行时间”来等待循环完成。
  • 怎么做可以编辑上面的代码并显示?? @hilarudeens
  • @JayantShinde:你在这条线上得到了什么String res = response.toString();?并添加CustomHttpClient类代码

标签: php android mysql


【解决方案1】:

您的问题出在 AsyncTask 部分

当您使用 AsyncTask 时,您可以在 doInBackground 函数上处理数据,但在 onPostExecute 上更新 UI。 将处理后的值返回给 onPostExecute,因为在 android 上使用 AsyncTask 允许您在加载完成后更改布局上的内容。但仅在 onPostExecute 状态下,因此在 doInBackground 上处理您的 json,然后将其反映到 onPostExecute 上的布局

public class RecoProd extends Activity {
EditText pd;
TextView error;

ArrayList<NameValuePair> postParameters;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recomain);
    pd = (EditText) findViewById(R.id.name);

    error = (TextView) findViewById(R.id.myTableLayout);

    pd.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("product", pd
                    .getText().toString()));


            // String valid = "1";

            DownloadWebPageTask dw = new DownloadWebPageTask();
            dw.execute("");

        }
    });
}

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response = null;
        for (String url : urls) {
            try {
                response = CustomHttpClient.executeHttpPost("http://10.0.2.2/abc/check2.php", postParameters);  
                String res = response.toString();
                // res = res.trim();
                res = res.replaceAll("\\s+", "");
                // error.setText(res);






            } catch (Exception e) {


            }
        }
        return res;
    }

    @Override
    protected void onPostExecute(String result) {

         if(result.equals("1")){    
             Intent loginintent = new Intent(RecoProd.this, RecoProd1.class);
             startActivity(loginintent);
         }
         else
             error.setText("Sorry!! ");
    }
}

}

【讨论】:

  • 如果您遇到错误,请将您的“String res”定义置于 try 案例之上
  • 另外,如果您想修复您的第二个修改代码,您的问题是您在此行更新 ui error.setText(res);在 doInBackground - 将其移动到 onPostExecute 并在您的 doInBackground 上返回 res 作为结果
【解决方案2】:

你可以这样做:

public class RecoProd extends Activity {
EditText pd;
TextView error;

ArrayList<NameValuePair> postParameters;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recomain);
    pd = (EditText) findViewById(R.id.name);

    error = (TextView) findViewById(R.id.myTableLayout);

    pd.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("product", pd
                    .getText().toString()));


            // String valid = "1";

            downloadWebPageTask();

        }
    });
}

private void downloadWebPageTask extends AsyncTask<String, Void, String> {
    String url = "http://10.0.2.2/abc/check2.php?postParameters=paramValue";
    grabURL(url);
}


public void grabURL(String url){
    try {
        new GrabURL().execute(new URL(url));
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

private class GrabURL extends AsyncTask<URL, Integer, JSONObject> {

    @Override
    protected JSONObject doInBackground(URL... urls) {
        // This method will send the http request
        JSONObject jsonResponse=null;
        try 
        {
            URL link = urls[0];
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(link.toString());
            ResponseHandler<String> responseHandler=new BasicResponseHandler();
            String responseBody = httpClient.execute(request, responseHandler);
            jsonResponse = new JSONObject(responseBody);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return jsonResponse;
    }

    @Override
    protected void onPreExecute() {
        // This method will be executed before the http request
        // In this method you can do things like showing the loading sign
    }

    @Override
    protected void onPostExecute(JSONObject jsonObj) {
        // This method will run after the http request and contains the results
        // This method expectes you return a valid jSon from the server
        try {
            if(! jsonObj.getString("code").equalsIgnoreCase("200") ){
                // Bad response from server
            }
            else if( jsonObj.has("data") ){
                JSONArray dataArray = jsonObj.getJSONArray("data");

                String tmpUserLoc = (String) jsonObj.getJSONObject("data").get("userLocation");
                String tempUserNIC = (String) jsonObj.getJSONObject("data").get("userNIC");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        // You can stop the loading sign here if you showed it in OnPreExecute
    }

}

}

我没有测试过这段代码,但它应该可以工作。如果您要从服务器返回 json 数组,您可能需要查看 jSonArray doc 或 this link 也可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-01-25
    • 2015-11-01
    • 2017-04-20
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多