Async HttpRequest Timing Out - android

The Problem
I have an AsyncTask task called from an Activity's OnCreate method. This task makes an http request. The HTTP request hangs. Once the "CODE HANGS HERE" code in the code below is executed, I observe in the debugger that the Async threads are perpetually 'running' and never return anything.
The Code
Here's the OnCreate method of the activity:
protected void onCreate(Bundle savedInstanceState) {
asyncRequest.delegate = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_attach);
Button retakeButton = (Button) (findViewById(R.id.retake_button));
retakeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AttachActivity.this, MainActivity.class);
startActivity(intent);
}
});
try {
URL url;
url = new URL("http://btl-cromwell:9000/api/engine/v1/version");
asyncRequest.execute(url);
} catch (Exception e) {
Log.e(logtag, e.toString());
}
}
Note the URL that is passed to he async task should just return JSON containing the version number of the service receiving the request.
The async task (asyncRequest) code is below:
public class AsyncRequest extends AsyncTask<URL, Void, List<String>> {
private String logtag = "AsyncRequestTask";
public AsyncResponse delegate;
List<String> projects = new ArrayList<String>();
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected List<String> doInBackground(URL... urls) {
try {
// Creating & connection Connection with url and required Header.
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET"); //POST or GET
urlConnection.setRequestProperty("User-Agent", "Test");
// CODE HANGS HERE
int responseCode = urlConnection.getResponseCode();
String responseMessage = urlConnection.getResponseMessage();
projects.add(responseMessage);
} catch (Exception e) {
Log.e(logtag, e.toString());
}
return projects;
}
#Override
protected void onPostExecute(List<String> result){
delegate.processFinish(result);
}
}
Once I have the request working I will populate the projects variable with what I actually want to return but for now I just have it set to responseMessage. I'm sure this is just something to do with my unfamiliarity in making requests in Java, but I have spent days on this and can't figure it out. Any help is greatly appreciated.

asyncRequest.execute(url);
asyncRequest.getStatus();
String[] projects = asyncRequest.get();
It is not possible to do both an .execute and a .get().
As you should never use .get(), you better remove that statement.
Remove all code after asyncRequest.execute(url); and put that code in the onPostExecute of your AsyncTask.

Related

Webservice call from Android failing

Very new at Android development. Trying to call a webservice in Android Studio and getting this: java.net.SocketTimeoutException: SSL handshake timed out. I dont see traffic with wireshark and am not sure at what point its failing. Does not seem to leave the emulator.
EDIT: The webservice contains three methods, for lack of better term. I am not sure how to call the proper method in android. In powershell I call like this:
Powershell:
$myname = New-WebServiceProxy -Uri $URI -Namespace myname-class ssl
$myname.webservicemethod($qualifications,0,30)
Android:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button2);
final TextView textview = findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AsyncTask asyncTask = new AsyncTask()
{
#Override
protected Object doInBackground(Object[] objects)
{
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://ip of webservice/pathvalue/WSDL/public/hostname/name").newBuilder();
urlBuilder.addQueryParameter("username", "someuser");
urlBuilder.addQueryParameter("password", "somepass");
urlBuilder.addQueryParameter("qualification", "Assigned Group=Admin Group");
String url = urlBuilder.build().toString();
Request request = new Request.Builder().url(url).build();
Response response = null;
try
{
response = client.newCall(request).execute();
return response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o)
{
textview.setText(o.toString());
}
}.execute();
}
});
}
}
I suspect preventing SocketTimeoutException is beyond our limit. One way to effectively handle it is to define a connection timeout and later handle it by using a try catch block. Hope this will helps
HttpUrlConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7000); //set the timeout in milliseconds

Finish procedure before starting a new one

