I am trying to consume a Rest Webservice. As i can not perform network operations in UI thread so i tried doing this using AsyncTask. Below is my code for my AsyncTask
public class CallMeServiceAsyncTask extends AsyncTask<String, Void, List<Service>> {
@Override
protected List<Service> doInBackground(String... params) {
CallmeService service= ServiceFactory.getCallmeService();
List<Service> services= service.getAllServices(); //Calls web service and Parses Json Response
return services;
}
}
CallmeService.getAllService() provides a service layer which eventually calls below method
public static String makeRestRequest(String url) throws MalformedURLException,IOException {
String response="";
URL restUrl= new URL(url);
HttpURLConnection connection=(HttpURLConnection)restUrl.openConnection();
InputStream is=new BufferedInputStream(connection.getInputStream());
response=convertStreamToString(is);
return response;
}
Now i am calling my task from onCreate method of my activity as below
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_home);
this.optionsList=(ListView)findViewById(R.id.optionsList);
//String[] options={"Teacher","Plumber","Electricians"};
ArrayAdapter adapter=getServiceMenu();
this.optionsList.setAdapter(adapter);
optionsList.setOnItemClickListener(this);
}
private ArrayAdapter getServiceMenu()
{
ArrayAdapter adapter= null;
try {
List<Service> menuServices= new CallMeServiceAsyncTask().execute("").get();
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, menuServices);
}
catch(Exception x)
{
x.printStackTrace();
}
return adapter;
}
I am very new to android development and not able to figure out what is the issue with above code. Please help me out. Let me know if you need more code to understand.