2016-07-06 73 views
-3

**編輯:解決**將代碼移動到AsyncTask

我正在測試AsyncTask功能上的示例代碼。但是dobackGround()方法沒有調用代碼。我注意到一些職位的幫助和重構我的代碼,但它仍然是不工作

這是主要佈局

<EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/editText1"> 
    </EditText> 

    <Button 
     android:text="Get Name" 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
    </Button> 

    <TextView 
     android:text="from Web service" 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
    </TextView> 

MainActivity.java

public class MainActivity extends Activity 
{ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

    } 
} 

WebServiceActivity.java

public class WebServiceActivity extends Activity implements View.OnClickListener { 

    Button btn; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     btn = (Button) findViewById(R.id.button1); 
     btn.setOnClickListener(this); 
    } 

    public void onClick(View view) { 

     switch (view.getId()) { 
      case R.id.button1: 
       new LongOperation().execute(""); 
       break; 
     } 
    } 

    private class LongOperation extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
      for (int i = 0; i < 5; i++) { 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        Thread.interrupted(); 
       } 
      } 
      return "Executed"; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      TextView txt = (TextView) findViewById(R.id.textView1); 
      txt.setText("Executed"); // txt.setText(result); 

     } 

     @Override 
     protected void onPreExecute() {} 

     @Override 
     protected void onProgressUpdate(Void... values) {} 
    } 
} 

WebServiceActivity containts嵌套類LongOperation延伸的AsyncTask。它是我的佈局沒有正確綁定?

需要一些建議

+0

下面的鏈接可以是有用的: http://stackoverflow.com/questions/9671546 /的AsyncTask-Android的示例 – Drv

回答

1

我是否需要移動整個視圖以異步任務?我不能 找到相關的文章

=>不,你不應該把整個東西移動到AsyncTask。首先了解AsyncTask的四種不同方法的目的並相應地移動你的東西。

  • onPreExecute() - 在開始執行之前需要準備的東西。例如,顯示進度條或對話框
  • doInBackground() - 寫下長時間運行的操作在此方法中喜歡做一個Web API調用
  • onProgressUpdate() - 你可以把部分更新此方法來UI。例如1/10那種在進度條輸出的
  • onPostExecute() - UI更新或要進行長時間運行的操作執行後的任何其他操作,即網絡API調用

其他一些要點:

  • 這些天AsyncTask沒有被使用那麼多,但一些其他的方法。

  • 有一些第三方和最佳庫中可用,這將有助於您實現長時間運行的任務。例如圖書館改造,OkHttp

  • 目前開發商已經採用被動方式啓動,所以在使用RxJava,RxAndroid庫。

0

你沒有必要把所有的代碼裏面的AsyncTask,你必須把的AsyncTask的內部doInBackground網絡操作碼()。

public class MainActivity extends Activity 
{ 
    /** 
    * Called when the activity is first created. 
    */ 
    private static final String SOAP_ACTION ="http://tempuri.org/HelloWorld"; 

    private static final String OPERATION_NAME = "findContact"; 

    private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/"; 

    private static final String SOAP_ADDRESS = "http://10.0.2.2:31736/WebSite3/Service.asmx"; 
    TextView tvData1; 
    EditText edata; 
    Button button; 
    String studentNo; 


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

     tvData1 = (TextView) findViewById(R.id.textView1); 
     button = (Button) findViewById(R.id.button1); 
     edata = (EditText) findViewById(R.id.editText1); 

