웹 사이트에서 한 줄의 텍스트를 읽으려고하면 오류가 발생합니다 (NetworkOnMainThreadException). 나는 몇 가지 시도했지만 지금까지 아무것도 작동하지 않습니다. 그래서 누군가가 도울 수 있다면 코드가 있습니다. 매니 페스트에는 인터넷에 대한 허가가있어서 문제가 없어야합니다.NetworkOnMainThreadException 웹에서 읽을 때
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Weather extends Activity {
Button button;
TextView t;
String result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
t = (TextView)findViewById(R.id.textView1);
}
public void myButtonClickHandler (View view) throws ClientProtocolException, IOException {
result = getContentFromUrl("http://url.com");
t.setText(result);
}
public static String getContentFromUrl(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null) {
InputStream inStream = entity.getContent();
String result = Weather.convertStreamToString(inStream);
inStream.close();
return result;
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Humm, 제발 이것과 함께 제게 제공 할 수 있습니까? – HyperX
예 : http://www.vogella.de/articles/AndroidPerformance/article.html 및 http://www.xoriant.com/blog/mobile-application-development/android-async-task.html에서 볼 수 있습니다. http://developer.android.com/resources/articles/painless-threading.html –