HttpUrlConnection not working on Galaxy S3 - android

Im making an app that requires the HttpURLConnection. I tested it on the emulator and on my
Optimus S version 2.3.3 but when i test it on my Galaxy S3 version 4.1.2 it automatically fails. The LogCat doesn't show any errors. So im wondering why it fails on the Galaxy S3.
Http Setup
System.setProperty("http.keepAlive", "false");
URL check_url = new URL("http://www.website.com");
HttpURLConnection http = (HttpURLConnection) check_url.openConnection();
http.setConnectTimeout(3000);
http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
http.setRequestMethod("GET");
http.connect();

Some Android version (I don't known) need an AsyncTask to make HTTP connection, so you must to put your code in a background thread like that.
public void makeSingUp(){
new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... params){
//Your code connection
return true;
}
#Override
public void onPostExecute(Boolean result){
//Some message that indicates the connection was finished, or nothing.
}
}.execute();
}

download volley lib and add in your project. tutorial [link]: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
public class send_data extends AsyncTask {
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(main.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle("please wait...");
mProgressDialog.show();
}
protected String doInBackground(String... args) {
String url = "http://your_url";
try {
ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>(
1);
nvp.add(new BasicNameValuePair("key for your data","yourdata"));
String str_responsebody = obj_service.executer(url, nvp);
Log.i("responce", str_responsebody + "===");
return str_responsebody;
} catch (Exception e) {
Log.i("error1", "" + e.toString());
return null;
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i("result", result);
mProgressDialog.dismiss();
}
} catch (Exception e) {
Log.e("error2", "" + e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
}
}
}

Related

android connect to nodejs

I have pc running node in the same wifi with development phone(i dont use virtual device).
I test nodejs server with firefox extension rested and works fine(same pc with server)
I try to post from my android app a simple json. No error thrown but no seems to work(I have a console.log() on server's .post which not shown). I have also open 8080 port. here is my android code
public void sendJson(View view) {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://192.168.1.5:8080/api");
URLConnection urlConn;
DataInputStream input;
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", "kalosto");
// Send POST output.
OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream ());
printout.write(jsonParam.toString());
printout.flush ();
printout.close ();
} catch (Exception e) {
e.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
I change the request from post to get, from my phone browser i can access the server and the console.log be triggered but app still do nothing

POST request from real android device

I working on android application which post its location to server. Here's one problem.
When I run this application in genymotion, it succesfully send POST requests to server. However, when I installed on samsung galaxy note, it doesn't send these post requests.
Where can be the problem?
EDIT: I successfully can fetch data from internet by GET request
Code:
class Posting extends AsyncTask<Location, String, String>{
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(Location... locations){
RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(RetrofitClient.API_URL2).build();
RetrofitClient.TestRetro retrofit = restAdapter.create(RetrofitClient.TestRetro.class);
IssdDeviceLog body=new IssdDeviceLog();
body.setDeviceNo("hello from SAMSUNG MAIN ACTIVITY service");
body.setLatitude(new BigDecimal(locations[0].getLatitude()));
body.setLongtitude(new BigDecimal(locations[0].getLongitude()));
Date date= new Date();
body.setDate(date.toString());
Gson gson = new Gson();
String json = gson.toJson(body);
Response response=retrofit.sendLocation(json);
Log.d("status code"," "+response.getStatus());
return null;
}
#Override
protected void onPostExecute(String file_url) {
}
}
With regards
can you put your error if you getting any error or you can use volley library i am sharing this code you can use this for your post request
public class send_data extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(main.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle("please wait...");
mProgressDialog.show();
}
protected String doInBackground(String... args) {
String url = "http://your_url";
try {
ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>(
1);
nvp.add(new BasicNameValuePair("key for your data","yourdata"));
String str_responsebody = obj_service.executer(url, nvp);
Log.i("responce", str_responsebody + "===");
return str_responsebody;
} catch (Exception e) {
Log.i("error1", "" + e.toString());
return null;
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i("result", result);
mProgressDialog.dismiss();
}
} catch (Exception e) {
Log.e("error2", "" + e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
}
}
}
download volley lib and add in your project. tutorial [link]: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

ProcessDialog is not appearing properly?

