Tuesday, October 25, 2016

Convert Layout View to Image and Store in Storage (Android)

This code able to convert the whole view in scrollview to images. It been tested and successfully working.



 

First image is from the mobile, after click the "save and print receipt" it will save the whole view and stored in image gallery. Second image is the result



Change Snippet Background Color
 
        

@BindView(R.id.native_resit)
protected ScrollView native_resit;


@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ....
        ....

        close_btn.setOnClickListener(new resitClickListener());
        print_resit.setOnClickListener(new resitClickListener());

        runRecieptData();
}

private class resitClickListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.close_btn){
                getFragmentManager().popBackStack();
            }
            else if (view.getId() == R.id.print_resit){
                print();
            }
        }
}

private void print(){
        ProgressDialog dialog = new ProgressDialog(getActivity());
        dialog.setMessage("Saving...");
        dialog.show();

        Bitmap bitmap = getBitmapFromView(native_resit,native_resit.getChildAt(0).getHeight(),native_resit.getChildAt(0).getWidth());
        try {
            File defaultFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Your_Folder");
            if (!defaultFile.exists())
                defaultFile.mkdirs();

            String filename = "Order ID "+orderHistoryResponse.getOrderId()+".jpg";
            File file = new File(defaultFile,filename);
            if (file.exists()) {
                file.delete();
                file = new File(defaultFile,filename);
            }

            FileOutputStream output = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
            output.flush();
            output.close();

            dialog.dismiss();

            Toast.makeText(getActivity(), Message.RECEIPT_SAVE, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            dialog.dismiss();
            Toast.makeText(getActivity(), Message.RECEIPT_SAVE_FAILED, Toast.LENGTH_SHORT).show();
        }
    }

    //create bitmap from the view
    private Bitmap getBitmapFromView(View view,int height,int width) {
        Bitmap bitmap = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null)
            bgDrawable.draw(canvas);
        else
            canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        return bitmap;
    } 

 

Wednesday, October 12, 2016

Android Viewpager Wait Fragment Finish Load

After several attempt on how to wait all the fragment in view pager is loaded, i came out a solution where i create interface class to communicate between activity and the fragment..
  1. Create Interface Class
  2. Implement it on Activity class
  3. Call it from each fragment at the off each process

Change Snippet Background Color



Create Interface as bridge between fragment and activity

public interface OnFragmentFinishLoad {
    public void onFinish(String tag,boolean state);
}
 

Now Create Activity Class contain Viewpager.. (Code not complete)

public class PizzaActivity extends BaseActivity implements OnFragmentFinishLoad {

   @BindView(R.id.cover_rl)
 
   protected RelativeLayout cover_rl;

   int countLoad = 0;

   @Override
 public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_carte_tab_layout);
      cover_rl.setVisibility(View.VISIBLE);


      setupViewPager(viewPager);

      mTabLayout.setupWithViewPager(viewPager);

      setupTabLayout(mTabLayout);

      ……
   }

   @Override
 public void onFinish(String tag, boolean state) {

      if (state)
 
         countLoad++;

      
      //cat.size() is the number of fragment in view pager.
      //each time fragment trigger this function, there will return true and countLoad will increase
      //if number of true == cat.size() the loading will disappear
  

      if (countLoad == cat.size() - 1) {

         cover_rl.setVisibility(View.GONE);

      }

   }
}
 
Then, Create Fragment class, 

public class PizzaFragment extends BaseFragment {

   @Override
 
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      return inflater.inflate(R.layout.default_fragment, container, false);

   }

   @Override
 
   public void onViewCreated(View view, Bundle savedInstanceState) {

       super.onViewCreated(view, savedInstanceState);

       ...
       ...

       
       //run task
       new AsyncDataTaskPizza().execute();
   }

   private class AsyncDataTaskPizza extends AsyncTask < Void, Void, Void > {
      @Override
 
      protected void onPreExecute() {

         super.onPreExecute();

      }

      @Override
      protected Void doInBackground(Void... params) {
           //HTTP Call or else
      }

      @Override
 
      protected void onPostExecute(List < PizzaDetail > result) {

          // call this function after finish load everything
          ((OnFragmentFinishLoad) getActivity()).onFinish(null, true);

      }
   }

}
 
