从AsyncTask返回一个String以在另一个Activity中使用?

时间:2018-03-28 00:37:06

标签: arrays string api android-studio android-asynctask

我有一个Asynctask类,它进行API调用并将JSON解析为一个字符串。然后我想在Activity类中使用这个字符串并放在一个字符串数组中。我怎么能这样做呢?

fetchDataClass- Aysnc

public class fetchDataClass extends  AsyncTask<Void, Void, Void> {


    String result = ""; //json result
    String coinNamesParsed = "";//parsed attributes
    String coinNames = ""; //String for each coinName with each iteration of 
                           //loop

    @Override
    protected Void doInBackground(Void... voids) {
        //Background Thread i.e API request
        try {
            URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream(); 
           //read result in from the connection

            BufferedReader bufferedReader = new BufferedReader(new 
            InputStreamReader(inputStream)); 

            String line = "";

            //Loop that reads all lines and represents them to as a string
            while (line != null) {
                line = bufferedReader.readLine(); //read line of json and 
                //assign to "line" if not null
                result = result + line;
            }

            //get the whole json object from the json file
            JSONObject myJsonObj = new JSONObject(result);

            //target the "result" Array of objects(BTC,LTC,ETH) and map them 
            //to a JsonArray for parsing

            JSONArray myJsonArray = myJsonObj.getJSONArray("result");

            //Itterate through the array and get the attributes of each 
           // object

            for (int i = 0; i < myJsonArray.length(); i++) {
                //for every object in the Array cast them and their 
                //attributes to another JSONobject

                JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);

                //Single JSON object parsed each iteration and name 
                //attritbute is targeted

                coinNames = myJsonObject.opt("MarketName") + "\n";

                //add the parsed result to the string coinNamesParsed
                coinNamesParsed = coinNamesParsed + coinNames + "\n";
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    //Runs on the UI thread after doInBackground()
    @Override
    protected void onPostExecute(String result) {
        //UI thread



    }
}

这是获取和解析数据的第一个类。这是我希望使用AsyncTask

结果的Activity

** SearchActivity **

public class searchActivity extends AppCompatActivity implements 
SearchView.OnQueryTextListener{

// Declare Variables
public static String coinNamesParesed = "";
ListView list;
coinAdapter adapter;
SearchView editsearch;
String[] coinNameList;

ArrayList<Coin> arraylist = new ArrayList<Coin>();

    //ON CREATE
    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);




        /*
        *
        *This is the string ARRAY i wish to contain the result of the 
        *AsyncTask
        *
        * */

        coinNameList = new String[]{String data from Async HERE };





        // Locate the ListView in content_search.xml
        list = findViewById(R.id.SearchResultList);

        for (int i = 0; i < coinNameList.length; i++) {
            Coin coinNames = new Coin(coinNameList[i]);
            // Binds all strings into an arraylist one by one
            arraylist.add(coinNames);
        }
        // Pass results to ListViewAdapter Class
        adapter = new coinAdapter(this, arraylist);

        // Binds the Adapter to the ListView
        list.setAdapter(adapter);

        // Locate the EditText in listview_main.xml
        editsearch = findViewById(R.id.SearchBar);
        editsearch.setOnQueryTextListener(this);
    }

private void setSupportActionBar(Toolbar toolbar) {
}

@Override
public boolean onQueryTextSubmit(String query) {
    //do something on text submit
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    //do something when the text changes
    String text = newText;
    adapter.filter(text);
    return false;
}
}

硬币适配器类

public class coinAdapter extends BaseAdapter {

// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Coin> coinNamesList = null;
private ArrayList<Coin> arraylist;

public coinAdapter(Context context, List<Coin> coinNamesList) {
    mContext = context;
    this.coinNamesList = coinNamesList;
    inflater = LayoutInflater.from(mContext);
    this.arraylist = new ArrayList<Coin>();
    this.arraylist.addAll(coinNamesList);
}
public class ViewHolder {
    TextView name;
}
@Override
public int getCount() {
    return coinNamesList.size();
}
@Override
public Coin getItem(int position) {
    return coinNamesList.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}

public View getView(final int position, View view, ViewGroup parent) {
    final ViewHolder holder;

    if (view == null) {
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.content_search, null);
        // Locate the TextViews in content_Search.xml
        holder.name = view.findViewById(R.id.name);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }
    // Set the results into TextViews
    holder.name.setText(coinNamesList.get(position).getCoinName());
    return view;
}
// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    coinNamesList.clear();
    if (charText.length() == 0) {
        coinNamesList.addAll(arraylist);
    } else {
        for (Coin wp : arraylist) {
            if (wp.getCoinName().toLowerCase(Locale.getDefault()).contains(charText)) {
               coinNamesList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}
}

感谢您提前的时间:)

1 个答案:

答案 0 :(得分:1)

您可以设置一个侦听器来发送名为&#34; coinNamesParsed&#34;的字符串结果。回到原始活动,执行名为&#34; fetchDataClass&#34;的asynctask,然后意图搜索活动,并将你得到的内容带到fetchDataClass。

searchActivity:

    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        list = findViewById(R.id.SearchResultList);
        editsearch = findViewById(R.id.SearchBar);

        ......
        FetchDateListener listener = new FetchDateListener();
        new fetchDataClass(listener).execute();
        ......

    }

    class FetchDateListener implements fetchDataClass.IFetchDateListener {
        @Override
        public void fetchDataResult(String coinNamesParsed) {
            // coinNamesParsed what you get from fetchDataClass
            ......
            coinNameList = new String[]{String data from Async HERE };

            for (int i = 0; i < coinNameList.length; i++) {
                Coin coinNames = new Coin(coinNameList[i]);
                // Binds all strings into an arraylist one by one
                arraylist.add(coinNames);
            }
            // Pass results to ListViewAdapter Class
            adapter = new coinAdapter(this, arraylist);

            // Binds the Adapter to the ListView
            list.setAdapter(adapter);

            // Locate the EditText in listview_main.xml
            editsearch.setOnQueryTextListener(this);
        }
    }

经过编辑后的示例代码:

fetchDataClass:

public class fetchDataClass extends  AsyncTask<Void, Void, ArrayList<String>> {
    interface IFetchDateListener {
        void fetchDataResult(ArrayList<String> coinNamesParsed);
    }

    String result = ""; //json result
    ArrayList<String> coinNamesParsed = new ArrayList<String>();//parsed attributes
    String coinNames = ""; //String for each coinName with each iteration of 
                           //loop

    IFetchDateListener listener;

    fetchDataClass(IFetchDateListener listener) {
        this.listener = listener;
    }

    .......

    @Override
    protected ArrayList<String> doInBackground(Void... voids) { <-----this line

        .......

            for (int i = 0; i < myJsonArray.length(); i++) {
                //for every object in the Array cast them and their 
                //attributes to another JSONobject

                JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);

                //Single JSON object parsed each iteration and name 
                //attritbute is targeted

                coinNames = myJsonObject.opt("MarketName");

                //add the parsed result to the string coinNamesParsed
                coinNamesParsed.add(coinNames);
            }
            return coinNamesParsed;//<------- you don't return what you catch
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    //Runs on the UI thread after doInBackground()
    @Override
    protected void onPostExecute(ArrayList<String> result) {
        //UI thread

        listener.fetchDataResult(result);
    }
}