我正在开发一个小应用程序,我试图从网站上读取一些文本,将文本存储在变量中,然后在另一个活动中显示该文本。在我的主要活动中,我有一个名为“许可协议”的可点击标签,点击后,应用程序应该从网站读取一些文本,转到另一个活动,然后为用户显示该文本。但是,每次我点击我的标签时,我的app力都会关闭。有什么建议?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void activity_license(View view) throws IOException{
String stringBuffer;
String text ="";
URL url = new URL("http://something.something.com/LICENSE");
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
while((stringBuffer = bufferReader.readLine()) != null){
text += stringBuffer;
}
bufferReader.close();
Intent licenseIntent = new Intent(this, LicenseActivity.class);
licenseIntent.putExtra("LICENSE_AGREEMENT", text);
startActivity(licenseIntent);
}
}
这是我的第二个活动代码,我想要显示文本......
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;
public class LicenseActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license);
Intent intent = getIntent();
String licenseText = intent.getStringExtra("LICENSE_AGREEMENT");
TextView lblText = (TextView)findViewById(R.id.lblLicense);
lblText.setText(licenseText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_license, menu);
return true;
}
}
答案 0 :(得分:0)
// RETRIVE YOUR RESPONSE
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch (Exception e)
{
Log.e("Loading Runnable Error converting result :", e.toString());
}
现在将此结果打印为字符串。
答案 1 :(得分:0)
试试这个
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
text.append(line + "\n");
}
try
intent.putExtra("licence",text.toString);
如果这不起作用,请尝试 HttpGet 代替 HttpPost ......