Showing posts with label AsyncTask. Show all posts
Showing posts with label AsyncTask. Show all posts
This is the second version my only app in the Google Play Store that is somehow not down in the abbess. A recent comment made me realize that certain functionality in the previous version do not work on the newer Android devices. It was because the newer devices do not allow the main thread to do the background task (which is a great restriction. Kudos Android). In my case, the background task was to connect to Random.org to extract random numbers. So, I had to jettison the previous code and re-implement it using AsyncTask.

Screenshots:








Code for DIY part

package com.randomayush;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class diy extends MainActivity {
    EditText min, max;
    Button submit;
    TextView box, status;
    String minimum, maximum;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diy);

        min = (EditText) findViewById(R.id.editText1);
        max = (EditText) findViewById(R.id.editText2);
        submit = (Button) findViewById(R.id.button1);
        box = (TextView) findViewById(R.id.textView3);
        status = (TextView) findViewById(R.id.textView5);

        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                InputMethodManager mgr = (InputMethodManager
                  getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.hideSoftInputFromWindow(min.getWindowToken(), 0);

                minimum = min.getText().toString() + "";
                maximum = max.getText().toString() + "";
                if (minimum == "" || maximum == "") {
                    box.setText("");
                    status.setText("Result: Invalid Input. Missing Data...");
                } else if (Integer.parseInt(maximum) <= 
                                            Integer.parseInt(minimum)) {
                    box.setText("");
                    status.setText
                      ("Result: Invalid Input. Check Max/Min Values ..");
                } else {
                    new MyTask().execute();
                }
            }
        });

    }

    private class MyTask extends AsyncTask<String, String, String> {
        String statusMsg = "";

        @Override
        protected String doInBackground(String... params) {
            statusMsg = "Status: Checking connection...";
            publishProgress(statusMsg);
            if (haveNetworkConnection()) {
                statusMsg = "Status: network available... connecting now...";
                publishProgress(statusMsg);
                try {
                    statusMsg = "Status: Connecting to RANDOM.org...";
                    publishProgress(statusMsg);
                    return dome(minimum, maximum);
                } catch (Exception e) {
                    statusMsg = "Status: Connection failed...";
                    publishProgress(statusMsg);
                    return ("");
                }
            }
            statusMsg = "Status: Connection failed...";
            publishProgress(statusMsg);
            return "";

        }

        @Override
        protected void onPostExecute(String result) {

            if (result.equals("")) {
                status.setText("DIY Random-Type: Pseudo");
                box.setText("" + (Integer.parseInt(minimum) + 
                (int) (Math.random() * (Integer.parseInt(maximum) - 
                 Integer.parseInt(minimum)) + .5)));
            }

            else {
                status.setText("DIY Random-Type: Real");
                box.setText(result);
            }

        }

        @Override
        protected void onPreExecute() {
            status.setText("");
        }

        @Override
        protected void onProgressUpdate(String... text) {
            status.setText(statusMsg);
        }

    }

    public boolean haveNetworkConnection() {
        ConnectivityManager cm = (ConnectivityManager
              getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null && 
           cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }

    public String dome(String min, String max) throws Exception {
        String sendto = "http://www.random.org/integers/?num=1&min=" + 
         min + "&max=" + max + "&col=1&base=10&format=plain&rnd=new";
        URL url = new URL(sendto);
        BufferedReader in = new BufferedReader
         (new InputStreamReader(url.openStream()));
        return (in.readLine());
    }
}


If someone approached me a couple of months ago and claimed that I would soon be relishing the new dimension of vocabulary enhancement, I would have undoubtedly replied that there was a zero probability of it happening. I could not be more incorrect.
Perhaps, the thought of mugging up some five thousand words sounded very tedious. But, once I set the ball rolling, I realized that the words have certain salient patterns to them. That meant, I need not learn their definitions, but instead, scrupulously explore for those patterns.

The purpose behind writing this app was to study the etymology of words.

The source: http://www.etymonline.com/







I also decided to add a TextView that reports the request status from AsyncTask's onProgressUpdate method.




The pith of the program:

1
2
3
4
5
doc = Jsoup.connect("http://www.etymonline.com/index.php?allowed_in_frame=0&search=" + request + "&searchmode=term").get();
Elements info = doc.select("div#dictionary");    
String html = info.toString();
doc = Jsoup.parse(html);
result = doc.body().text();

Getting rid of the keyboard once Submit button is pressed:


1
2
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);

This project is very similar to one of my previous projects. Click here.