     button.setOnClickListener(new OnClickListener() 
     { 

      public void onClick(View v) 
      { 
       studentNo = edata.getText().toString(); 

       new BackgroundTask().execute(); 
      } 
     }); 

    } 


    class BackgroundTask extends AsyncTask<String, Void, String> 
    { 

     @Override 
     protected String doInBackground(String... params) 
     { 
      SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME); 
      PropertyInfo propertyInfo = new PropertyInfo(); 
      propertyInfo.type = PropertyInfo.STRING_CLASS; 
      propertyInfo.name = "eid"; 

      request.addProperty(propertyInfo, studentNo); 

      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
      envelope.dotNet = true; 
      envelope.setOutputSoapObject(request); 

      HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS); 

      try 
      { 
       httpTransport.call(SOAP_ACTION, envelope); 
       Object response = envelope.getResponse(); 
       return response.toString(); 
      } catch (Exception exception) 
      { 
       return exception.toString() + " Or enter number is not Available!"; 
      } 
     } 

     @Override 
     protected void onPostExecute(String s) 
     { 
      tvData1.setText(s); 
     } 
    } 

} 
1

我想你需要一個AsyncTask的例子,所以在這裏。這是使用AsyncTask的loginTask的一個例子。希望它會幫助你...

import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.Intent; 
import android.content.res.Resources; 
import android.net.ConnectivityManager; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.Toast; 
import org.json.JSONException; 
import org.json.JSONObject; 

/** 
    * Created by jatin khattar on 01-10-2015. 
*/ 
public class LoginTask extends AsyncTask<String, Integer, String> { 


Context context; 
User user; 
private ConnectivityManager conMgr; 
private Resources r; 
private ProgressDialog dialog; 
private Session session; 


private final static String API_PARAM_TYPE="type"; 
private final static String API_PARAM_EMAIL="email"; 
private final static String API_PARAM_PASSWORD="password"; 



public LoginTask(Context context, User user, ConnectivityManager conMgr){ 
    this.context = context; 
    this.user = user; 
    this.conMgr = conMgr; 
    r=context.getResources(); 
    session=new Session(context); 
} 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    dialog=ProgressDialog.show(context, r.getString(R.string.progress_message), "Please Wait"); 
} 

@Override 
protected String doInBackground(String... params) { 
    API api=new API(this.context, conMgr); 
    api.setAPI("user"); 
    api.setAction("login"); 
    api.setParam(API_PARAM_TYPE, "general"); 
    api.setParam(API_PARAM_EMAIL, user.email); 
    api.setParam(API_PARAM_PASSWORD, user.pass); 
    String result=api.process(); 
    Log.d("API Response", result); 
    return result; 
} 

@Override 
protected void onPostExecute(String result) { 
    super.onPostExecute(result); 
    dialog.dismiss(); 
    try { 
     JSONObject res=new JSONObject(result); 
     if(res.getBoolean("success")){ 
      session.CreateSession(res.getInt("id"), res.getString("name"), res.getString("auth_key"), res.getString("email")); 
      Toast.makeText(this.context, "Logged in Successfully", Toast.LENGTH_LONG).show(); 
      Intent intnt = new Intent(context, MainActivity.class); 
      intnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
      context.startActivity(intnt); 
     }else{ 
      if(res.has("message")){ 
       Toast.makeText(this.context, res.getString("message"), Toast.LENGTH_SHORT).show(); 
      }else{ 
       Toast.makeText(this.context, r.getString(R.string.error_message_unknown), Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     Toast.makeText(this.context, r.getString(R.string.error_invalid_response_message), Toast.LENGTH_SHORT).show(); 
    } 

} 

} 
0

好的,我弄清了代碼..這是我工作的Asyntask代碼。只有一個主類和一個內部類需要

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/editText1"> 
    </EditText> 

    <Button 
     android:text="Get Name" 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
    </Button> 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
    </TextView> 

    </LinearLayout> 

MainActivity.java

public class MainActivity extends Activity 
{ 

TextView tvData1; 
EditText edata; 
Button button; 

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

    tvData1 = (TextView)findViewById(R.id.textView1); 


    button=(Button)findViewById(R.id.button1); 

    button.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      new LongOperation().execute(""); 

     } 
    }); 
} 


private class LongOperation extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     for (int i = 0; i < 5; i++) { 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       Thread.interrupted(); 
      } 
     } 
     return "executed"; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     tvData1.setText(result); 
    } 

    @Override 
    protected void onPreExecute() {} 

    @Override 
    protected void onProgressUpdate(Void... values) {} 
} 
}