這是我的第一個Android應用程序。我張貼我用於HTTP連接的代碼(不是我的,這是來自一個教程網站)。問題是當我按下按鈕來下載文本時,它顯示進度對話框並且app force關閉。我張貼代碼。嘗試使Http連接時應用程序強制關閉
package com.example.httpconnectsample;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Httpconnectionsample extends Activity {
private Button getImageButton;
private Button getTextButton;
private ProgressDialog progressDialog;
private Bitmap bitmap = null;
private String text = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_httpconnectionsample);
getImageButton = (Button)findViewById(R.id.Button01);
getTextButton = (Button)findViewById(R.id.Button02);
getImageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
downloadImage("http://www.android.com/media/wallpaper /gif/android_logo.gif");
}
});
getTextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
downloadText("http://xyz.com")
}
});
}
private void downloadImage(String urlStr) {
progressDialog = ProgressDialog.show(this, "", "Fetching Image...");
final String url = urlStr;
new Thread() {
public void run() {
InputStream in = null;
Message msg = Message.obtain();
msg.what = 1;
try {
in = openHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
messageHandler.sendMessage(msg);
}
}.start();
}
private void downloadText(String urlStr) {
progressDialog = ProgressDialog.show(this, "", "Fetching Text...");
final String url = urlStr;
new Thread() {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
Message msg = Message.obtain();
msg.what=2;
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (IOException e) {
e.printStackTrace();
}
messageHandler.sendMessage(msg);
}
}.start();
}
private InputStream openHttpConnection(String urlStr) {
InputStream in = null;
int resCode = -1;
try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException ("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return in;
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
/*case 1:
ImageView img = (ImageView) findViewById(R.id.imageview01);
img.setImageBitmap((Bitmap)(msg.getData().getParcelable("bitmap")));
break; */
case 2:
TextView text = (TextView) findViewById(R.id.textview01);
text.setText(msg.getData().getString("text"));
break;
}
progressDialog.dismiss();
}
};
}
下面是我的XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="24dp"
android:text="Button" />
<Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="56dp"
android:text="Button" />
<TextView
android:id="@+id/textview01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/Button02"
android:layout_marginTop="39dp"
tools:context=".Httpconnectionsample" />
</RelativeLayout>
</ScrollView>
以下是日誌: -
10-26 15:22:43.660: D/ddm-heap(23866): Got feature list request
10-26 15:22:48.930: W/System.err(23866): java.net.SocketException: Permission denied (maybe missing INTERNET permission)
10-26 15:22:48.940: W/System.err(23866): at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocketImpl(Native Method)
10-26 15:22:48.945: W/System.err(23866): at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocket(OSNetworkSystem.java:187)
10-26 15:22:48.945: W/System.err(23866): at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:266)
10-26 15:22:48.950: W/System.err(23866): at java.net.Socket.checkClosedAndCreate(Socket.java:889)
10-26 15:22:48.950: W/System.err(23866): at java.net.Socket.connect(Socket.java:1036)
10-26 15:22:48.950: W/System.err(23866): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init> (HttpConnection.java:62)
10-26 15:22:48.950: W/System.err(23866): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager$ConnectionPool.getHttpConnection(HttpConnectionManager.java:145)
10-26 15:22:48.950: W/System.err(23866): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager.getConnection(HttpConnectionManager.java:67)
10-26 15:22:48.960: W/System.err(23866): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getHTTPConnection(HttpURLConnection.java:821)
10-26 15:22:48.960: W/System.err(23866): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:807)
10-26 15:22:48.965: W/System.err(23866): at com.example.httpconnectsample.Httpconnectionsample.openHttpConnection(Httpconnectionsample.java:142)
10-26 15:22:48.965: W/System.err(23866): at com.example.httpconnectsample.Httpconnectionsample.access$3(Httpconnectionsample.java:126)
10-26 15:22:48.965: W/System.err(23866): at com.example.httpconnectsample.Httpconnectionsample$5.run(Httpconnectionsample.java:97)
10-26 15:22:48.965: W/dalvikvm(23866): threadid=15: thread exiting with uncaught exception (group=0x4001b180)
10-26 15:22:48.995: E/AndroidRuntime(23866): Uncaught handler: thread Thread-8 exiting due to uncaught exception
10-26 15:22:49.090: E/AndroidRuntime(23866): java.lang.NullPointerException
10-26 15:22:49.090: E/AndroidRuntime(23866): at java.io.Reader.<init>(Reader.java:65)
10-26 15:22:49.090: E/AndroidRuntime(23866): at java.io.InputStreamReader.<init>(InputStreamReader.java:65)
10-26 15:22:49.090: E/AndroidRuntime(23866): at com.example.httpconnectsample.Httpconnectionsample$5.run(Httpconnectionsample.java:99)
10-26 15:22:49.100: I/dalvikvm(23866): threadid=7: reacting to signal 3
10-26 15:22:49.115: I/dalvikvm(23866): Wrote stack trace to '/data/anr/traces.txt'
我試圖尋找一種修復,但不明白爲什麼會這樣。我只需要下載文本,因此目前我忽略了此代碼的下載圖像部分。此外,我在清單中添加了 使用權限android:name =「android.permission.INTERNET」 ,但仍然顯示權限被拒絕。 我會很感激任何幫助。
發表您的AndroidManifest.xml文件 –