gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:21:32 25 4
gpt4 key购买 nike

我是 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 函数上传递字符串。

最佳答案

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

如何传递url

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

如何接收url

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

您还可以发送参数数组。另外要小心 AsyncTask,不要传递上下文/ View 变量,它可能会导致内存泄漏,read docs .

关于java - 我想将从字符串中获取的字符串传递给 onPostExecute 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54315444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com