使用edittext将主要活动中的字符串转换为扩展AsyncTask的活动

时间:2017-09-30 16:05:09

标签: android android-asynctask

我需要通过从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 =从编辑文本中获取的任何城市名称。

1 个答案:

答案 0 :(得分:1)

有多种方法可以将数据传递给AsyncTask

  1. AysncTask中创建一个带参数的构造函数,如< - p>

      public void fetchData(String city) {
    
      } 
    
  2. 传递AsyncTask参数中的值 - < - p>

     fetchData process = new fetchData();
     process.execute(text.getText().toString()); // Pass parameter
    
  3. 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>