簡體   English   中英

從服務器獲取 json 響應

[英]Getting json response from server

請有人幫助我,我有一個php腳本,如果條件滿足,它會返回Json響應為“成功” 我已經放置了一個日志語句,我得到的響應是“成功”,但是當我在if 語句中放置響應時,它無法識別它。 另外,如果我得到響應“成功”,我想在if 語句中將按鈕顏色從紅色更改為綠色,這給我帶來錯誤並且我的應用程序崩潰。 所以我的問題是:

  1. 我得到了“成功”的響應,但如何將其放入 if 語句中? 因為它直接執行else語句。
  2. 如果我將按鈕更改語句放在 else 部分進行測試,則按鈕更改語句會使我的應用程序崩潰。

這是我的代碼

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    // Session class instance
    session = new SessionManager(getApplicationContext());
    Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
    /**
     * Call this function whenever you want to check user login
     * This will redirect user to LoginActivity is he is not
     * logged in
     * */
    session.checkLogin();

    setContentView(R.layout.movie_detail);
    bt=(Button)findViewById(R.id.buttonchange);
    titlee=(TextView)findViewById(R.id.mtitle);
    date=(TextView)findViewById(R.id.mdate);
like=(TextView)findViewById(R.id.mlikes);
    video=(TextView)findViewById(R.id.mvideo);
    idd=(TextView)findViewById(R.id.mid);
    image=(ImageView)findViewById(R.id.imageView);
    UniqueId=(TextView)findViewById(R.id.unique_id);
    ts=(TextSwitcher)findViewById(R.id.tsLikesCounter);



    Intent i=getIntent();
    //image.setImageResource(i.getStringExtra("THUMB"));
    titlee.setText(i.getStringExtra("TITLE"));
   like.setText("Likes = "+i.getStringExtra("LIKES"));
    date.setText("Date = " + i.getStringExtra("DATE"));
    video.setText("Video = " + i.getStringExtra("VIDEO"));
    idd.setText(i.getStringExtra("IDD"));
    UniqueId.setText(i.getStringExtra("UNIQUEID"));



   String id = idd.getText().toString();

   String unique = UniqueId.getText().toString();

    // private void insertToDatabase(String id,String unique){
    class SendPostReqAsyncTaskk extends AsyncTask<String, String, String>  {
        @Override
        protected String doInBackground(String... params) {
            String paramUsername = params[0];
           String paramAddress = params[1];

            String id = idd.getText().toString();
            String unique = UniqueId.getText().toString();


            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id", id));
            nameValuePairs.add(new BasicNameValuePair("unique", unique));

            // getting JSON Object
            // Note that create product url accepts POST method

           try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("MY_URL");
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpClient.execute(httpPost);
               String json = EntityUtils.toString(response.getEntity());

               if(json=="success"){
                   Log.d("IN IF::", json);
                   bt.setBackgroundResource(R.drawable.green1);
               }
               else {
                   Log.d("IN ELSE:::", json);

               }
               // writing response to log
               Log.d("Http Response:::", json);
              // Toast.makeText(getBaseContext(), response.toString(), Toast.LENGTH_SHORT).show();
            HttpEntity  entity = response.getEntity();

               //JSONObject myObject = new JSONObject(TAG_SUCCESS);

              //  int success =response.getInt(TAG_SUCCESS);


            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }
            return "success";


        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);


        }
    }

  SendPostReqAsyncTaskk check = new SendPostReqAsyncTaskk();
   check.execute(id, unique);

}

這是按鈕更改語句的錯誤

