SenderReceiver.java
public class SenderReceiver extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
String query;
ListView lv;
ProgressDialog pd;
public SenderReceiver(Context c, String urlAddress, String query, ListView lv,ImageView...imageViews) {
this.c = c;
this.urlAddress = urlAddress;
this.query = query;
this.lv = lv;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Pesquisando...");
pd.setMessage("Por favor aguarde.");
pd.show();
}
@Override
protected String doInBackground(Void... params) {
return this.sendAndReceive();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
lv.setAdapter(null);
if(s != null) {
if(!s.contains("null")) {
Parser p = new Parser(c,s,lv);
p.execute();
} else {
Toast.makeText(c.getApplicationContext(), "Usuário não encontrado.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(c.getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
private String sendAndReceive()
{
HttpURLConnection con = Connector.connect(urlAddress);
if(con==null) {
return null;
} try {
OutputStream os = con.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
bw.write(new DataPackager(query).packageData());
bw.flush();
bw.close();
os.close();
int responseCode = con.getResponseCode();
if(responseCode==con.HTTP_OK) {
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
if(br != null) {
while ((line=br.readLine()) != null) {
response.append(line+"n");
}
} else {
return null;
}
return response.toString();
} else {
return String.valueOf(responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DataPackager.java
public class DataPackager {
String query;
public DataPackager(String query) {
this.query = query;
}
public String packageData() {
JSONObject jo = new JSONObject();
StringBuffer queryString = new StringBuffer();
try {
jo.put("Query",query);
Boolean firstValue = true;
Iterator it = jo.keys();
do {
String key = it.next().toString();
String value = jo.get(key).toString();
if(firstValue) {
firstValue = false;
} else {
queryString.append("&");
}
queryString.append(URLEncoder.encode(key,"UTF-8"));
queryString.append("=");
queryString.append(URLEncoder.encode(value,"UTF-8"));
} while (it.hasNext());
return queryString.toString();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}