2013-08-22 201 views
1

這是每個我接觸到的ImageView我的應用程序等待大約5秒的時間我的代碼 然後chrashes應用程序崩潰每次我做一個HTTP請求時

我有INTERNET權限

在服務器端我有一個PHP頁面讀取GET和數據庫中的

public class Home extends Activity { 
ImageView lightbut; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_home); 
    ImageView lightbut = (ImageView) findViewById(R.id.light); 
    lightbut.setClickable(true); 
    lightbut.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Log.d("== My activity ===","OnClick is called"); 
     // Creating HTTP client 
      HttpClient httpClient = new DefaultHttpClient(); 

      // Creating HTTP Post 
      HttpGet httpPost = new HttpGet("http://192.168.0.102/HR/index.php?command=ligthsoff"); 
      try { 
       HttpResponse response = httpClient.execute(httpPost); 


      } catch (ClientProtocolException e) { 
       // writing exception to log 
       e.printStackTrace(); 

      } catch (IOException e) { 
       // writing exception to log 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 
+0

爲了便於使用,請查看[droidQuery](http://bit.ly/droidquery)。獲取'XML'或'JSON'就像'$ .getJSON(url)'或'$ .getXML(url)'一樣簡單。 – Phil

+0

這些天你應該使用Android的排球庫https://developer.android.com/training/volley/index.html – Benitok

回答

3

插入一個logcat的將是非常有益的,但它可能是從上UI做網絡的東西。您應該將所有網絡代碼移到後臺Thread,例如AsyncTask。這將很容易讓你在後臺執行網絡操作,然後在UI上運行的函數中更新UI

AsyncTask Docs

Here is an answer示出的基本結構。基本上,您可以撥打中的AsyncTask(如onClick()),然後在doInBackground()中執行網絡操作,在任務第一次啓動時調用該操作,然後您可以使用其他任何方法更新UI

使用我引用的示例,您只需將所有網絡內容填入鏈接中示例的doInBackground()方法內,即看起來像onClick()中的所有內容。然後在你的onClick()你會做類似

lightbut.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     TalkToServer task = new TalkToServer(); // could pass params to constructor here but might not be needed in this situation 
     task.execute(); // could pass in params for `doInBackground()` such as url, etc... but again maybe not needed for this situation 
} 
+0

我該怎麼做?如果你給了我一個代碼,我會非常感謝! –

+0

我已經編輯了一個鏈接來開始使用它的一個例子。您還應該閱讀文檔,因爲您需要了解重要的信息。 – codeMagic

+0

我再次編輯了一些說明。這應該讓你開始。如果在其他任何地方都不需要,可以簡單地將'AsyncTask'作爲'Activity'的內部類。然後,您可以訪問「Activity」的成員變量以及訪問其功能 – codeMagic

相關問題