我有一个Java程序,它与下面的代码完美配合。当我将它添加到Android时,我在BufferedReader行获得异常。我已经为清单文件添加了权限。我在实际设备上运行代码。 runController()方法返回一个我在屏幕上打印的String。我能找到的唯一解决方案是必须添加互联网权限,我这样做了。我不知道我错过了什么。任何帮助将不胜感激。我的代码如下:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidwebconnect"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidwebconnect.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Java代码是:
public class ControllerLast {
private static URL urlObj;
private static URLConnection connection;
String message;
String urlString = "http://www.dailydiary.hljointventure.co.za/viewentry.php"; //the url for the website is here
public ControllerLast() {
}
public String runControllerLast() {
try {
urlObj = new URL(urlString);
connection = urlObj.openConnection();
connection.setDoOutput(true);
}
catch (MalformedURLException ex) {
message = ex.getMessage();
}
catch (Exception ex) {
message = ex.getMessage();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {
message = lineRead;
}
reader.close();
}
catch (IOException ex) {
message = ex.getMessage();
}
return message;
}
}
public class MainActivity extends Activity {
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStatus = (Button)findViewById(R.id.btn_check);
final TextView text = (TextView)findViewById(R.id.text);
btnStatus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
text.setText(message);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}