I am beginner in Android and I need some help. So, I have a procedure with sub-procedures inside. How can I finish one before starting a new one. Here is a code to better understand:
public void onCellLocationChanged(CellLocation lokacija) {
super.onCellLocationChanged(lokacija);
location = (GsmCellLocation) Phone.getCellLocation();
textCellId.setText(String.valueOf(location.getCid() % 65536));
textCellLac.setText(String.valueOf(location.getLac()));
String JSON_URL_string=JSON_URL + "?cellid=" + String.valueOf(location.getCid()%65636);
getJSON(JSON_URL_string);
myJSONString = textCellNameSakriven.getText().toString();
ParseJSON(myJSONString);
}
Problem is that myJSONString is empty, cause textCEllNameSkriven is also empty. That textView textCellNameSkriven is made when getJSON(JSON_URL_string) is finished. If I run debugger and go step by step, app goes directly from getJSON(JSON_URL_string) row to the next one and the next etc
Edit: Maybe the problem is that onPostExecute is not finished before starting ParseJSON. Here is also a code for getJSON:
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textCellNameSakriven.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
Since you are running a async task it practically runs on a different thread, so your getJson method need not wait for post execute and can return after starting the async task, so you can never be sure in this way that parseJson gets executed after textView is populated. You are running into classic race condition issue.
Your issue could be easily solved, if you have a callback which is called after postExecute is done, and you can handle parseJson there
So, something simple like , create interface MyCallback
public interface MyCallback {
public OnReadJsonDone();
}
Let your activity implement this MyCallback
public MainActivity implements MyCallback
{
...........
#Override
public OnReadJsonDone(){
parseJson();
}
Now change signature of getJson to
getJSON(string json, final MyCallback callback) {
Now in onpostexecute
//call OnReadJsonDone
callback.OnReadJsonDone()
So, all you now need is while calling getJSon pass this as second param
getJSON(JSON_URL_string,this);
Haven't tested this but you get the idea

Trouble in calculating the size of URL

I want to know the size of the url in order to download the file but its crashing on runtime. Here is my code:
public class MainActivity extends AppCompatActivity {
TextView t1;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.text1);
try {
URL url = new URL("https://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
i = conection.getContentLength();
}
catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
t1.setText(i + "MB");
}
}
all url task done in background,so use Async Task class for this........
Below code ......look like this
class SignInAsyntask extends AsyncTask<String, String, String> {
String result;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
// doing all url works.................
return result;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.e("Result", response);
}
}
and call it onCreate() method look like tis......
new SignInAsyncTask().execute();
The reason your app crashes is because you're accessing the network on the main thread. You should make the network call on a background thread, using AsyncTask.

Android HTTP GET doesn't work

I know Java but unfortunately chosen Basic4Android for Android Development. After working over an year I realized I should move in native solution. So my question might be silly but I need your advice to solve it.
My goal is to retrieve data from a GET request. I've tried tons of android http client tutorials over internet but failed with each tutorial. I'm just going to share one here so that you can help me to fix. When I'm clicking on the button, nothing is happening without tons of error message in logcat window.
Main Class is here for a quick review:
public class MainActivity extends Activity implements OnClickListener {
private Button Test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Test = (Button) findViewById(R.id.Test);
Test.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.Test){
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.google.com";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
// do something with the response
String response = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And the whole project is here: https://dl.dropboxusercontent.com/u/15625012/TestHttp.zip
I'll really appreciate any sort of help/advice.
you are currently doing a network access in your main UI thread (Button click function). Android does not allow long operations such as network access in the main thread UI thread of the app. You need to do this asynchronously in a separate thread. You can use built in Async Class for this purpose.
Here is a sample code i wrote
public class Sample extends Activity
{
private ProgressDialog progress_dialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
progress_dialog = new ProgressDialog(this);
}
public void MyButtonClick(View view)
{
EditText usernameEditText = (EditText)findViewById(R.id.sample_username);
String username = usernameEditText.getText();
String URL = "http://SOME_WEBSITE?Username=" + username;
progress_dialog.setMessage("Loading. Please wait...");
progress_dialog.setCancelable(false);
progress_dialog.show();
new SampleAsynThread().execute(URL);
}
private class SampleAsynThreadextends AsyncTask <String, Void, String>
{
protected String doInBackground(String... urls)
{
// make your request here
return "Response";
}
protected void onPostExecute(String result)
{
// show response on ui
progress_dialog.dismiss();
}
}
protected void onDestroy()
{
progress_dialog.dismiss();
super.onDestroy();
}
#Override
protected void onPause()
{
progress_dialog.dismiss();
super.onPause();
}
}
First- always post the errors in logcat here, we almost always need them to fix the problem.
But here it's easy- you can't do network IO on the main thread. You need to run it on an AsyncTask or a Thread instead.
try {
URL url = new URL(urlstr);
HttpsURLConnection connection =
(HttpsURLConnection)url.openConnection();
connection.setReadTimeout(6000);
connection.setRequestMethod("GET");
connection.setRequestProperty("User_agent", "android");
OutputStream os = connection.getOutputStream();
//os.write(buffer);
InputStream is = connection.getInputStream();
} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
}

Convert android AsyncTask call to a separate class and call from all activities

