I have PostData class to transmit data lat, long,mac,..
to the server which is being sent to it from the service class. In PostData class, the data is being processed with the aid of AsyncTask
and HttpURLConnection
.
Now I have a new activity where the user can send query to the server. To reach that I have to get ArrayList<Integer>
from the server and create a something like checkbox list, where the user can select the desirable items then the data will be sent to the server to retrieve a result.
Can I implement a new Asyntask
and HttpURLConnection
to achieve that or I have to use my AsynTask
and HttpURLCOnnection
in the POstData
class?
I appreciate any help.
My PostData class:
public class PostData {
String jSONString;
private AsyncTaskCallback callback;
public PostData(AsyncTaskCallback callback) {
this.callback = callback;
}
public String getjSONString() {
return jSONString;
}
public void setjSONString(String jSONString) {
this.jSONString = jSONString;
}
public void post_data(String jSONString, Context context) {
this.jSONString = jSONString;
new MyAsyncTask(context).execute(jSONString);
}
class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
final Context mContext;
ArrayList<Integer> routes = new ArrayList<Integer>();
double distance;
public MyAsyncTask(Context context) {
mContext = context;
}
@Override
protected ArrayList<Integer> doInBackground(String... params) {
BufferedReader reader = null;
try {
URL myUrl = new URL(
"https://bustracker.rhcloud.com/webapi/test");
HttpURLConnection conn = (HttpURLConnection) myUrl
.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes(params[0]);
wr.close();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Gson gson = new Gson();
StopsJSON data = gson.fromJson(sb.toString(), StopsJSON.class);
routes = data.getRoutes();
distance = data.getDistance();
System.out.println("The output of the StringBulder: "
+ sb.toString());
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
return null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
protected void onPostExecute(ArrayList<Integer> result) {
if (routes != null && !routes.isEmpty()) {
callback.onAsyncTaskFinished(routes, distance);
}else{
Log.e("123", "Avoiding null pointer, the routes are null!!!");
}
}
}
}