从服务器

时间:2015-10-20 05:21:32

标签: java android json android-asynctask

请有人帮助我, 我有一个php脚本,如果条件满足,则会将Json响应返回为“成功”。 我已经发布了一个日志声明,我得到的响应是“成功”,但是当我在 if语句中添加响应时,它无法识别它。 加上如果我得到响应“成功”我想在 if语句中将按钮颜色从红色更改为绿色,这会给我错误并且我的应用程序崩溃。 所以我的问题是:

  1. 我得到的答案是“成功”,但如何将其置于if语句中?因为它直接执行else语句。
  2. 如果我将按钮更改语句放在else部分进行测试,则按钮更改语句会使我的应用程序崩溃。
  3. 这是我的代码

     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:线程退出,未捕获异常(组= 0x400207d8)
      10-20 10:34:56.797 2433-2452 /? E / AndroidRuntime:FATAL EXCEPTION:AsyncTask#1       java.lang.RuntimeException:执行doInBackground()时发生错误               在android.os.AsyncTask $ 3.done(AsyncTask.java:200)               at java.util.concurrent.FutureTask $ Sync.innerSetException(FutureTask.java:273)               at java.util.concurrent.FutureTask.setException(FutureTask.java:124)               at 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)               at 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)               在android.view.View.invalidate(View.java:5139)               在android.view.View.setBackgroundDrawable(View.java:7486)               在android.view.View.setBackgroundResource(View.java:7395)               at com.sne.movi​​elist.MovieDetailActivity $ 1SendPostReqAsyncTaskk.doInBackground(MovieDetailActivity.java:145)               at com.sne.movi​​elist.MovieDetailActivity $ 1SendPostReqAsyncTaskk.doInBackground(MovieDetailActivity.java:114)               在android.os.AsyncTask $ 2.call(AsyncTask.java:185)               at 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)   at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.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}} finished = false

3 个答案:

答案 0 :(得分:2)

至于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
    }
});

答案 1 :(得分:2)

您应该使用equals()方法来比较Strings

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

关于崩溃,您尝试从UI方法更新doInBackground()以使其崩溃,以更新您应该在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 {

        } 

    }
}

答案 2 :(得分:0)

正如其他建议你不应该使用 == 运算符来比较两个字符串。你应该使用:

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);

            }
   }