Autocomplete Feature für Kursnamen hinzugefügt (eigene API, da von DHBW nicht bereitg...
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / network / JsonRequestHelper.java
1 package de.dhbwloe.campusapp.network;
2
3 import android.util.Log;
4
5 import com.loopj.android.http.AsyncHttpClient;
6 import com.loopj.android.http.AsyncHttpResponseHandler;
7
8 import org.json.JSONArray;
9 import org.json.JSONException;
10 import org.json.JSONObject;
11
12 import java.util.List;
13
14 import cz.msebera.android.httpclient.Header;
15
16 /**
17  * Created by pk910 on 09.03.2016.
18  */
19 public abstract class JsonRequestHelper {
20
21     protected void requestJsonFromWeb(String url) {
22         AsyncHttpClient client = new AsyncHttpClient();
23
24         Log.i("HTTPClient", "Request: " + url);
25         client.get(url, new AsyncHttpResponseHandler() {
26             @Override
27             public void onStart() {
28             }
29
30             @Override
31             public void onSuccess(int statusCode, Header[] headers, byte[] response) {
32                 String recvStr = new String(response);
33                 JSONObject jsonObj = null;
34                 JSONArray jsonArr = null;
35                 try {
36                     jsonObj = new JSONObject(recvStr);
37                 } catch (JSONException e) {
38                     e.printStackTrace();
39                 }
40                 try {
41                     jsonArr = new JSONArray(recvStr);
42                 } catch (JSONException e) {
43                     e.printStackTrace();
44                 }
45                 if(jsonObj != null)
46                     onJsonReceived(jsonObj);
47                 else if(jsonArr != null)
48                     onJsonReceived(jsonArr);
49                 else
50                     onTextReceived(recvStr);
51             }
52
53             @Override
54             public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
55                 String error = null;
56                 try {
57                     error = new String(errorResponse, "US-ASCII");
58                 } catch (Exception e1) {
59                 }
60                 Log.i("HTTPClient", "  Error: " + statusCode + " - " + error);
61                 onJsonRequestFail(statusCode, error);
62             }
63
64             @Override
65             public void onRetry(int retryNo) {
66             }
67         });
68     }
69
70     protected abstract void onJsonReceived(JSONObject json);
71     protected abstract void onJsonReceived(JSONArray json);
72     protected abstract void onTextReceived(String response);
73     protected abstract void onJsonRequestFail(int statusCode, String errorMessage);
74
75 }