iT邦幫忙

0

Volley使用StringRequest與JsonObjectRequest

想要用EditText以StringRequest POST到php做運算,之後再用JsonObjectRequest顯示在TextView
json 顯示資料可以
那可以在json上面再加上StringRequest嗎 還是可以直接寫在json做POST跟SHOW資料

public void onClick(View view) {
                final String fourg,innet,outnet,phonecall;
                fourg = Fourg.getText().toString();
                innet = Innet.getText().toString();
                outnet = Outnet.getText().toString();
                phonecall = Phonecall.getText().toString();
               StringRequest stringRequest = new StringRequest(Request.Method.POST, json_url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {

                            }
                        }
                        , new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("fourg",fourg);
                        params.put("innet",innet);
                        params.put("outnet",outnet);
                        params.put("phonecall",phonecall);
                        return params;
                    }
                };
                MySingleleton.getInstancr(MainActivity.this).addToRequestque(stringRequest);


                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, json_url,(String) null,
                        new Response.Listener<JSONObject>(){

                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                    fee.setText(response.getString("fee"));
                                    project.setText(response.getString("project"));
                                    url.setText(response.getString("allfee"));
                                }catch (JSONException e){
                                    e.printStackTrace();
                                }

                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_LONG).show();
                        error.printStackTrace();
                    }
                });

                MySingleleton.getInstancr(MainActivity.this).addToRequestque(jsonObjectRequest);
            }
        });

1 個回答

1
fysh711426
iT邦新手 3 級 ‧ 2017-11-18 12:48:14
最佳解答

需看您如何和 PHP 配合,
如果您的 PHP 設計成,運算完直接回傳,就可以用一個 Request 完成,
如果您的 PHP 運算完會寫入資料庫並且沒有回傳,而讀取資料是在另一支程式上,那麼就需要兩個 Request,
覺得寫在一起會比較好,可以少一次網路傳輸的開銷
/images/emoticon/emoticon37.gif

public void onClick(View view) {
    final String fourg,innet,outnet,phonecall;
    fourg = Fourg.getText().toString();
    innet = Innet.getText().toString();
    outnet = Outnet.getText().toString();
    phonecall = Phonecall.getText().toString();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, json_url, null,
    new Response.Listener<JSONObject>(){
        @Override
        public void onResponse(JSONObject response) {
            try {
                fee.setText(response.getString("fee"));
                project.setText(response.getString("project"));
                url.setText(response.getString("allfee"));
            }catch (JSONException e){
                e.printStackTrace();
            }

        }
    }, 
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_LONG).show();
            error.printStackTrace();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("fourg",fourg);
            params.put("innet",innet);
            params.put("outnet",outnet);
            params.put("phonecall",phonecall);
            return params;
        }
    };
    
     MySingleleton.getInstancr(MainActivity.this)
         .addToRequestque(jsonObjectRequest);
}
看更多先前的回應...收起先前的回應...
bennnn iT邦新手 5 級 ‧ 2017-11-18 13:12:09 檢舉

PHP確實設計運算完直接回傳
可是我剛剛試直接和在一起可是他會跑出Something went wrong
還是我的PHP有問題嗎?

<?php
$FourG =$_POST["fourg"];
$Innet = $_POST["innet"];
$Outnet = $_POST["outnet"];
$Phonecall = $_POST["phonecall"];
$user_name = 'root';
$password = '';
$host = 'localhost';
$db_name = 'emonoo';
$con = mysqli_connect($host,$user_name,$password,$db_name);
mysqli_set_charset($con,"utf8");
$sql = "SELECT * FROM 4gtest ORDER BY fee ASC";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result))
{
	$intuse = $row['4g'];
	$in = $row['innet'];
	$out = $row['outnet'];
	$call = $row['phonecall'];

	if($intuse>=$FourG && $in>=$Innet && $out>=$Outnet && $call>=$Phonecall)
	{

 		 $fee = $row['fee'];
 		 $u = $row['project'];
 		 echo json_encode(array("fee"=> $row['fee'],"project"=> $row['project'],"allfee"=> $row['url']));
 		 exit();
	}


}
?>

