Recent Posts

Sunday 22 November 2015

Creating Views in android in loops ( Java )

Here goes a small code for looping in android using java.

Layout to which we add views

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent" android:layout_height="wrap_content"
  android:orientation="vertical" android:id="@+id/content">
</LinearLayout>



Lets create views in for loop and add to above layout

LinearLayout content=(LinearLayout)findViewById(R.id.content);

int[5] x={1,2,3,4,5};
for(int i:x)
{
  Button butn=new Button(getApplicationContext());
  butn.setTag(i);       // used for identifying individually each button 
 content.addView(butn);
}

Sunday 6 September 2015

Compressing images as like WhatsApp in Android



package com.smartapps.ImageResolution;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Details extends ActionBarActivity {
    File profile_pic_file;
    SharedPreferences pref;
    ImageView preview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        pref = getSharedPreferences("log_account", 0);
        String user_name = pref.getString("user_name", null);

        if (user_name == null)
            // Creating the profile pic file
            try {
                File dir = getExternalFilesDir(null);
                File _dir = new File(dir, "LocalStorage");
                if (!_dir.exists()) _dir.mkdir();

                profile_pic_file = new File(_dir, "profile.jpg");
                if (!profile_pic_file.exists()) profile_pic_file.createNewFile();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

        preview = (ImageView) findViewById(R.id.preview_image);
        ImageButton image_select = (ImageButton) findViewById(R.id.image_select);
        Button save_butn = (Button) findViewById(R.id.save_butn);

        image_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent image_select = new Intent();
                image_select.setAction(Intent.ACTION_PICK);
                image_select.setType("image/*");
                startActivityForResult(image_select, 1);
            }
        });// end of the select_image button

        save_butn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }); // end of the Save Button

    }

    private String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        cursor.moveToFirst();
        int column = cursor.getColumnIndex(projection[0]);
        String path = cursor.getString(column);
        cursor.close();
        return path;
    }

    @Override
    protected void onActivityResult(int req_code, int res_code, Intent data) {
        if (req_code == 1)
            if (res_code == RESULT_OK) {
                String path = getPath(data.getData());
                try {
                    File file = new File(path);
                    FileInputStream fis = new FileInputStream(file);
                    byte[] bytes_data = new byte[(int) file.length()];
                    fis.read(bytes_data);fis.close();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;

                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes_data, 0, bytes_data.length, options);
                    int w = options.outWidth,h=options.outHeight, insampleSize = 1;

                    if(h>w){ insampleSize=getSample(h,false); }
                    else { insampleSize=getSample(w,true); }

                    if(insampleSize!=1){
                        options.inSampleSize=insampleSize;
                        options.inJustDecodeBounds = false;

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        bitmap = BitmapFactory.decodeByteArray(bytes_data, 0, bytes_data.length, options);
                        bitmap.compress(Bitmap.CompressFormat.JPEG,25,bos);

                        FileOutputStream fos = new FileOutputStream(profile_pic_file);
                        fos.write(bos.toByteArray());fos.flush();fos.close();
                    }
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

        if (req_code == 2)
            if (res_code == RESULT_OK) {
                ByteArrayOutputStream bos=new ByteArrayOutputStream();
                Bitmap bm=data.getExtras().getParcelable("data");
                bm.compress(Bitmap.CompressFormat.JPEG,25,bos);
                try {
                    FileOutputStream fos=new FileOutputStream(profile_pic_file);
                    fos.write(bos.toByteArray());fos.flush();fos.close();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();}
                finally {
                    preview.setImageBitmap(bm);
                }
            }
    }

    private int getSample(int x,boolean isWidth){
        int u=1;
        if(isWidth)
        {
            if(x>1000) u=x/1000;
        }
        else{
            if(x>350) u=x/350;
        }
        return u;
    }
}

Tuesday 30 June 2015

Finding Factorial using the BigInteger in JAVA

Up to Schooling we may only find factorial up to 25 but in real engineering we may have to deal with the largest numbers where the usual datatypes may not work. In Java , BigInteger is the pre-defined class we use in order to deal with those numbers.

Here in our example, using BigInteger we are finding factorial for larger Numbers.

import java.lang.*;
import java.util.Scanner;
import java.math.BigInteger;

public class HelloWorld {
    @ SuppressWarnings ("deprication")
    /*  The above line suppress the deprication warnings */
    public static void main(String[] args) {
    try{
        Scanner sc=new Scanner(System.in);
        int tests=Integer.parseInt(sc.next());
        BigInteger num,sum;
        String res;
        while(tests--!=0)
        {
        sum=new BigInteger("1");
        num=new BigInteger(sc.next());
        while(num.compareTo(new BigInteger("0"))!=0){
        sum=sum.multiply(num);
        num=num.subtract(new BigInteger("1"));
        }
        res+=sum+"\n";
        }
        System.out.println(res);
    }
    catch(Exception e){ System.out.println(e.getMessage()); }
    }
}

