In my Android App, I am executing the URL for n number of times. The program loads quick when there is a less number of items in the arraylist "prefCoinList". It actually takes lot of time when the number of itemsin the list is more. This causes serious delay while loading the App.
I need to do this quickly using any parallel process. Could you please advice any efficient process ?
public class initialFetchAltCoins extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
}
protected String doInBackground(String... params) {
try {
loadAltCoins(getAltCoinData());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String params) {
maingame.dataReady=true;
//-- Testing 1111 starts----
System.out.println("Testing 1111 loading Initial + (Prefered + Tran Coins) : " + df.format(new Date()));
//-- Testing 1111 Ends----
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
}
}
public String getAltCoinData() throws IOException {
List<String> setting = getSetting();
BufferedReader br = new BufferedReader(new InputStreamReader(getDataFromURL("https://api.coinmarketcap.com/v1/ticker/?convert="+setting.get(0)+"&limit="+setting.get(1))));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if(!line.toString().equals("]")){
sb.append(line);
}
sb.append("\n");
}
//-- Testing 1111 starts----
System.out.println("Testing 1111 Initial 30 coins Loading Time : " + df.format(new Date()));
//-- Testing 1111 Ends----
List<String> prefCoinList = getPrefCoin();
if(prefCoinList.size()>0){
sb.append(",");
for(int i=0;i<prefCoinList.size();i++){
System.out.println("prefCoinList.get(i) : " + prefCoinList.get(i));
System.out.println("setting.get(0) : " + setting.get(0));
br = new BufferedReader(new InputStreamReader(getDataFromURL("https://api.coinmarketcap.com/v1/ticker/"+prefCoinList.get(i)+"/?convert="+setting.get(0))));
while ((line = br.readLine()) != null) {
if(!(line.toString().equals("[") )) {
if(!line.toString().equals("]")){
sb.append(line);
} else{
if(i!=(prefCoinList.size()-1)){
sb.append(",");
}
}
}
sb.append("\n");
}
if(i==(prefCoinList.size()-1)){
sb.append("]");
}
}
}else{
sb.append("]");
}
//-- Testing 1111 starts----
System.out.println("Testing 1111 loading (Prefered + Tran Coins) : " + df.format(new Date()));
//-- Testing 1111 Ends----
br.close();
return sb.toString();
}
You can use an
ExecutorServiceto pool and execute a number of requests, or even launch several async tasks, one per URL you want to fetch. This means, instead of having a singleinitialFetchAltCoinsclass which secuentially reads all the url's, launch anAsyncTaskfor every URL. If you follow this approach, make sure you have a way of controlling how many threads are sent at once. You don't want to make 100 tasks at once.