我有以下android應用程序(見下文),它從url中讀取文本文件並在textview中顯示它。現在我需要更改代碼,以便bt.execute中使用的url地址由用戶輸入而不是硬編碼,即當應用程序啓動時,它應該首先要求用戶給出url地址,並且只有在繼續執行之後。該應用旨在用於真實設備。如何使url連接到用戶給定的地址
任何建議非常感謝!
package com.example.kaytto.main;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
private Activity context;
private ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute("http://123.12.22.32/tmp/text.txt");
}
//background process to download the file from internet
private class BackTask extends AsyncTask<String,Integer,Void>{
String text="";
protected void onPreExecute(){
super.onPreExecute();
//display progress dialog
pd = new ProgressDialog(context);
pd.setTitle("Reading alarms");
pd.setMessage("Please wait...");
pd.setCancelable(true);
pd.setIndeterminate(false);
pd.show();
}
protected Void doInBackground(String...params){
URL url;
int lines = 0;
try {
//create url object to point to the file location on internet
url = new URL(params[0]);
//make a request to server
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//get InputStream instance
InputStream is=con.getInputStream();
//create BufferedReader object
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
//read content of the file line by line
while((line=br.readLine())!=null){
if(++lines > 1900)
text+=line + "\n";
}
br.close();
}catch (Exception e) {
e.printStackTrace();
//close dialog if error occurs
if(pd!=null) pd.dismiss();
}
return null;
}
protected void onPostExecute(Void result){
//close dialog
if(pd!=null)
pd.dismiss();
TextView txtview = (TextView) findViewById(R.id.text_view);
txtview.setMovementMethod(ScrollingMovementMethod.getInstance());
//display read text in TextView
txtview.setText(text);
}
}
}
謝謝!這是一個完美的答案!我仍然需要使用我的佈局,否則你的代碼完美地工作。 – Vallu
我的榮幸。隨時接受/ upvote答案。 :) – Darish
我試過了,但由於聲譽得分,我無法做到這一點 – Vallu