-3

Please someone help me in this, I have a php script which returns Json response as "success" if condition is satisfied. I have put a log statement and I am getting response as "success" but when I put reesponse in if statement it does not recognize it. plus if I get the response "success" i want to change the button color from red to green in if statement which is giving me error and my application crashes. so my problem is:

  1. I get the response "success" but how to put it in if statement? because it directly execute else statement.
  2. The button change statement makes my application crash if i put the button change statement in else part for testing.

Here is my code

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

}

here is the error to button change statement

10-20 10:34:56.597 2433-2452/? D/IN ELSE:::﹕ "success"
10-20 10:34:56.787 2433-2452/? W/dalvikvm﹕ threadid=14: thread exiting with uncaught exception (group=0x400207d8)
10-20 10:34:56.797 2433-2452/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1 java.lang.RuntimeException: An error occured while executing doInBackground() at 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) at java.util.concurrent.FutureTask.run(FutureTask.java:137) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) at java.lang.Thread.run(Thread.java:1096) Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRoot.checkThread(ViewRoot.java:2812) at android.view.ViewRoot.invalidateChild(ViewRoot.java:607) at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633) at 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) at com.sne.movielist.MovieDetailActivity$1SendPostReqAsyncTaskk.doInBackground(MovieDetailActivity.java:145) at com.sne.movielist.MovieDetailActivity$1SendPostReqAsyncTaskk.doInBackground(MovieDetailActivity.java:114) at android.os.AsyncTask$2.call(AsyncTask.java:185) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)             at java.util.concurrent.FutureTask.run(FutureTask.java:137)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)             at java.lang.Thread.run(Thread.java:1096)
10-20 10:34:56.797 175-175/? W/ActivityManager﹕ Force finishing activity com.sne.movielist/.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﹕ Reporting idle of ActivityRecord{4a4c4b50 token=android.os.BinderProxy@4a4c4618 {com.sne.movielist/com.sne.movielist.MainActivity}} finished=false

Hasanaga
  • 1,099
  • 1
  • 9
  • 19
Shelby
  • 81
  • 1
  • 11

3 Answers3

2

As for the json issue, first of all never compare strings in java using ==, always use equals:

if (json.equals("success"))

Also, make sure you're comparing to the right response. It could be that instead of a simple "success" string, you're getting a "{success}" json object string (maybe in a key-value fashion). Print out the response to the log and see the exact format of the response.

As for the exception, it says it all:

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

You can only update UI components on the UI thread, since that's the thread that created it.

If you're running inside an Activity, you can use runOnUiThread, or to be on the safe side just use a Looper:

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

    @Override
    public void run() {
        //your code here
    }
});
Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
2

You should use equals() method to compare Strings,

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

And regarding the crash , you try to update UI from doInBackground() method so it is crashing, to update the UI you should do in onPostExecute() method as it is guaranteed to execute in UI thread.

In your case you can do something like below

In your doInBackground() method return the json and compare the result in 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 {

        } 

    }
}
Satyen Udeshi
  • 3,223
  • 1
  • 19
  • 26
0

As other suggested you should not use == operator for comparing two strings. You should use:

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

And for the crash you have to move the below code snippet to you onPostExecute() method like as below:

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

            }
   }
Pankaj
  • 7,908
  • 6
  • 42
  • 65