AsyncTask not returning any response - java

Hi I have trouble getting the response of my url from my host. I tried putting static variables and it worked but when I tried to use a asynctask for response it didnt work.
<?PHP
include_once('connection.php');
$where='';
if(isset($_GET['userLat']) && isset($_GET['userLng'])){
$where = "WHERE ((userLat >= '".addslashes($_GET['userLat'])."' AND userLat <= '".addslashes($_GET['userLat'])."' + .00901) OR (userLat <= '".addslashes($_GET['userLat'])."' AND userLat >= '".addslashes($_GET['userLat'])."' - .00901)) AND ((userLng >= '".addslashes($_GET['userLng'])."' AND userLng <= '".addslashes($_GET['userLng'])."' + .014935) OR (userLng <= '".addslashes($_GET['userLng'])."' AND userLng >= '".addslashes($_GET['userLng'])."' - .014935))";
$query = "SELECT * FROM tbl_user ".$where." AND isOnline = 'Yes' LIMIT 1 ";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$json['details'][]=$row;
}
}
mysqli_close($conn);
echo json_encode($json);
}
?>
AsyncTask
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setMessage("Checking nearby wingmans");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
request = result;
Log.d("Test", result);
}
}
how i call my url
btnEmergency.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();
new JsonTask().execute(url);
}
});
Thanks guys i hope i get an answer to my question. Thanks :)

Very foolish of me. I jsut change the AND to & in my url
from
String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();
to
String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"&userLng="+tvLng.getText().toString();
And it worked. Thanks!

Related

Exctracting more than one field at time from a JSon file

I was developing a simple application that exctracts some fields of a JSon that tells me in real time what weather is in that exact moment, and I have exctracted only one filed, and I was asking myself: Is it possible to extract more than on field at time?
Here is the the link from where i parse the Json:
https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139
And here's my code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
ArrayMap<Integer, String> arrayMap = new ArrayMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139");
}
});
}
public class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
try {
JSONObject Object = new JSONObject(result);
JSONArray arr = new JSONArray(Object.getString("weather"));
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
//txtJson.append("main: " + jsonPart.getString("main") + '\n');
arrayMap.put(i, jsonPart.getString("main"));
txtJson.append("main: " + arrayMap.get(i) + '\n');
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
//txtJson.setText(result);
}
}
}
If I understand correctly you want to extract other object alongwith main from the array weather
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F50n.png?1499366021876"
}
If that is the requirement then you can use the same process like you have done just change the name of the object.
arrayMap.put(i, jsonPart.getString("description"));
or
you can use gson and convert the object in pojo class in one go. Then use the object of the pojo and access the data.
Hope it helps.

How to return background result?

I did the code in android to retrieve records from website url. But I am stuck in receiving the result in string variable.
I want to display received values in receiveddata variable. Please help me on this..
I did this code:
Main2Activity.java
btnsync.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String receiveddata="";
Toast.makeText(getApplicationContext(), "Syncing data...",Toast.LENGTH_SHORT).show();
SyncLoginData process = new SyncLoginData();
process.execute();
Toast.makeText(getApplicationContext(), "Data synced successfully....",Toast.LENGTH_SHORT).show();
}
});
SyncLoginData.java
public class SyncLoginData extends AsyncTask<Void, Void, Void> {
String data="";
String dataParsed = "";
DatabaseHelper mydb;
String singleParsed ="";
#Override
protected Void doInBackground(Void... voids) {
try
{
URL url = new URL("https://api.myjson.com/bins/1034t9");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Main2Activity.data.setText(this.data);
}
}
Try this instead.
public class SyncLoginData extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... voids) {
String data;
try {
URL url = new URL("https://api.myjson.com/bins/1034t9");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String data) {
Main2Activity.data.setText(data);
}
}

How can i display images that i am receiving from (server) in a string ? Here is the code:

