0

Hi I am trying check if a username is available but has to go through an async task to check. tried a few ways but wasn't able to do it. So, I came with this:

async task is in a normal class, so will call a new instance, call the async task (checkusername), then wait for async task to finish (on postexecute, it will update a public variable, 'resultOut'). while at the activity, to prevent from locking, loop to 1000 OR resultOut before it exits.

I keep getting 'resultOut' as false. Here's the code:

urlConnection url = new urlConnection(); if(url.isConnected(view.getContext())) { Toast.makeText(getApplicationContext(), "connected ", Toast.LENGTH_LONG).show(); boolean result=false; url.checkUserName(user_name); int i = 0; while (!result && i!=1000){ i++; result=url.resultOut; } 

Here is the urlconnection class (edited)

private void connectUrl(String action, String user_name, String pwd) { String urlParam = null; strAction=action; switch (action){ case "update": urlParam = "/test.php?action=update&user_id=7&lat="+latitude+"&lon="+longitude; break; case "locate": urlParam = "/test.php?action=locate&user_id=7"; break; case "insert": urlParam = "/test.php?action=insert&user_name="+user_name+"&pwd="+pwd; break; case "check": urlParam = "/test.php?action=check&user_name="+user_name; } //Toast.makeText(, "Connecting to site: " + WB_URL + urlParam, Toast.LENGTH_LONG).show(); new DownloadWebpageTask().execute(WB_URL + urlParam); } private class DownloadWebpageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { // params comes from the execute() call: params[0] is the url. try { return downloadUrl(urls[0]); } catch (IOException e) { return "Unable to retrieve web page. URL may be invalid."; } } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { result=result.trim(); switch (strAction){ case "update": int i = Integer.parseInt(result); if (i > 0) { //Toast.makeText(getApplicationContext(), "Update successful", Toast.LENGTH_LONG).show(); }else{ //Toast.makeText(getApplicationContext(), "Update failed", Toast.LENGTH_LONG).show(); } break; case "locate": String[] s = result.split(","); case "insert": break; case "check": int x = Integer.parseInt(result); resultOut=true; //Toast.makeText(getApplicationContext(), "Check Result: "+x, Toast.LENGTH_LONG).show(); if (x==0){ //cannot locate name so, name usable isUserNameUsed=false; }else{ isUserNameUsed=true; } } //showLocation(null); } } private String downloadUrl(String myurl) throws IOException { InputStream is = null; // Only display the first 500 characters of the retrieved // web page content. int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); Log.d(DEBUG_TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } } public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); } 

}

Help appreciated, thank you in advance. Richard

4
  • use interface callback for getting response when you get response from api. Commented May 18, 2016 at 3:40
  • thanks for replying, i read about the interface thing but not sure how to implement it, how to callback? Tried to call the downloadurl directly but application crashed. Commented May 18, 2016 at 5:50
  • it will take time to make whole code and implemetation for that. wait till i make. Commented May 18, 2016 at 6:25
  • Tried to call the downloadurl directly but application crashed don't call network related operation in main thread Commented May 18, 2016 at 6:48

1 Answer 1

0

your utility asyncTask class which you have interface you have to implement it in your fragment or in activity. apiKey is used to check onResponse of which api have you called.

public class UtilityAsyncRequest extends AsyncTask<String, Integer, String> { private final OnAsyncRequestComplete caller; private String requestType = ""; private String strJsonData = ""; private int apiKey = 0; /** * @param caller callback interface for request * @param requestType GET POST * @param jsonStringData payload with request type POST * @param apiKey apiKey */ public UtilityAsyncRequest(OnAsyncRequestComplete caller, String requestType, String jsonStringData, int apiKey) { this.caller = caller; this.apiKey = apiKey; if (requestType.equalsIgnoreCase("Get")) { this.requestType = "Get"; } else if (jsonStringData != null && requestType.equalsIgnoreCase("Post")) { this.requestType = "Post"; this.strJsonData = jsonStringData; } } public String doInBackground(String... urls) { // callApi url pointing to entry point of API String address = urls[0]; String response = ""; if (requestType.equalsIgnoreCase("Post")) { response = Connection.postAPIResponse(address, strJsonData); } else if (requestType.equalsIgnoreCase("Get")) { response = Connection.getAPIResponse(address); } return response; } public void onPreExecute() { if(caller!=null) caller.onPreExecute(apiKey); } public void onPostExecute(String response) { if (caller != null) caller.onPostExecute(response, apiKey); } protected void onCancelled(String response) { if(caller!=null) caller.onCancelled(apiKey); } // Interface to be implemented by calling activity public interface OnAsyncRequestComplete { void onPreExecute(int api); void onPostExecute(String response, int api); void onCancelled(int api); } } 

now to make async Request you can do like this in your activity. by implementing interface.

public class MainActivity extends Activity implements UtilityAsyncRequest.OnAsyncRequestComplete{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //first Api Call UtilityAsyncRequest utilityAsyncRequest=new UtilityAsyncRequest(this,"GET",null,1); utilityAsyncRequest.execute("https://www.google.co.in/?gws_rd=ssl"); //Second Api Call utilityAsyncRequest=new UtilityAsyncRequest(this,"GET",null,2); utilityAsyncRequest.execute("https://www.google.co.in/?gws_rd=ssl"); } @Override public void onPreExecute(int api) { switch (api){ case 1: //first api call pre show Loading dialog else whatever you want break; case 2: //second api call pre break; } } @Override public void onPostExecute(String response, int api) { switch (api){ case 1: //first api call response break; case 2: //second api call response break; } } @Override public void onCancelled(int api) { } } 

for handling receiving and posting data.

public class Connection { // Private constructor prevents instantiation from other classes private Connection() { } public static String postAPIResponse(String url, String data) { HttpURLConnection con = null; InputStream inputStream; StringBuffer responses = null; try { URL urlObject = new URL(url); con = (HttpURLConnection) (urlObject.openConnection()); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestProperty("Content-Length", Integer.toString(data.getBytes().length)); con.setRequestProperty("Content-Language", "en-US"); if (Cookie.getCookie() != null) con.addRequestProperty("Cookie", Cookie.getCookie()); con.setUseCaches(false); con.setDoInput(true); con.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); //Get Response if (con.getResponseCode() == 200) { if (Cookie.getCookie() == null) Cookie.setCookie(con.getHeaderField("Set-Cookie")); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; responses = new StringBuffer(); while ((line = rd.readLine()) != null) { responses.append(line); } rd.close(); } else { inputStream = new BufferedInputStream(con.getErrorStream()); return convertInputStreamToString(inputStream); } } catch (Exception e) { e.printStackTrace(); } finally { assert con != null; con.disconnect(); } return responses != null ? responses.toString() : ""; } public static String getAPIResponse(String urlName) { String response = null; HttpURLConnection con = null; InputStream inputStream; try { URL url = new URL(urlName); con = (HttpURLConnection) (url.openConnection()); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (Cookie.getCookie() != null) con.addRequestProperty("Cookie", Cookie.getCookie()); int statusCode = con.getResponseCode(); if (statusCode == 200) { inputStream = new BufferedInputStream(con.getInputStream()); response = convertInputStreamToString(inputStream); if (Cookie.getCookie() == null) Cookie.setCookie(con.getHeaderField("Set-Cookie")); } else { inputStream = new BufferedInputStream(con.getErrorStream()); response = convertInputStreamToString(inputStream); } } catch (Exception e) { e.printStackTrace(); } finally { assert con != null; con.disconnect(); } return response != null ? response : ""; } static public String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; String result = ""; while ((line = bufferedReader.readLine()) != null) { result += line; } /* Close Stream */ inputStream.close(); return result; } } 

and to handle cookie model class.

public class Cookie { private static String Cookie; //private static final com.core.Cookie singleton = new Cookie( ); /* A private Constructor prevents any other * class from instantiating. */ private Cookie() { } /* Other methods protected by singleton */ public static String getCookie() { return Cookie; } public static void setCookie(String cookie) { Cookie = cookie; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

is it helpful for you ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.