2013-04-16 41 views
1

我試圖做一個「載入中...」的消息出現,而用戶反應如何顯示「加載...」消息正在等待效應初探從Web服務出現。在等待來自Web服務

我看了一下其他各種類似的問題/答案和教程我在網上找到,但不能完全得到它正常工作。

任何幫助將非常感激!

代碼是在這裏:

public class SunriseSunset extends Activity implements OnClickListener { 

    public Button getLocation; 
    public Button setLocationJapan; 
    public TextView LongCoord; 
    public TextView LatCoord; 
    public double longitude; 
    public double latitude; 
    public LocationManager lm; 
    public Spinner Locationspinner; 
    public DateDialogFragment frag; 
    public Button date; 
    public Calendar now; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.sunrisesunset); 
     // Show the Up button in the action bar. 
       setupActionBar(); 

     //Setting onClickListener for Calculate Sunrise/Sunset Button 
     findViewById(R.id.CalculateSunriseSunset).setOnClickListener(this); 

     //Sets up LocationManager to enable GPS data to be accessed. 
     lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, 
       new MyLocationListener()); 

     //Declares Latitude and Longitude TextViews 
     LatCoord = (TextView) findViewById(R.id.LatCoord); 
     LongCoord = (TextView) findViewById(R.id.LongCoord); 

     //Declares for Location Spinner/Dropdown 
     addListenerOnSpinnerItemSelection(); 

     //Date shit 
     now = Calendar.getInstance(); 
     date = (Button)findViewById(R.id.date_button); 
     date.setText(DateFormat.format("dd MMMM yyyy", Calendar.getInstance())); 
     date.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       showDialog(); 
      } 
     }); 

    } 
    /** 
    * Set up the {@link android.app.ActionBar}. 
    */ 
    private void setupActionBar() { 

     getActionBar().setDisplayHomeAsUpEnabled(true); 

    } 

    // More date shit 
    @SuppressLint("CommitTransaction") 
    public void showDialog() { 
     FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment 
     frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){  

     public void updateChangedDate(int year, int month, int day){      
     now.set(year, month, day); 
     date.setText(DateFormat.format("dd MMMM yyyy", now));    
     } 
      }, now); 
     frag.show(ft, "DateDialogFragment");  } 



    public interface DateDialogFragmentListener{ 
     //this interface is a listener between the Date Dialog fragment and the activity to update the buttons date 
     public void updateChangedDate(int year, int month, int day); 
    } 

    public void addListenerOnSpinnerItemSelection() { 
     Locationspinner = (Spinner) findViewById(R.id.Locationspinner); 
     Locationspinner 
       .setOnItemSelectedListener(new CustomOnItemSelectedListener(
         this)); 
    } 


    protected void showCurrentLocation() { 
     // TODO Auto-generated method stub 
     // This is called to find current location based on GPS data and sends 
     // these values to the LongCoord and LatCoord TextViews 
     Location location = lm 
       .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 

     LongCoord.setText(Double.toString(longitude)); 
     LatCoord.setText(Double.toString(latitude)); 
    } 

    @Override 
    public void onClick(View arg0) { 
     Button b = (Button) findViewById(R.id.CalculateSunriseSunset); 
     b.setClickable(false); 
     new LongRunningGetIO().execute(); 
    } 

    public class LongRunningGetIO extends AsyncTask<Void, Void, String> { 
     //Reads in the web service 
     protected String getASCIIContentFromEntity(HttpEntity entity) 
       throws IllegalStateException, IOException { 
      InputStream in = entity.getContent(); 
      StringBuffer out = new StringBuffer(); 
      int n = 1; 
      while (n > 0) { 
       byte[] b = new byte[4096]; 
       n = in.read(b); 
       if (n > 0) 
        out.append(new String(b, 0, n)); 
      } 
      return out.toString(); 
     } 

     @SuppressLint("SimpleDateFormat") 
     @Override 
     protected String doInBackground(Void... params) { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpContext localContext = new BasicHttpContext(); 

      // Finds todays date and adds that into the URL in simple date format DD/MM 
      SimpleDateFormat df = new SimpleDateFormat("dd/MM"); 
      String formattedDate = df.format(now.getTime()); 

      String finalURL = "http://www.earthtools.org/sun/" 
        + LatCoord.getText().toString().trim() + "/" 
        + LongCoord.getText().toString().trim() + "/" 
        + formattedDate + "/99/0"; 
      HttpGet httpGet = new HttpGet(finalURL); 
      String text = null; 

      try { 
       HttpResponse response = httpClient.execute(httpGet, 
         localContext); 
       HttpEntity entity = response.getEntity(); 
       text = getASCIIContentFromEntity(entity); 
      } catch (Exception e) { 
       return e.getLocalizedMessage(); 
      } 
      return text; 
     } 

     protected void onPostExecute(String results) { 
      if (results != null) { 
       try { 

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory 
          .newInstance(); 
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
        InputSource s = new InputSource(new StringReader(results)); 
        Document doc = dBuilder.parse(s); 
        doc.getDocumentElement().normalize(); 
        TextView tvSunrise = (TextView) findViewById(R.id.Sunrise); 
        TextView tvSunset = (TextView) findViewById(R.id.Sunset); 
        tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent()); 
        tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent()); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
      Button b = (Button) findViewById(R.id.CalculateSunriseSunset); 
      b.setClickable(true); 
     } 
    } 



    class MyLocationListener implements LocationListener { 
     @Override 
     public void onLocationChanged(Location location) { 
      // TODO Auto-generated method stub 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
      // TODO Auto-generated method stub 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      // TODO Auto-generated method stub 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      // TODO Auto-generated method stub 
     } 
    } 
} 