Create other Fragment class, do like the same or something else but last process must end with ((OnFragmentFinishLoad) getActivity()).onFinish(null, true);


This is how i manage and i found that more easier to listen when all fragment in ViewPager is finish loading.  :D

Create different keystore for different flavour in Gradle Android

My current Android projects has a lot of flavors, and each flavor has different keystore to sign with. As a result it has very long build.gradle project file. As each flavor need defining separate singningConfig and defining flavor signing on release buildType. After reading couple of articles, i end up with this solution:


Change Snippet Background Color



1. Modify signingConfigs to fit with difference signing keystore for each flavour like example below
 
   // create 2 or more difference keystore.
    signingConfigs {
        
        configFirst {
            keyAlias KEY_ALIAS_MY
            keyPassword STORE_PASSWORD_MY
            storeFile file('../keystore_my.jks')
            storePassword KEY_PASSWORD_MY
        }

        configSecond {
            keyAlias KEY_ALIAS_SG
            keyPassword STORE_PASSWORD_SG
            storeFile file('../keystore_sg.jks')
            storePassword KEY_PASSWORD_SG
        }

        .....

        debug{

        }
    }
     

2. This is example of flavour. based on this example, only SGPROD and MYPROD i assign it to their own keystore. That's all as easy 123.. :D
    
    productFlavors{

        SGPROD{
            applicationId "com.mobile.sg"
            buildConfigField 'String', 'URL_LINK',SG_URL_PROD;
            buildConfigField 'String', 'URL_API',SG_API_PROD;
            
            //assign this flavour with signingConfigs configSecond
            signingConfig signingConfigs.configSecond
        }


        SGDEV{
            applicationId "com.mobile.sg.dev"
            buildConfigField 'String', 'URL_LINK',SG_URL_DEBUG;
            buildConfigField 'String', 'URL_API',SG_API_DEBUG;
        }

        MYPROD{
            applicationId "com.mobile.my"
            buildConfigField 'String', 'URL_LINK',MY_URL_PROD;
            buildConfigField 'String', 'URL_API',MY_API_PROD;

            //assign this flavour with signingConfigs configFirst
            signingConfig signingConfigs.configFirst
        }

        MYDEV{
            applicationId "com.mobile.my.dev"
            buildConfigField 'String', 'URL_LINK',MY_URL_DEBUG;
            buildConfigField 'String', 'URL_API',MY_API_DEBUG;
        }
    }

    

Thursday, September 29, 2016

Circle of Numbers (CodeFIght)

Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any two neighbouring numbers is equal (note that 0 and n - 1 are neighbouring, too).

Given n and firstNumber, find the number which is written in the radially opposite position tofirstNumber.


Example


For n = 10 and firstNumber = 2, the output should be
circleOfNumbers(n, firstNumber) = 7.




Change Snippet Background Color
 




int circleOfNumbers(int n, int firstNumber) {
    return (firstNumber+(n/2)) % n;
}
 

Sunday, September 25, 2016

How To Hide Keys in Android


Android apps which make RESTful calls typically need to supply an api key when making HTTP requests. Ideally, you wanna create an Android app that uses Twitter APIs, so yo need an API key and an API secrets only you and your apps know. Because you need these values inside you app, it’s easy and quick to write them down directly in your source code. But when you commit this code to GitHub (or any other public repo), practically you’re telling your secret keys to entire world. Seems uncommon??

For example, if you declare in code

private static final String API_KEY = “123456abc”;
private static final String API_URL = “https://your-domain-api.com/api/”;

and push your changes to a public git repo, your api key is now known to everyone. Other developers could re-use it.

One simple way to avoid this bad practice is to store your values inside an environmental variable, so only your machine knows it, then read this values in some way and inject them in your code at build time. For best way where i can find is hiding your keys inside gradle.properties

Where to find gradle.properties
  1. Show Hidden files
  2. Find .gradle folder in ~/Users and Click it
  3. You will find gradle.properties file inside .gradle folder. If not exist, then create new file name gradle.properties
  4. Then store anything that you want inside it. See below example:

