我想将我从字符串中获得的字符串传递给onPostExecute方法

时间:2019-01-22 19:47:35

标签: java android android-studio

我是android studio的新手,并且想要更多。实际上,我正在尝试将在微调器中获得的字符串传递给onCreateMethod并传递给onPostExecute函数。我将感谢您的帮助。贝娄是我的代码。

我尝试制作一个名为First的全局变量,并存储Spinner中的字符串并将其传递给onPostExecute函数。

 public class Convert extends AppCompatActivity implements LocationListener 
{
  Spinner dropdown;
  Button btn;
  String text;
  String first;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_convert);
    dropdown = (Spinner) findViewById(R.id.spinner1);
    btn = (Button)findViewById(R.id.btn);

String[] items = new String[]{"United States,USD", "Nepal,NPR", "Bangladesh,BDT","Brazil,BRL"};

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);

    dropdown.setAdapter(adapter);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            text = dropdown.getSelectedItem().toString();
            first = text.substring(text.length()-3);
            Log.i("her", first);
        }
    });
  new DownloadTask().execute("http://openexchangerates.org/api/latest.json? 
  app_id=XXXXXXXXXX");


}

public class DownloadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {


        String result = "";

        URL url;
        HttpURLConnection httpURLConnection = null;

        try {
            url = new URL(urls[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            InputStream in = httpURLConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {
                char counter = (char) data;
                result += counter;

                data = reader.read();
            }

            return result;


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);



        try{
            JSONObject jsonObject = new JSONObject(result);
            JSONObject curr = jsonObject.getJSONObject("rates");
            String npr = curr.getString(first);
            Log.i("money", npr );


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

我想要的是首先在onPostExecute函数上传递字符串。

1 个答案:

答案 0 :(得分:1)

当您调用DownloadTask时,asyncTask使用execute方法触发,只需将参数传递给他即可。示例:

如何传递网址

new DownloadTask().execute("url for download");

如何接收网址

protected String doInBackground(String... urls) {
    String url = urls[0]; // url for download
}

还可以发送参数数组。另外请注意AsyncTask,请不要传递上下文/视图变量,否则可能会引起内存泄漏,read docs