Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reuse a rest connection class all over my app?
    primarykey
    data
    text
    <p>I've been trying to find an answer here but I feel that none of the questions asked are helping me. </p> <p>I'm developing an Android App which will be under constant maintenance and changes. It will also use a lot of rest services. In iOS I managed to create a connection class which handled the connections and all it needed to receive was the name of the service it was invoking and parameters in case those were needed to invoke a specific service. It was really easy to maintain because all the connection code was in this single class. I tried to do the same thing in Android but I have a really difficult time because of the threads (I'm using AsyncTask). I'm very new to Android development so please forgive me if I'm doing something really dumb or if I just don't know of some android object that will help me with this.</p> <p>This is the code of my MainActivity calling the "Connection Class"</p> <pre><code>public void submitLogin(View view){ RestHandler rh=new RestHandler(); rh.mainActivity=this; int connection = rh.checkConnection(this); if(connection!=0){ /*GetServiceTask task = new GetServiceTask(); task.execute(new String []{"http://httpbin.org/ip","http://httpbin.org/get"});*/ rh.performServiceWithData(true, "http://httpbin.org/get"); }else{ new AlertDialog.Builder(this).setTitle(R.string.popup_info).setMessage(R.string.error_network).setNeutralButton(R.string.accept, null).show(); } } public void success(String result){ new AlertDialog.Builder(this).setTitle(R.string.popup_info).setMessage("success: " + result).setNeutralButton(R.string.accept, null).show(); } </code></pre> <p>And this is the code of the "Connection Class"</p> <pre><code>public class RestHandler{ private HttpClient client; private HttpPost httPost; private HttpGet httpGet; private HttpResponse response; private HttpEntity entity; private InputStream inputStream; private BufferedReader reader; private StringBuilder stringBuilder; private String line; private String result; private String finalResult="UNMODIFIED"; MainActivity mainActivity; public String performServiceWithData(boolean isGet, String url){ if(isGet){ GetServiceTask task = new GetServiceTask(); task.execute(new String[]{url}); }else{ PostServiceTask task = new PostServiceTask(); task.execute(new String[]{url}); } return finalResult; } private class GetServiceTask extends AsyncTask&lt;String, Void, String&gt;{ protected String doInBackground(String... services) { String response = ""; for(String service:services){ response=response + "\n" + sendGet(service); } return response; } protected void onPostExecute(String result) { finalResult = result; mainActivity.success(finalResult); } } private class PostServiceTask extends AsyncTask&lt;String, Void, String&gt;{ protected String doInBackground(String... services) { String response = ""; RestHandler rh=new RestHandler(); for(String service:services){ response=response + "\n" + sendPost(service, null); } return response; } protected void onPostExecute(String result) { finalResult = result; } } public String sendGet(String path) { try { client = new DefaultHttpClient(); httpGet = new HttpGet(path); response = client.execute(httpGet); entity = response.getEntity(); inputStream = entity.getContent(); reader = new BufferedReader(new InputStreamReader(inputStream)); stringBuilder = new StringBuilder(); line = ""; result = ""; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } result = stringBuilder.toString(); inputStream.close(); return result; } catch (Exception e) { result = e.toString(); return null; } } public String sendPost(String path, List nameValuePairs) { try { client = new DefaultHttpClient(); stringBuilder = new StringBuilder(path); httPost = new HttpPost(stringBuilder.toString()); httPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = client.execute(httPost); entity = response.getEntity(); inputStream = entity.getContent(); reader = new BufferedReader(new InputStreamReader(inputStream)); stringBuilder = new StringBuilder(); line = ""; result = ""; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } result = stringBuilder.toString(); inputStream.close(); return /*"sendPost correct " +*/ result; } catch (Exception e) { return "sendPost exception " + e.toString(); } } public int checkConnection(Activity activity) { int connectionType=0; /* connectionType 0 --&gt; no connection * connectionType 1 --&gt; wifi * connectionType 2 --&gt; cell network*/ ConnectivityManager cm = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] info = cm.getAllNetworkInfo(); for (NetworkInfo ni : info) { if (ni.getTypeName().equalsIgnoreCase("wifi")) if (ni.isConnected()) connectionType=1; if (ni.getTypeName().equalsIgnoreCase("mobile")) if (ni.isConnected()) connectionType=2; } return connectionType; } } </code></pre> <p>This code works but I would like to make something similar to this that could be used by any activity in my app, this example i developed so far only works because I'm using MainActivity as an object in the connection class. </p> <p>Any suggestions on how to make something similar but independent of the class? should the asyncTask be executed in each Activity instead of the "Connection" class?</p> <p>BTW, sorry for my English :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload