2012-10-30 56 views
1

問題已解決,謝謝您的幫助。基本上,我有我的onCreate()類設置一個按鈕上的OnClick偵聽器。一旦我點擊它,就會創建並執行一個異步任務。如何在異步任務完成後更改活動?

這個異步任務從服務器獲取響應,然後將信息發送到onPostExecute()。

從這裏,如果信息有效或無效,我想對結果進行敬酒並相應地切換活動。

截至目前,我試圖從onPostExecute()做到這一點,它不工作。不知何故,我必須回到我的主線,並在那裏做。我該怎麼做呢? 下面是代碼:

public class Class1 extends Activity { 

JSONObject jObj = null; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.myLayout); 

    Button submit = (Button) findViewById(R.id.submitButton); 
    submit.setOnClickListener(new View.OnClickListener(){ 

     public void onClick(View arg0){ 

      (new CallAPI(restfulCall)).execute(); 
     } 
    });   
} 

public class CallAPI extends AsyncTask<Void,Void,String> 
{ 
    private String restfulCall = ""; 

    public CallAPI(String command) 
    { 
     restfulCall = command; 
    } 

    protected String doInBackground(Void... urls) 
    { 
     return API.getData(restfulCall); 
    } 

    protected void onPostExecute(String result) { 
     try { 
      jObj = new JSONObject(result); 
     } catch (JSONException e1) { 
      e1.printStackTrace(); 
     } 

      try { 
       if(jObj.get("status").toString().equals("success")) 
       { 
        Toast.makeText(getBaseContext(),"Registration Succesful",Toast.LENGTH_LONG).show(); 
        Intent intent = new Intent(Class1.this,Success.class); 
        Class1.this.startActivity(intent); 

       } 
       else 
       { 
        Toast.makeText(getBaseContext(),jObj.get("error").toString(),Toast.LENGTH_LONG).show(); 
        Intent intent = new Intent(Class1.this,Error.class); 
        Class1.this.startActivity(intent);   
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

    } 
} 

}

+2

爲什麼它不工作?它給出了任何錯誤?如果是的話,你可以共享logcat ... – yahya

+2

'onPostExecute'已經在主線程上運行,所以這可能不是問題。另外,你不能用=='jObj.get(「status」)。toString()==「success」'在java中比較字符串。嘗試使用'jObj.get(「status」)。toString()。equals(「success」)''。正如yahya所說,提供更多關於爲什麼它不起作用的信息。 – Marcelo

+0

我應該看看我的logcat更多...它不會進入如果其他...讓我解決這個問題。 –

回答

1

使用equals比較這一翻譯的==爲字符串:的

if(jObj.get("status").toString().equals("success") 

代替

if(jObj.get("status").toString() == "success")