How can i display images that i am receiving from (server) in a string ?
I'm using AsyncTask
Here is the code:
AsyncTask
public class sendRequest extends AsyncTask<String, Void,String> {
String response="";
Context context;
sendRequest(Context context)
{
this.context=context;
// this.list=list;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params)
{
URL url;
BufferedReader reader = null;
String link =<i> "example.com/example.php";</i>
try {
url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.connect();
String inputToFile = URLEncoder.encode("mName", "UTF-8") + "=" + URLEncoder.encode("name", "UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(inputToFile);
writer.flush();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
//Here i have add data to string how to display images
//The result of Toast in onpostexecute is
//{"images":[{"image":"http:\/\/example.com\/example.jpg"},{"image":"http:\/\/example.com\/example.jpg"}]}
response += line;
}
//Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//Toast.makeText(context,bmp.toString(),Toast.LENGTH_SHORT).show();
} catch (MalformedURLException e) {
// DonorList.setText("Url Error");
e.printStackTrace();
response = "Exception: " + e.getMessage();
} catch (IOException e) {
// DonorList.setText("Connection could not be opened");
e.printStackTrace();
response += "Exception: " + e.getMessage();
}
return response;
}// DO IN BACKGROUND
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Toast.makeText(context, "Recieved: "+response, Toast.LENGTH_LONG).show();
Use Glide library for loading image in ImageView
Glide.with(context).load(image_url).into(imageView);

Making Attendance App in Android

I have to make attendance app for college.The app will take data from colleges website and display it on app according to user login and password.
When we login into college's website we have to put id and password, same thing I want on my app so that user can see it on an app itself.
I have searched httpurlconnection, httpget, httppost, jsoup.
Up till now, I have understood that I have to make httprequest for loading the college's attendance site and then httppost to post username and password and after that jsoup to grab the data from HTML page.
But I have seen tutorials only to request JSON pages, but how to request for HTML pages?and post login to it?
Here is what I tried and collected data from JSON
private TextView textresponse1;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Get= (Button) findViewById(R.id.httprequest);
textresponse1= (TextView)findViewById(R.id.textresponse);
progressDialog=new ProgressDialog(this);
Get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
progressDialog.setMessage("Collecting Data");
progressDialog.show();
}
public class JSONTask extends AsyncTask<String,String,String >{
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
String line="";
StringBuffer buffer=new StringBuffer();
while ((line = reader.readLine())!=null) {
buffer.append(line);
}
String finaljosn=buffer.toString();
StringBuffer add =new StringBuffer();
JSONObject parentobject=new JSONObject(finaljosn);
JSONArray parentarray=parentobject.getJSONArray("movies");
for(int i=0;i<parentarray.length();i++) {
JSONObject moviename = parentarray.getJSONObject(i);
String finalmovie = moviename.getString("movie");
int finalyear = moviename.getInt("year");
add.append(finalmovie +"- "+finalyear + "\n");
}
return add.toString();
// return finalmovie +" -Rushabh- " +finalyear;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection!=null) {
connection.disconnect();
}
try {
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
textresponse1.setText(result);
}
}
String mLoadURL="http://www.google.com";
public class LoadHtml extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(mLoadURL);
StringBuilder stringBuilder = new StringBuilder();
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.trim().isEmpty()) {
//load html to webview
}
}
}
Call Above AsyncTask using:
LoadHtml loadHtml= new LoadHtml();
load.execute();

Download a large pdf with jsoup

I would like to download a large pdf file with jsoup. I have try to change timeout and maxBodySize but the largest file I could download was about 11MB. I think if there is any way to do something like buffering. Below is my code.
public class Download extends Activity {
static public String nextPage;
static public Response file;
static public Connection.Response res;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle b = new Bundle();
b = getIntent().getExtras();
nextPage = b.getString("key");
new Login().execute();
finish();
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
res = Jsoup.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.execute();
SharedPreferences pref = getSharedPreferences(
MainActivity.PREFS_NAME, MODE_PRIVATE);
String username1 = pref.getString(MainActivity.PREF_USERNAME,
null);
String password1 = pref.getString(MainActivity.PREF_PASSWORD,
null);
file = (Response) Jsoup
.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.maxBodySize(1024*1024*10*2)
.timeout(70000*10)
.cookies(res.cookies()).data("uname", username1)
.data("pass", password1).data("next", nextPage)
.data("submit", "").method(Method.POST).execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
String name = "eclassTest.pdf";
FileOutputStream out;
try {
int len = file.bodyAsBytes().length;
out = new FileOutputStream(new File(PATH + name));
out.write(file.bodyAsBytes(),0,len);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I hope somebody could help me!
I think, it's better to download any binary file via HTTPConnection:
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://example.com/file.pdf");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
Jsoup is for parsing and loading HTML pages, not binary files.

Categories

Resources