This is my function that is in LoginActivity.java.So onclick of button i am calling this function.
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
AppResponse = reqClient.execute().get();
String status = ValidateLoginStatus.checkLoginStatus(AppResponse);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
From this function i am calling a AsynkTask for Http Communication.So onclick of button when i am geeting the response then my processDialog in opening just for one sec.I want as i click the buttoon my processDialog should get open utill i got the response
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
DefaultHttpClient httpClient=new DefaultHttpClient();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginActivity.url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(pDialog!=null)
pDialog.dismiss();
}
}
So please suggest me what changes i have to make so that processDialog should display properly in the center of the device
//add style in your progressbialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Authenticating user...");
if (pDialog != null && !pDialog.isShowing()) {
pDialog.show();
}
}
AsyncTask return value only after using get() method
Drawing from the above link
Calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.
The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.
On Button click
RequestClient reqClient = new RequestClient(LoginActivity.this,new TheInterface() {
#Override
public void theMethod(String result) {
Log.i("Result =",result);
}
});
reqClient.execute(url); // no get(). pass url to doInBackground()
In your activity class
public interface TheInterface {
public void theMethod(String result);
}
}
AsyncTask
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
TheInterface listener;
public RequestClient(Context c,TheInterface listen) {
context = c;
listener = listen;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]); // url
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pDialog.dismiss();
if (listener != null)
{
listener.theMethod(result);
}
}
}
It seems that your button code is not correct, because it's async, but you are trying to use it as standart sync code.
Try to move this code into onPostExecute:
String status = ValidateLoginStatus.checkLoginStatus(response);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
and make this button click code:
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
reqClient.execute();
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}

how to a set progress bar till get a data from server using json? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Android AsyncTask Progress bar
Am using login process,during tat time am getting the data from server is delay.so i want set a progress bar for tat delay.how to set progress bar till get a response from server.any know the answer please help me.
private class LongOperation extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
progressDialog = new ProgressDialog(activity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(String... params)
{
try
{
//Getting data from server
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
Intent n = new Intent(firstactivity.this, secondactivity.class);
startActivity(n);
}
}
How to call this
ProgressDialog progressDialog;
LongOperation mytask = null;
mytask = new LongOperation();
mytask.execute();
Use AsyncTask in your code and put your code in doInBackground(....) process.
Show your progress dialog in onPreExecute and dismiss it in onPostExecute(...) .
Add an infinite progressbar view to your layout and make it invisible first.
Create an AyncTask to do the server communication.
In onPreExecute() make the progressbar visible.
In onPostExecute() hide the progressbar again.
You can use the onProcessupdate method of an AsyncTask
private class GetLogin extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show("Downloading...");
}
#Override
protected String doInBackground(String... params) {
for (String myUrl : params) {
try {
URL url = new URL(myUrl);
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
//error
} catch (IOException e) {
//error
}
}
return "All Done!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setMessage("Downloading... (" + values[0] + "%)");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}

Android httpurlconnection and basicauthentication

I'm having a really tough nut to crack with a bug. Api being used is v11, honeycomb 3.0
I have a asynctask inside a fragment downloading from a XML api with basic authentication. It works perfectly even when i change the parameters from the fragment within with the edittexts etc. But when i try to mutate a autocompletetextview from outside the fragment, suddenly i get a "no element at line 1. column 0" exception. I tried the androidhttpclient, fiddled with systemprop(http.keepalive), and completly narrowed it down to this method.
public void setStations(String a, String b){
AutoCompleteTextView fromET = (AutoCompleteTextView ) getView().findViewById(R.id.from);
fromET.setText(a);
AutoCompleteTextView toET = (AutoCompleteTextView) getView().findViewById(R.id.to);
toET.setText(b);
}
When this method executes it botches up my downloadtask somewhere. If i manually edit these textview it works fine.
class LoadDataTask extends AsyncTask<String, Integer, ArrayList<Reisadvies>> {
private Exception ex;
private ProgressDialog pd;
protected void onPreExecute() {
//loadprogressdialog
}
protected ArrayList<Reisadvies> doInBackground(String... params) {
try{
ex = null;
return new APIreader().getRA(params[0], params[1], params[2],params[3],params[4],params[5], params[6]);
}catch (Exception e){
cancel(true);
pd.dismiss();
ex = e;
return null;
}
}
protected void onPostExecute(ArrayList<Reisadvies> ra){
//send list to activity
}
protected void onCancelled() {
super.onCancelled();
showError(ex);
}
}
};
public ArrayList<Reisadvies> getRA(String fromStation, String toStation, String viaStation, String dateTime, String departure, String hslAllowed, String yearCard) throws APIException{
try{
String uri = url(fromStation, toStation, viaStation, dateTime, departure, hslAllowed,yearCard);
URL url = new URL(uri);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if (!url.getHost().equals(uc.getURL().getHost())) {
throw new APIException("HotspotForwadingActive");
}
String basicAuth = "Basic " + "username:password"; //base64 encoded
uc.setRequestProperty ("Authorization", basicAuth);
uc.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
try{
return (ArrayList<Reisadvies>) new XMLParser().parseRP(in);
}finally{
uc.connect();
}
}catch (Exception e){
e.printStackTrace();
throw new APIException(e.getMessage());
}
}
I think there is a problem in doInBackground:
pd.dismiss();
You can do operations on UI element only in UI Thread. It means that you can do this in onPostExecute method, or, if you want, you can use runOnUiThread method:
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
I hope this is helpful...
You are right about that too, but the problem was different. Just found out that it was to urlencoding. Should have figured that out right away but was throw off by the fact that it worked sometimes with a space in it :)

Categories

Resources