任何幫助將非常感激:) X

回答

3

閱讀AsyncTask,如果您尚未閱讀。

該類允許執行後臺操作並在UI線程上發佈結果 而無需操作線程和/或處理程序。

有,你可以在它裏面很少使用的功能。例如: onPreExecute,doInBackground,onProgressUpdate和onPostExecute。

在onPreExecute(),申報一個對話框,顯示加載...使用此框:

private final ProgressDialog dialog = new ProgressDialog(YourClass.this); 

protected void onPreExecute() { 
    this.dialog.setMessage("loading..."); 
    this.dialog.show(); 
} 

然後在doInBackground,你可以做你的任務。即調用web服務並等待響應(這樣您將在後臺線程中等待而不鎖定UI)。

protected Boolean doInBackground(final Void unused) { 
    // call your web service here and do other stuff(wait). 
    // return true when success else false 
} 

上述函數會返回一個被接受爲onPostExecute OnpostExecute(參數)布爾值,停止該對話框並顯示其他像成功等喜歡的東西:

protected void onPostExecute(final Boolean result) { 
    if (this.dialog.isShowing()) { // if dialog box showing = true 
     this.dialog.dismiss(); // dismiss it 
    } 
    if (result.booleanValue()) { 
     //also show register success dialog 
    } 
} 

還要檢查this線程。希望這可以幫助。

+2

加[onProgressUpdate(http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate%28Progress...%29)如果你想有一個進度條,而不僅僅是一個靜態的文本。 – Gustek

0

嘗試顯示進度對話框,而你執行你的AsyncTask和解僱後的對話框執行你的AsyncTask的。此外:

private ProgressDialog progressDialog; 

@Override 
    public void onClick(View arg0) { 
     Button b = (Button) findViewById(R.id.CalculateSunriseSunset); 
     b.setClickable(false); 
     progressDialog = ProgressDialog.show(SunriseSunset.this, "Loading", 
       "Please wait while fetching data"); 
     new LongRunningGetIO().execute(); 
    } 

...

protected void onPostExecute(String results) { 
progressDialog.dismiss(); 
       if (results != null) { 
        try {