https://stackoverflow.com/questions/24376134/android-volley-request-parameters-not-included-in-request
https://stackoverflow.com/questions/24285544/android-volley-http-request-custom-header/24402403#24402403
發現 JsonObjectRequest 並不會呼叫 getParams(),
這裡提供兩個解法,第一個採用第一篇的做法使用 JSONObject。

JSONObject params = new JSONObject();
params.put("fourg",fourg);
params.put("innet",innet);
params.put("outnet",outnet);
params.put("phonecall",phonecall);

new JsonObjectRequest(Request.Method.POST, json_url, params, ...

第二個換成使用 StringRequest,然後自己解析 JSON XD。

bennnn iT邦新手 5 級 ‧ 2017-11-18 14:50:26 檢舉

我按照您給的寫法 但會變成一整段JsonObjectRequest都是錯誤

JSONObject params = new JSONObject();
                params.put("fourg",fourg);
                params.put("innet",innet);
                params.put("outnet",outnet);
                params.put("phonecall",phonecall);



                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,params,json_url, (String) null,
                        new Response.Listener<JSONObject>()


然後改String 則是顯示Something went wrong

 StringRequest stringRequest =new StringRequest(Request.Method.POST, json_url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            fee.setText(json.getString("資費"));
                            project.setText(json.getString("方案"));
                            url.setText(json.getString("完整資費內容"));
                        }catch (JSONException e){
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_LONG).show();
                        error.printStackTrace();

                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("fourg",fourg);
                        params.put("innet",innet);
                        params.put("outnet",outnet);
                        params.put("phonecall",phonecall);
                        return  params;
                    }
                };
                MySingleleton.getInstancr(MainActivity.this).addToRequestque(stringRequest);

您參數的位置放錯了,不過剛剛 Google 了一下這種寫法還是有問題,這種寫法 Post 出去的會是 Json 格式,而不是我們常用的 key=value 格式,所以還是用 StringRequest 就好。
http://www.jianshu.com/p/bba47f2df849

然後您可以看看,這段程式碼的 response 回來的結果是什麼?

public void onResponse(String response) {

如果這裡沒回來就出錯,那要去 PHP 那裡,看看 PHP 有沒有正常執行,echo 回來的內容是什麼。

bennnn iT邦新手 5 級 ‧ 2017-11-18 17:18:51 檢舉

我用數字換掉php的變數但顯示app上顯示不出來
可是之前jsonRequest能夠顯示
是我這段有寫錯嗎?

public void onResponse(String response) {
    try {
         JSONObject json = new JSONObject(response);
         fee.setText(json.getString("資費"));                      project.setText(json.getString("方案"));
         url.setText(json.getString("完整資費內容"));
        }catch (JSONException e){
            e.printStackTrace();
        }
  }
}

對阿您原來是英文怎麼變成中文了 XD

fee.setText(response.getString("fee"));
project.setText(response.getString("project"));
url.setText(response.getString("allfee"));
fee.setText(json.getString("資費"));
project.setText(json.getString("方案"));
url.setText(json.getString("完整資費內容"));

建議您將 response 印出來看看,不然好難猜 XD

bennnn iT邦新手 5 級 ‧ 2017-11-18 19:25:38 檢舉

我一開始寫json用英文
下午寫String就改中文了PHP也有改 忘了說不好意思
然後可以請問要怎麼印出response嗎
有錯誤就會顯示TOAST的指令
所以是要更改這段嗎?

  public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this,"SOMEthing is wrong",Toast.LENGTH_LONG).show();
                        error.printStackTrace();

想看看 PHP 回來的是什麼

public void onResponse(String response) {
    try {
         Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
        }catch (JSONException e){
            e.printStackTrace();
        }
  }
}

然後 onErrorResponse 可以改成

public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.getMessage(),Toast.LENGTH_LONG).show();
                        error.printStackTrace();

這樣試試看吧 XD

bennnn iT邦新手 5 級 ‧ 2017-11-18 19:47:33 檢舉

我照這樣打後就都跑得出來了 真的很謝謝你

/images/emoticon/emoticon42.gif

我要發表回答

立即登入回答