Wednesday, April 29, 2015

Simple parse JSON from URL on Android

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following

Async task has three primary methods:
  1. onPreExecute() - most commonly used for setting up and starting a progress dialog
  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).
  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, than run the onPreExecute() method setting up a simple progress dialog.
class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }
Than we need to set up the connection and how we want to handle the response:
    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)
Lastly, here we will parse the return, in this example it was a JSON Array and than dismiss the dialog:
    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

Tuesday, April 28, 2015

Global Variable Or Application Context Variable


 Global_application_context_project_sketch


Global_variable_workflow

In this example defining variable in application context and you can use this variable as a Global variable. You can set value in this variable and get value on any activity / broadcast recieiver / service in application context(environment).
The problem is how to save value across several Activities and all parts of your application context. You can achieve this by creating static variable but it is not the good way it influencing towards memory leaks. The way in Android is to associate your variable with the Application context.

Every Application has a context, and Android guarantees that Application context will exist as a instance across your application.

The way to do this is to create a class and extends with android.app.Application, and specify your class in the application tag in your AndroidManifest.xml file. Android will create an instance of that class and make it available for your entire application context. You can get object of your class on any activity / broadcast reciever / service in application context(environment) by Context.getApplicationContext() method.









 

File : src/GlobalClass.java


Create your custom class subclass of android.app.Application class. you will use this class as global class for your Application environment(Conext).

package com.androidexample.globalvariable;
 
import android.app.Application;
 
public class GlobalClass extends Application{
     
    private String name;
    private String email;
     
 
    public String getName() {
         
        return name;
    }
     
    public void setName(String aName) {
        
       name = aName;
         
    }
    
    public String getEmail() {
         
        return email;
    }
     
    public void setEmail(String aEmail) {
        
      email = aEmail;
    }
 
}

File : AndroidManifest.xml


Assign GlobalClass.java in application tag, see this line in application tagandroid:name="com.androidexample.globalvariable.GlobalClass"
After assign you can get GlobalClass.java instance on any activity / broadcast reciever / service in application context.

<?xml version="1.0" encoding="utf-8"?>
    package="com.androidexample.globalvariable"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="9" />
 
    <application
        android:name="com.androidexample.globalvariable.GlobalClass"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidexample.globalvariable.FirstScreen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
             
        </activity>
         
        <activity android:name=".SecondScreen" ></activity> 
        <activity android:name=".ThirdScreen" ></activity>
    </application>
 
</manifest>

File : src/FirstScreen.java


getApplicationContext() method of Context will give GlobalClass.java instance and set name/email values and maintain state of GlobalClass.java instance.

package com.androidexample.globalvariable;
 
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
 
public class FirstScreen extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstscreen);
         
        final Button secondBtn = (Button) findViewById(R.id.second);
         
        // Calling Application class (see application tag in AndroidManifest.xml)
        final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
         
        //Set name and email in global/application context
        globalVariable.setName("Android Example context variable");
        globalVariable.setEmail("xxxxxx@aaaa.com");
         
         
        secondBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                 
                Intent i = new Intent(getBaseContext(), SecondScreen.class);
                startActivity(i);
            }
        });
    }  
}

File : src/SecondScreen.java


Call getApplicationContext() method of Context and get GlobalClass.java instance , By GlobalClass.java instance you can get set values for name/email variables.

package com.androidexample.globalvariable;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
 
public class SecondScreen extends Activity {
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondscreen);
     
        TextView showGlobal     = (TextView) findViewById(R.id.showGlobal);
        final Button thirdBtn = (Button) findViewById(R.id.third);
         
        // Calling Application class (see application tag in AndroidManifest.xml)
        final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
         
        // Get name and email from global/application context
        final String name  = globalVariable.getName();
        final String email = globalVariable.getEmail();
         
        String showString = "
 
Name : "+name+"
"+
                            "Email : "+email+"
 
";
         
        // Show name/email values in TextView
        showGlobal.setText(showString);
         
        thirdBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                 
                Intent i = new Intent(getBaseContext(), ThirdScreen.class);
                startActivity(i);
            }
        });
         
    }
     
    @Override
    protected void onDestroy() {
         
        super.onDestroy();
         
    }
}

File : src/ThirdScreen.java


Call getApplicationContext() method of Context and get GlobalClass.java instance , By GlobalClass.java instance you can get set values for name/email variables.

package com.androidexample.globalvariable;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
 
public class ThirdScreen extends Activity {
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thirdscreen);
     
        TextView showGlobal     = (TextView) findViewById(R.id.showGlobal);
         
        // Calling Application class (see application tag in AndroidManifest.xml)
        final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
         
        // Get name and email from global/application context
        final String name  = globalVariable.getName();
        final String email = globalVariable.getEmail();
         
        String showString = "
 
Name : "+name+"
"+
        "Email : "+email+"
 
";
         
        // Show name/email values in TextView
        showGlobal.setText(showString);
         
    }
}