Issue
I have an Asynctask class that makes an API call and parses the JSON into a string for me. I then want to use this string in the Activity class and place in a string array. How can I go about this ?
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
}
}
This is the first class where the data is fetched and parsed. Here is the Activity in which I wish to use the result from the AsyncTask
**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;
}
}
coin Adapter class
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();
}
}
Thanks for your time in advance :)
Solution
You can set a listener to send your string result named "coinNamesParsed" back to origin activity, which execute asynctask named "fetchDataClass", then intent to searchActivity and also bring what you get at 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);
}
}
After edited sample code like 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);
}
}
Answered By - Sean Lee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.