Monday, June 24, 2013

Standard Android Utilities (for beginers)

Dialob Box Ceation:
   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
   alertDialogBuilder.setTitle("Your Title");
   alertDialogBuilder.setMessage("Click yes to exit!").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
     longToast("Loading...");
    }
   }).setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
     dialog.cancel();
    }
   });

   AlertDialog alertDialog = alertDialogBuilder.create();
   alertDialog.show();
--------------------------------------------------------------------------------

HTTP URL Connection (4.x, there is a new way making http connections): Create this inner class directly within the activity code, there is something different with the thread programming if you move it outside. We will findout what it is.
 private class GetXMLTask extends AsyncTask {
  @Override
  protected String doInBackground(String... urls) {
   String output = null;
   for (String url : urls) {
    output = getOutputFromUrl(url);
   }
   Log.d("AVIK - Output: ", output);
   return output;
  }

  private String getOutputFromUrl(String url) {
   StringBuffer output = new StringBuffer("");
   try {
    InputStream stream = getHttpConnection(url);
    BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
    String s = "";
    while ((s = buffer.readLine()) != null)
     output.append(s);
   } catch (IOException e1) {
    e1.printStackTrace();
   }
   return output.toString();
  }

  // Makes HttpURLConnection and returns InputStream
  private InputStream getHttpConnection(String urlString) throws IOException {
   InputStream stream = null;
   URL url = new URL(urlString);
   URLConnection connection = url.openConnection();

   try {
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    httpConnection.setRequestMethod("GET");
    httpConnection.connect();

    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
     stream = httpConnection.getInputStream();
    }
   } catch (Exception ex) {
    ex.printStackTrace();
   }
   return stream;
  }

  @Override
  protected void onPostExecute(String output) {
   searchEditText.setText(output);
  }

  @Override
  protected void onPreExecute() {
   Log.i("AVIK : PreExecute : ", "onPreExecute");
  }
 }