Google+

Thursday, November 1, 2012

How to Return value from Async task in android

Hi,

After bit R&D, reach on some fatastic solution to get return data from Custom AsyncTask in your activity without using onPostExecute() Method.


Following are the steps to for our Goal.


  • Create your android simple project. 
  • Write "MySampleAsyncTask.java" which extends AsyncTask class. (For example check below class)
MySampleAsyncTask.java

1:  package com.sks.asyncresultback;  
2:  import java.util.Random;  
3:  import android.os.AsyncTask;  
4:  public class MySampleAsyncTask extends AsyncTask<Void, Void, Void> {  
5:       OnAsyncResult onAsyncResult;  
6:       public void setOnResultListener(OnAsyncResult onAsyncResult) {  
7:            if (onAsyncResult != null) {  
8:                 this.onAsyncResult = onAsyncResult;  
9:            }  
10:       }  
11:       @Override  
12:       protected Void doInBackground(Void... params) {  
13:            if (onAsyncResult != null) {  
14:                 // TODO apply your business logic  
15:                 int someNumber = new Random().nextInt(999);  
16:                 if (someNumber % 2 == 0) {  
17:                      onAsyncResult.onResultSuccess(0, "Congratulations\nYou Got Success Value");  
18:                 } else {  
19:                      onAsyncResult.onResultFail(1, "Ohhhhhhhhhhh\n Your Result failed");  
20:                 }  
21:            }  
22:            return null;  
23:       }  
24:       public interface OnAsyncResult {  
25:            public abstract void onResultSuccess(int resultCode, String message);  
26:            public abstract void onResultFail(int resultCode, String errorMessage);  
27:       }  
28:  }  


Look into class

At the bottom of code created a new Interface to code.

public interface OnAsyncResult {  
            public abstract void onResultSuccess(int resultCode, String message);  
            public abstract void onResultFail(int resultCode, String errorMessage);  
       }

You are free to use this listener. Here I didn't use onPostExecute() Method. so you can use your business logic as per your way.



  • Now lets Create your "MainActivity.java" from which we are calling our MySampleAsyncTask for our purpose.

1:  public class MainActivity extends Activity {  
2:       public TextView textView;  
3:       MySampleAsyncTask asyncTask;  
4:       @Override  
5:       public void onCreate(Bundle savedInstanceState) {  
6:            super.onCreate(savedInstanceState);  
7:            setContentView(R.layout.activity_main);  
8:            textView = (TextView) findViewById(R.id.tv_Result);  
9:            findViewById(R.id.btn_clickMe).setOnClickListener(new OnClickListener() {  
10:                 @Override  
11:                 public void onClick(View v) {  
12:                      asyncTask = new MySampleAsyncTask();  
13:                      asyncTask.setOnResultListener(asynResult);  
14:                      asyncTask.execute();  
15:                 }  
16:            });  
17:       }  
18:       OnAsyncResult asynResult = new OnAsyncResult() {  
19:            @Override  
20:            public void onResultSuccess(final int resultCode, final String message) {  
21:                 // need to add this part in ui thread.  
22:                 // as you will then thread exception.  
23:                 runOnUiThread(new Runnable() {  
24:                      public void run() {  
25:                           textView.setText("Code : " + resultCode + "\nMessage : " + message);  
26:                      }  
27:                 });  
28:            }  
29:            @Override  
30:            public void onResultFail(final int resultCode, final String errorMessage) {  
31:                 // need to add this part in ui thread.  
32:                 // as you will then thread exception.  
33:                 runOnUiThread(new Runnable() {  
34:                      public void run() {  
35:                           textView.setText("Code : " + resultCode + "\nMessage : " + errorMessage);  
36:                      }  
37:                 });  
38:            }  
39:       };  

at the last block we have create instance of OnAsynkResult listener and set to our MySampleAsyncTask object on Button Click.


18:      OnAsyncResult asynResult = new OnAsyncResult() {  
19:            @Override  
20:            public void onResultSuccess(final int resultCode, final String message) {  
21:                 // need to add this part in ui thread.  
22:                 // as you will then thread exception.  
23:                 runOnUiThread(new Runnable() {  
24:                      public void run() {  
25:                           textView.setText("Code : " + resultCode + "\nMessage : " + message);  
26:                      }  
27:                 });  
28:            }  
29:            @Override  
30:            public void onResultFail(final int resultCode, final String errorMessage) {  
31:                 // need to add this part in ui thread.  
32:                 // as you will then thread exception.  
33:                 runOnUiThread(new Runnable() {  
34:                      public void run() {  
35:                           textView.setText("Code : " + resultCode + "\nMessage : " + errorMessage);  
36:                      }  
37:                 });  
38:            }  
39:       };



on each method, if you want to set values to view then you have to use runOnUiThread methods.
as this listeners are already calling from thread.




Download Source Code

Check our Source code 

svn checkout 
http://smartphone-app-by-sachin-shelke.googlecode.com/svn/trunk/


Comments are always welcome.




Monday, September 10, 2012

How to find Screen Size and Density of Device in Android programatically

Hi add this below code in on Create method and check your device or emulator screen configuration.




if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
Toast.makeText(Util.mContext, "Large Screen", Toast.LENGTH_SHORT).show();
Util.v("Screen Size : Large ");

} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Toast.makeText(Util.mContext, "X Large Screen", Toast.LENGTH_SHORT).show();
Util.v("Screen Size : X Large ");

} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Toast.makeText(Util.mContext, "Normal Screen", Toast.LENGTH_SHORT).show();
Util.v("Screen Size : Normal ");

}



//Determine density
   DisplayMetrics metrics = new DisplayMetrics();
       getWindowManager().getDefaultDisplay().getMetrics(metrics);
       int density = metrics.densityDpi;

       if (density==DisplayMetrics.DENSITY_HIGH) {
           Toast.makeText(this, "DENSITY_HIGH... Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
           Util.v("DENSITY_HIGH... Density is " + String.valueOf(density));
       }
       else if (density==DisplayMetrics.DENSITY_MEDIUM) {
           Toast.makeText(this, "DENSITY_MEDIUM... Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
           Util.v("DENSITY_MEDIUM... Density is " + String.valueOf(density));
       }
       else if (density==DisplayMetrics.DENSITY_LOW) {
           Toast.makeText(this, "DENSITY_LOW... Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
           Util.v("DENSITY_LOW... Density is " + String.valueOf(density));
       }
       else {
           Toast.makeText(this, "Density is neither HIGH, MEDIUM OR LOW.  Density is " + String.valueOf(density),  Toast.LENGTH_LONG).show();
           Util.v("Density is neither HIGH, MEDIUM OR LOW... Density is " + String.valueOf(density));
       }

Monday, July 16, 2012

How to resolve Conversion to Dalvik format failed with error 1


Many times we faced problem of "Conversion to Dalvik format failed with error 1"


When i went through Google and found many solutions but below has solved my problem.



  1. In Eclipse Package Explorer, Right Click on Project -> Select Properties -> Select "Java Build Path" -> and remove all the JARs from library. Then click OK. Project will show you an error.
  2. Then as usual your try fix project property and clean project.
  3. Then again follow the above 1st steps to add your JARs.
  4. Now follow again 2nd step to clear and clean your project.
Hurreeee,
Your problem has been resolve. Run Project and enjoy Coding



Google+