10-20 10:34:56.597 2433-2452/? D/IN ELSE:::::“成功”
10-20 10:34:56.787 2433-2452/? W/dalvikvm: threadid=14: 線程退出並出現未捕獲的異常 (group=0x400207d8)
10-20 10:34:56.797 2433-2452/? E/AndroidRuntime:致命異常:AsyncTask #1 java.lang.RuntimeException:在 java.util.concurrent.FutureTask$Sync 在 android.os.AsyncTask$3.done(AsyncTask.java:200) 上執行 doInBackground() 時發生錯誤.innerSetException(FutureTask.java:273) 在 java.util.concurrent.FutureTask.setException(FutureTask.java:124) 在 java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 在 java.util。 concurrent.FutureTask.run(FutureTask.java:137) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 在 java .lang.Thread.run(Thread.java:1096) 引起:android.view.ViewRoot$CalledFromWrongThreadException:只有創建視圖層次結構的原始線程才能觸及其視圖。 在 android.view.ViewRoot.checkThread(ViewRoot.java:2812) 在 android.view.ViewRoot.invalidateChild(ViewRoot.java:607) 在 android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633) 在 android.view。 ViewGroup.invalidateChild(ViewGroup.java:2505) at android.view.View.invalidate(View.java:5139) at android.view.View.setBackgroundDrawable(View.java:7486) at android.view.View.setBackgroundResource(View) .java:7395) 在 com.sne.movi​​elist.MovieDetailActivity$1SendPostReqAsyncTaskk.doInBackground(MovieDetailActivity.java:145) 在 com.sne.movi​​elist.MovieDetailActivity$1SendPostReqAsyncTaskk.doInBackground(MovieDetailActivity.java:112.osAsyncTask) .call(AsyncTask.java:185) 在 java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 在 java.util.concurrent.FutureTask.run(FutureTask.java:137) 在 java.util。 concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExec utor.java:561) 在 java.lang.Thread.run(Thread.java:1096)
10-20 10:34:56.797 175-175/? W/ActivityManager﹕強制完成活動 com.sne.movi​​elist/.MovieDetailActivity
10-20 10:34:56.887 175-192/? I/ActivityManager: ensureBootCompleted():enableScreenfalse
10-20 10:34:56.897 2433-2433/? I/ActivityThread: queueIdle
10-20 10:34:56.897 2433-2433/? V/ActivityThread:報告ActivityRecord的空閑{4a4c4b50 token=android.os.BinderProxy@4a4c4618 {com.sne.movi​​elist/com.sne.movi​​elist.MainActivity}}完成=false

至於 json 問題,首先永遠不要使用==比較 java 中的字符串,始終使用equals

if (json.equals("success"))

另外,請確保您正在與正確的響應進行比較。 可能不是簡單的"success"字符串,而是"{success}" json 對象字符串(可能是鍵值方式)。 將響應打印到日志並查看響應的確切格式。

至於例外,它說明了一切:

Caused by: android.view.ViewRoot$CalledFromWrongThreadException:
     Only the original thread that created a view hierarchy can touch its views.

您只能在 UI 線程上更新 UI 組件,因為這是創建它的線程。

如果您在Activity內運行,則可以使用runOnUiThread ,或者為了安全起見,只需使用Looper

new Handler(Looper.getMainLooper()).post(new Runnable() {

    @Override
    public void run() {
        //your code here
    }
});

您應該使用equals()方法來比較Strings

json.equals("\\"success\\"")

關於崩潰,您嘗試從doInBackground()方法更新UI ,因此它崩潰,更新您應該在onPostExecute()方法中執行的UI因為它保證在UI線程中執行。

在您的情況下,您可以執行以下操作

doInBackground()方法中返回json並比較onPostExecute()的結果,

// private void insertToDatabase(String id,String unique){
class SendPostReqAsyncTaskk extends AsyncTask<String, String, String>  {
    @Override
    protected String doInBackground(String... params) {
        String paramUsername = params[0];
       String paramAddress = params[1];

        String id = idd.getText().toString();
        String unique = UniqueId.getText().toString();

        String json = "";
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("id", id));
        nameValuePairs.add(new BasicNameValuePair("unique", unique));

        // getting JSON Object
        // Note that create product url accepts POST method

       try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("MY_URL");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);
            json = EntityUtils.toString(response.getEntity());


        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }
        return json;


    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(result.equals("\"success\"")){
         // Update your Button here
        } else {

        } 

    }
}

正如其他人所建議的,您不應該使用==運算符來比較兩個字符串。 你應該使用:

if (json.equals("success"))
Or
if (json.equalsIgnoreCase("success"))

對於崩潰,您必須將以下代碼片段移動到您的onPostExecute()方法中,如下所示:

   @Override
   protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(json=="success"){
                   Log.d("IN IF::", json);
                   bt.setBackgroundResource(R.drawable.green1);
            } else {
                   Log.d("IN ELSE:::", json);

            }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM