Monday, 29 February 2016

Convert HasMap.to String() to HasMap


    Here I am going to explain HasMap.toString() to HasMap.

   HasMap.toString() to HasMap.

   public HashMap<String, String> convertToHashMap(String mapString
   {
    HashMap<String, String> data = new HashMap<String, String>();
    Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
    String[] split p.split(mapString);
    for (int i = 1; i + 2 <= split.length; i += 2) {
        data.put(split[i], split [i + 1]);
    }
    return data ;
 }

// If String contains any spaces use Pattern p = Pattern.compile("(=|, )++");



  String() to HasMap.

  public HashMap<String, String> convertToHashMap(String jsonString
   {

   HashMap<String, String> data= null;
        try 
     {
          data= new HashMap<String, String>();

            String[] pairs jsonString.split(",");
            for (int i = 0; i < pairs.length; i++) 
            {
                String pair = pairs[i];
                String[] keyValue = pair.split(":");
                data.put(keyValue[0], keyValue[1]);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return data;
}

Happy Coding:)

Friday, 26 February 2016

Calculating vehicle speed in android


  Here I am going to explain how to calculate vehicle(car ,two wheeler etc..) speed using location provided by either GPS or Network.



Step 1)SpeedActivity

public class SpeedActivity extends Activity 
       { 
         Context context
         @Override 
         protected void onCreate(Bundle savedInstanceState) 
          {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           LocationManager locationManager=(LocationManager) this 
                                        .getSystemService(Context.LOCATION_SERVICE);
            LocationListener locationListener = new LocationListener() 
              {
                 public void onLocationChanged(Location location)
                     {
                  Toast.makeText(context, "Current speed:" + location.getSpeed(),                                                                     Toast.LENGTH_SHORT).show(); 
                     } 
          public void onStatusChanged(String provider, int status, Bundle extras) 
           { 
           } 
          public void onProviderEnabled(String provider) 
           { 
           } 
         public void onProviderDisabled(String provider)
          { 
          } 
       };
       locationManager.requestLocationUpdates
                    (LocationManager.NETWORK_PROVIDER, 0,0, locationListener);  


}


Step 2)Manifest Permission

android:name="android.permission.INTERNET
android:name="android.permission.ACCESS_NETWORK_STATE"
android:name="android.permission.READ_PHONE_STATE"
android:name="android.permission.ACCESS_COARSE_LOCATION"
android:name="android.permission.ACCESS_FINE_LOCATION"

  

Happy Coding:)
   



Thursday, 18 February 2016

Android Multi Selection Spinner



             Here I am going to explain Android MultiSelectionSpinner 







                              


Step 1).MultiSelectionSpinner.class

package com.extra;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


public class MultiSelectionSpinner extends Spinner implements
        DialogInterface.OnMultiChoiceClickListener
{
    String[] _items = null;
    boolean[] mSelection = null;

    ArrayAdapter<String> simple_adapter;

    public MultiSelectionSpinner(Context context)
    {
        super(context);

        simple_adapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_spinner_item);
        super.setAdapter(simple_adapter);
    }

    public MultiSelectionSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);

        simple_adapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_spinner_item);
        super.setAdapter(simple_adapter);
    }

    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        if (mSelection != null && which < mSelection.length) {
            mSelection[which] = isChecked;

            simple_adapter.clear();
            simple_adapter.add(buildSelectedItemString());
        } else {
            throw new IllegalArgumentException(
                    "Argument 'which' is out of bounds.");
        }
    }

    @Override
    public boolean performClick() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMultiChoiceItems(_items, mSelection, this);

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {

            }
        });


        builder.show();
        return true;
    }

    @Override
    public void setAdapter(SpinnerAdapter adapter) {
        throw new RuntimeException(
                "setAdapter is not supported by MultiSelectSpinner.");
    }

    public void setItems(String[] items) {
        _items = items;
        mSelection = new boolean[_items.length];
        simple_adapter.clear();
        simple_adapter.add(_items[0]);
        Arrays.fill(mSelection, false);
    }

    public void setItems(List<String> items) {
        _items = items.toArray(new String[items.size()]);
        mSelection = new boolean[_items.length];
        simple_adapter.clear();
        simple_adapter.add(_items[0]);
        Arrays.fill(mSelection, false);
    }

    public void setSelection(String[] selection) {
        for (String cell : selection) {
            for (int j = 0; j < _items.length; ++j) {
                if (_items[j].equals(cell)) {
                    mSelection[j] = true;
                }
            }
        }
    }

    public void setSelection(List<String> selection) {
        for (int i = 0; i < mSelection.length; i++) {
            mSelection[i] = false;
        }
        for (String sel : selection) {
            for (int j = 0; j < _items.length; ++j) {
                if (_items[j].equals(sel)) {
                    mSelection[j] = true;
                }
            }
        }
        simple_adapter.clear();
        simple_adapter.add(buildSelectedItemString());
    }

    public void setSelection(int index) {
        for (int i = 0; i < mSelection.length; i++) {
            mSelection[i] = false;
        }
        if (index >= 0 && index < mSelection.length) {
            mSelection[index] = true;
        } else {
            throw new IllegalArgumentException("Index " + index
                    + " is out of bounds.");
        }
        simple_adapter.clear();
        simple_adapter.add(buildSelectedItemString());
    }

    public void setSelection(int[] selectedIndicies) {
        for (int i = 0; i < mSelection.length; i++) {
            mSelection[i] = false;
        }
        for (int index : selectedIndicies) {
            if (index >= 0 && index < mSelection.length) {
                mSelection[index] = true;
            } else {
                throw new IllegalArgumentException("Index " + index
                        + " is out of bounds.");
            }
        }
        simple_adapter.clear();
        simple_adapter.add(buildSelectedItemString());
    }

    public List<String> getSelectedStrings() {
        List<String> selection = new LinkedList<String>();
        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                selection.add(_items[i]);
            }
        }
        return selection;
    }

    public List<Integer> getSelectedIndicies() {
        List<Integer> selection = new LinkedList<Integer>();
        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                selection.add(i);
            }
        }
        return selection;
    }

    private String buildSelectedItemString() {
        StringBuilder sb = new StringBuilder();
        boolean foundOne = false;

        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                if (foundOne) {
                    sb.append(", ");
                }
                foundOne = true;

                sb.append(_items[i]);
            }
        }
        return sb.toString();
    }

    public String getSelectedItemsAsString() {
        StringBuilder sb = new StringBuilder();
        boolean foundOne = false;

        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                if (foundOne) {
                    sb.append(", ");
                }
                foundOne = true;
                sb.append(_items[i]);
            }
        }
        return sb.toString();
    }
}


Step 2)Spinner

          //please use package with class name

          <com.extra.MultiSelectionSpinner
                    android:id="@+id/input1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="2dp" />

Step 3)Add the below code in your Activity

 Spinner spinner=(Spinner)findViewById(R.id.input1);

   List<String> list = new ArrayList<String>();
        list.add("List1");
        list.add("List2");
        spinner.setItems(list);


Happy Coding:)
   


     

Prevent EditText from resizing itself in landscape view


Here I am going to explain how to prevent EditText from  itself in landscape view


                                     


   Add the property android:imeOptions="flagNoExtractUi"  to each EditText in your XML file.


    

HappyCoding:)



                      


Friday, 12 February 2016

How to get Call end event


              Here I am going to explain how to detect call end event using Broadcast listener.


Step 1)PhoneBroadcastReceiver.java

     public class PhoneBroadcastReceiver extends BroadcastReceiver {
      
     Context mcontext;
     String number;
     private int prev_state;

    @Override
    public void onReceive(Context context, Intent intent) {
       TelephonyManager telephony =
                                  (TelephonyManager)context.getSystemService
                                                      (Context.TELEPHONY_SERVICE); 
      CustomPhoneStateListener customPhoneListener = new                                                                                        CustomPhoneStateListener();
      telephony .listen(customPhoneListener ,
                                        PhoneStateListener.LISTEN_CALL_STATE);
        Bundle bundle = intent.getExtras();
        String phoneNum = bundle.getString("number");
        mcontext= context;

    }

    
    public class CustomPhoneStateListener extends PhoneStateListener {

       @Override
        public void onCallStateChanged(int state, String incomingNumber){

           if( incomingNumber != null && incomingNumber.length() > 0 ) 
              number incomingNumber

            switch(state){
                case TelephonyManager.CALL_STATE_RINGING:
                      
                        prev_state=state;
                        break;

                case TelephonyManager.CALL_STATE_OFFHOOK:
                                
                        prev_state=state;
                        break;

                case TelephonyManager.CALL_STATE_IDLE:

                    if((prev_state== TelephonyManager.CALL_STATE_OFFHOOK)){
                        prev_state=state;
                        //Answered Call 
                    }
                    if((prev_state== TelephonyManager.CALL_STATE_RINGING)){
                        prev_state=state;
                        //Rejected or Missed call
                    }
                    break;
            }
        }
    }
}


Step 2)Register the receiver

  <receiver android:name=".PhoneBroadcastReceiver">  
       <intent-filter>  
               <action android:name="android.intent.action.PHONE_STATE">       
       </action></intent-filter>  
</receiver> 


Step 3)Add permission to your manifest

   <uses-permission android:name="android.permission.READ_PHONE_STATE">
  </uses-permission> 

Happy Coding:)

Saturday, 6 February 2016

Create text file in android programmatically


Here I am going to explain how to create text file and insert data to that file on android


Step 1)

 private void writeFile(String name)
    {

      try {
      File root = new File(Environment.getExternalStorageDirectory(), "History");
            if (!root .exists()) {
                root .mkdirs();
            }
            File file= new File(root, "example.txt");
            FileWriter writer = new FileWriter(file);
            writer.append(name);
            writer.flush();
            writer.close();
     Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
          
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


Step 2)Adding permissions to Manifest file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


HappyCoding:)