Converting Numbers to Different Numerical Systems in JAVA

You may have to change the numbers from one format to other format, as like from decimal to hexagon . Here i have tried the different approach where you can convert from one numerical system to other numerical system using the digits in that numerical system.

For Example , if i want to convert the 10 from decimal to hexagon. I will provide the input in the following format along with the number of Test Cases.
1
# input1: 10 0123456789 0123456789abcdef
# output: a

Here is the logic for that written in JAVA language.

import java.lang.*; import java.util.*; public class Numbers{ @ SuppressWarnings ("deprication") public static void main(String[] args) { String result=""; Scanner sc=new Scanner(System.in); int i=0,tests=Integer.parseInt(sc.next()); while(i++<tests){ String numbr=sc.next(); String source_pattern=sc.next(); String target_pattern=sc.next(); Number_System source=new Number_System(source_pattern); Number_System target=new Number_System(target_pattern); result=result+"Case #"+i+": "+target.genValue(source.genDeciValue(numbr))+"\n"; } System.out.print(result); } } class Number_System{ int len=0; String pattern; public Number_System(String seq){ len=seq.length(); pattern=seq; } public int genDeciValue(String x){ int i=0,v,str_len=x.length(); Double value=new Double(0.0); while(i<str_len){ v=pattern.indexOf(x.charAt(str_len-i-1)); value=v*Math.pow(len,i)+value; i++; } return value.intValue(); } public String genValue(int x){ String res=""; while(x!=0) { if(x<len){ res=pattern.charAt(x)+""+res; break; } res=pattern.charAt(x%len)+""+res; x=x/len; } return res; } }

Sunday 7 June 2015

Validating IPAddress in Java

This is the part of the java Regular Expressions, Validating,searching the data using the matches function This is mostly used in analyzing the data. To know further about it read about JAVA Regex  

import java.io.*;

public class ValidIP{

     public static void main(String []args){
       String IP="000.12.12.034";
       String pat="(([01]?(\\d)?(\\d))|([2]?([012345])?([012345])))";
       String pattern=pat+"."+pat+"."+pat+"."+pat;
       System.out.println(IP.matches(pattern));
     }
}

Sunday 31 May 2015

Basic Steps to Create your WebSite

WebServer: The computer which serves the requests from the client (webbrowser) is called webserver.

 WebClient: The computer from which the clients request the services (webpage) is called webClient. The application used in webclient to access the webserver is called WebServer.

 To make the business, internet is the best market place. Setting up the website is the basic step for online business.

Today we are going to learn about How to setup the website ? We can setup the website in 3 steps.

1.) Register your domain :Domain name is the virtual address to your website. Generally to access the webserver we use ipaddress of the server, but for humans it was difficult to remember numbers than alphabets . So we register our static ipaddress with the corresponding alphabatics. Those are called Domain Names.
                               Eg: www.google.com   www.blogger.com  

2.) Prepare your hosting area : Hosting means storing your files in the system whose ipaddress is registered for Domain Name. This can be done in two ways :
  1. Creating your server
  2. Buying Hosting area ( www.godaddy.com )
3.) Linking your hosting and domain : Login to your domain name provider website, select your domain name and now activate it by updating the name servers provided by the hosting website / update name servers with your hosting system in case of own hosting system.

  Testing the system : After linking the domain, it takes minimum 15 min and max 1 day for activate your system. Create the file with name "index.html" and in that file write "Its working" and place it in public_html folder.

 Now enter your domain in the browser and click enter to see "Its working".


    I hope you understand the basic steps. If any doubts please comment it.

Tuesday 26 May 2015

Executing C program in android mobile using terminal IDE

While studying about the android software stack . I got to know that the base is linux terminal . So I got one idea doubt if we can run the C program .
Yes of course we can execute the C program in android mobile using the app Terminal IDE ,which lets us to access the Linux terminal in our android mobile.

Here are the steps to download, install the terminal IDE in your mobile and executing C program.
First Step : Install the Terminal IDE app in your android mobile phone, which lets you to access your linux terminal in android mobile.

Second Step : Open the terminal IDE and select the option Install System.



Third Step : Now press back and select the Terminal IDE option to access your terminal IDE.Now navigate to the system folder and then to src folder, where this app is having the permissions to execute the file. To navigate to that directory type the command cd system/src . And also create the directory code where we are going to store our code using the command mkdir code


Fourth Step : Its now time to create the C program file, here i am creating the file test.c file and placing the code for "Hello World" program .Before that navigate to code folder using cd code . Commands to create and write the code are cat>test.c.

Fifth Step : Now in the terminal list select the another terminal other than Terminal 1 .


Sixth Step : We have to install the terminal GCC for compiling and executing the C Program. To install the terminal GCC type the command install_gcc .


Seventh Step : Its time for us to compile and execute the C program. Lets do that in three steps.
  1. terminal-gcc -c test.c
  2. terminal-gcc test.o -o test
  3. ./test

 
biz.