I am new to android development. I have a AsyncTask function in my application. Calling http request from all activities. Now in each activity I am using the following class to connect to server, in some activities I even called twice !!.
Basically I am a web developer and in such cases we use a single class which can be accessed from entire application(web) and use the common function to do the same activity. The only difference is input and out put will be changed.
My doubt is in this case can I use ( convert) this to such a function or class ?
My assume is
Create an android class ( which can be accessed from all the activities )
Just make the JSON string we need with specific server ( for process in server )
Just pass the created json to the created class and then made the http connect )
Process the returned data from server
Pass that to the corresponding activity
So that I can use the same function for all the activities and I can avoid duplicate query
Can I convert this code to such a manner ?
My Code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
LogIN loginUser = new LogIN();
LoginUser.execute("");
}
private class LogIN extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
String path = "http://www.domain_name.com/app/checkSession.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("access_token", "123456");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("result");
if(passedStringValue.equals("1")){
flags=1;
//Log.v("TAGG", "Success");
}
else {
flags=0;
//Log.v("TAGG", "Failed !");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialogue("Login Processing", "Loading");
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
if(flags.equals(1)){
Itent homepage = new Intent(MainActivity.this, RegisterDevice.class);
startActivity(homepage);
finish();
}
else {
Intent homepage = new Intent(MainActivity.this, LoginActivity.class);
startActivity(homepage);
finish();
}
super.onPostExecute(result);
}
}
}
Please any one help/advise
Thanks in advance
Extract your class to a different file and make it public
public class LogIN extends AsyncTask<Object, Integer, String> {
private ILoginListener listener;
#Override
protected String doInBackground(Object... arg0) {
try {
this.listener = (ILoginListener) arg0[0];
//You can also send the url in the obj array
String theUrl = (String) arg0[1];
String path = "http://www.domain_name.com/app/checkSession.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("access_token", "123456");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("result");
if(passedStringValue.equals("1")){
flags=1;
//Log.v("TAGG", "Success");
}
else {
flags=0;
//Log.v("TAGG", "Failed !");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialogue("Login Processing", "Loading");
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
listener.logInSessionCheckListener(flag.equals(1));
super.onPostExecute(result);
}
}
Regarding your other question, I normally have an interface for that, something like this:
public interface ILoginListener {
public void logInSessionCheckListener(SomeNeeded Value);
}
I implement the interface in the class where i need the postExecute result and in the overriden method you can to what you want with the result of your task.
Your class where you user it will look something like this:
public class SomeClass implements ILoginListener {
//Call it like this from any class:
LogIN loginTask = new LogIn();
Object[] someParams = new Object[2];
//add the listener
someParams[0] = SomeClass.this
//add the url
someParams[1] = someUrlString;
loginTask.execute(someParams);
#Override
public void logInSessionCheckListener(SomeNeeded Value){
//do Stuff with your results
}
}
You can do it like make separate class for everything inside doInBackground() method and called it in all activity with passing parameter to
LogIN loginUser = new LogIN(yourparameter);
LoginUser.execute("");
and check parameter in AsyncTask Class constructor like
public LogIN(Myparameter){
// Your data
}
On the other hand you can use this great framework for android : android-query and the async API.
It allows you to perform asynchroneous network tasks from activities and easily work with the results of your requests.
You should use interfaces to implement a callback to your ui activity.
Have a look at this thread, it might be useful:
android asynctask sending callbacks to ui
And your asyntask class should be in a seperate java file with public acces.
And to pass the parametres you simply have to call a new LogIN async Task like this:
new LogIN().execute(urls);
Hope it helped :)
Remember that you can never know when AsyncTask is going to finish. So if you're using this to authenticate users and then perform task X, task Y, or task Z,
then maybe it's better to create a Login helper class
public class LoginHelper {
public boolean login(params){
// Authenticate user and return true if successfull
}
}
and then have in your Activity classes
private class X extends AsyncTask {
#Override
protected String doInBackground(String... sUrl) {
...
boolean authenticated = LoginHelper.login(params...);
if(authenticated == true) {
// Perform task X here...
} else {
// Inform the user that the login failed...
}
}
First of all
You have to pass the context in which you are calling your async task
Sample Code
Login loginTask = new Long(getContext());
loginTask.execute();
You class Login should have a constructor that accepts the Context
Sample Code
public class Login extends AsyncTask<String, Integer, String> {
private Context mContext ;
private ProgressDialog pd;
private Handler handler = new Handler { };
public Login (Context context){
mContext = context ;
}
.....
Then make sure to create the method showDialog inside Login class to show the progress dialog
Note
You can add what ever Constructors you need to customize the behaviour of your Login task
for example : pass boolean parameter to tell that the Login Task is cancelable....
Hope that help you :)

Categories

Resources