Note (Warning): 
  1. Amend your .gitignore file to exclude gradle.properties from version control /gradle.properties
  2. Remove your gradle.properties file from your remote git repo, if it exists.

How to use the .gradle.properties global variable

Just call the name inside the build.gradle

for example:

signingConfigs {


    release {

        storeFile file('../yourkeystore.keystore')

        storePassword PROJECT_STORE_PASSWORD

        keyAlias PROJECT_KEY_ALIAS

        keyPassword PROJECT_KEY_PASSWORD

    }


    debug{



    }

}

buildConfigField 'String','SECRETKEY',PROJECT_API_SECRET
buildConfigField 'String','URL_API',PROJECT_URL_API_DEBUG

Then if you want to call the buildConfigField inside your code : BuildConfig.URL_API to get the value in gradle.properites



That’s all, then it’s up to you how to create more elaborated configurations. 

Saturday, September 24, 2016

Type of Programmer In This World

In journeys and programming adventures, there are many strange foes, and even stranger allies. They are identified at least five different kinds of code warriors, some make for wonderful comrades in arms, while others seem to foil my every plan. However they all have their place in the pantheon of software development. Without a healthy mix of these different programming styles you’ll probably find your projects either take too long to complete, are not stable enough or are too perfect for humans to look upon.

The OCD Perfectionist Programmer
"You want to do what to my code?"

This guy is the foundation of your company. When something goes wrong he will fix it fast and in a way that won’t break again. Of course he doesn’t care about how it looks, ease of use, or any of those other trivial concerns, but he will make it happen, without a bunch of talk or time-wasting nonsense. The best way to use this person is to point at a problem and walk away.

The Duct Tape Programmer
"The code may not be pretty, but damnit, it works!"

This guy doesn’t care about your deadlines or budgets, those are insignificant when compared to the art form that is programming. When you do finally receive the finished product you will have no option but submit to the stunning glory and radiant beauty of perfectly formatted, no, perfectly beautiful code, that is so efficient that anything you would want to do to it would do nothing but defame a masterpiece. He is the only one qualified to work on his code.

The Theoretical Programmer
"Well, that’s a possibility, but in practice this might be a better alternative."

His world has one simple truth; writing code is bad. If you have to write something then you’re doing it wrong. Someone else has already done the work so just use their code. He will tell you how much faster this development practice is, even though he takes as long or longer than the other programmers. But when you get the project it will only be 20 lines of actual code and will be very easy to read. It may not be very fast, efficient, or forward-compatible, but it will be done with the least effort required.

The Half-Assed Programmer
"What do you want? It works doesn’t it?"

The guy who couldn’t care less about quality, that’s someone elses job. He accomplishes the tasks that he’s asked to do, quickly. You may not like his work, the other programmers hate it, but management and the clients love it. As much pain as he will cause you in the future, he is single-handedly keeping your deadlines so you can’t scoff at it (no matter how much you want to).

The Anti-programming Programmer
"I’m a Programmer, damnit. I don’t write code."

This guy is more interested the options than what should be done. He will spend 80% of his time staring blankly at his computer thinking up ways to accomplish a task, 15% of his time complaining about unreasonable deadlines, 4% of his time refining the options, and 1% of his time writing code. When you receive the final work it will always be accompanied by the phrase “if I had more time I could have done this the right way”.



Sources: Steve Banner

Sunday, September 18, 2016

CPROM 2016 Q10 Adding Hexadecimal Number

Download Question Here

Change Snippet Background Color
 
import java.util.*;

/**
   Author : Hafiq
   Date :
**/

public class HexaDec{
   public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
      String line = System.getProperty("line.separator");
      scan.useDelimiter(line);
      
      int cases = scan.nextInt();
      
      for(int x=0;x<cases;x++){
         String[] split = scan.next().split(" ");
         
         int one = Integer.parseInt(split[0],16);
         int two = Integer.parseInt(split[1],16);
         
         System.out.println(Integer.toHexString(one+two).toUpperCase());
  
      }
      
   }
}