我需要通过从MainActivity获取输入将字符串传递给AsyncTask中存在的url,将字符串传递给AsyncTask。我有两个活动,一个是MainActivity,另一个是fetchData活动。我的MainActivity代码:
public class MainActivity extends AppCompatActivity {
Button click;
EditText text;
public static TextView data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = (Button) findViewById(R.id.button);
data = (TextView) findViewById(R.id.fetcheddata);
text = (EditText) findViewById(R.id.editText);
String theText = text.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {fetchData process = new fetchData();process.execute();}});}}
我的fetchData活动代码如下:
public class fetchData extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
String uriString;
@Overrideprotected Void doInBackground(Void... voids) {
try {
URL url = new URL("http://fuelpriceindia.herokuapp.com/price?city=mumbai");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;}
JSONObject JO = new JSONObject(data);
}}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}return null;}@Override protected void onPostExecute(Void aVoid){super.onPostExecute(aVoid);MainActivity.data.setText(this.dataParsed);}}`
我想传递一个字符串来获取网址中的任何城市名称
URL url = new URL("http://fuelpriceindia.herokuapp.com/price?city=mumbai");
city =从编辑文本中获取的任何城市名称。
答案 0 :(得分:1)
有多种方法可以将数据传递给AsyncTask
。
在AysncTask
中创建一个带参数的构造函数,如< - p>
public void fetchData(String city) {
}
传递AsyncTask
参数中的值 - < - p>
fetchData process = new fetchData();
process.execute(text.getText().toString()); // Pass parameter
在AsyncTask
获取此值
@Override
protected Void doInBackground(String...params)
{
String cityName = params[0];
try {
URL url = new URL("http://fuelpriceindia.herokuapp.com/price?city="+cityName);
.......
}
确保转换
public class fetchData extends AsyncTask<Void,Void,Void>
进入
public class fetchData extends AsyncTask<String,Void,Void>