Thursday, February 9, 2017

Update content of spinner after selecting item in Android

Are your spinners in different activities? 

If they are, so you can just pass the selected value of the first spinner via Intent (See the putExtra section) and retrieve the value from the next activity so that you can set accordingly the next spinners. 

Edit: 
Here is an example that changes the selected item in the 2nd and 3rd spinner. Update the listener (onItemSelected method) with your logic

Create Activity:

private Spinner s;
private Spinner s2;
private Spinner s3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    String[] myList = new String[] {
        Hello,
        World,
        Foo,
        Bar
    };
    String[] myList2 = new String[] {
        Hello2,
        World2,
        Foo2,
        Bar2
    };
    String[] myList3 = new String[] {
        Hello3,
        World3,
        Foo3,
        Bar3
    };

    s = (Spinner) findViewById(R.id.spinner1);
    s2 = (Spinner) findViewById(R.id.spinner2);
    s3 = (Spinner) findViewById(R.id.spinner3);

    s.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_item, myList));
    s2.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_item, myList2));
    s3.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_item, myList3));

    s.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView parent, View v,
            int pos, long id) {
            s2.setSelection(pos);
            s3.setSelection(pos);
        }

        @Override
        public void onNothingSelected(AdapterView arg0) {

        }
    });
}

Create main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout android:layout_width=”fill_parent” xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”wrap_content”
android:orientation=”vertical”>
<Spinner android:id=”@+id/spinner1″ android:layout_height=”wrap_content” android:layout_width=”fill_parent” />
<Spinner android:id=”@+id/spinner2″ android:layout_height=”wrap_content” android:layout_width=”fill_parent” />
<Spinner android:id=”@+id/spinner3″ android:layout_height=”wrap_content” android:layout_width=”fill_parent” />
</LinearLayout>

Monday, February 6, 2017

Swipe gesture implementation in android

1st way of making swipe gesture:
 public class OnSwipeTouchListener implements OnTouchListener {  
   private final GestureDetector gestureDetector = new GestureDetector(new GestureListener());  
   public boolean onTouch(final View view, final MotionEvent motionEvent) {  
     return gestureDetector.onTouchEvent(motionEvent);  
   }  
   private final class GestureListener extends SimpleOnGestureListener {  
     private static final int SWIPE_THRESHOLD = 100;  
     private static final int SWIPE_VELOCITY_THRESHOLD = 100;  
     @Override  
     public boolean onDown(MotionEvent e) {  
       return true;  
     }  
     @Override  
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {  
       boolean result = false;  
       try {  
         float diffY = e2.getY() - e1.getY();  
         float diffX = e2.getX() - e1.getX();  
         if (Math.abs(diffX) > Math.abs(diffY)) {  
           if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {  
             if (diffX > 0) {  
               onSwipeRight();  
             } else {  
               onSwipeLeft();  
             }  
           }  
         } else {  
           if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {  
             if (diffY > 0) {  
               onSwipeBottom();  
             } else {  
               onSwipeTop();  
             }  
           }  
         }  
       } catch (Exception exception) {  
         exception.printStackTrace();  
       }  
       return result;  
     }  
   }  
   public void onSwipeRight() {  
   }  
   public void onSwipeLeft() {  
   }  
   public void onSwipeTop() {  
   }  
   public void onSwipeBottom() {  
   }  
 }  
 //call OnSwipeTouchListener to set gesture to particular control.  
 relParent.setOnTouchListener(new OnSwipeTouchListener() {  
         public void onSwipeTop() {  
           Toast.makeText(this, "top", Toast.LENGTH_SHORT).show();  
         }  
         public void onSwipeRight() {  
           Toast.makeText(this, "right", Toast.LENGTH_SHORT).show();  
         }  
         public void onSwipeLeft() {  
           Toast.makeText(this, "left", Toast.LENGTH_SHORT).show();  
         }  
         public void onSwipeBottom() {  
           Toast.makeText(this, "bottom", Toast.LENGTH_SHORT).show();  
         }  
       });  
2nd way of implementing swipe gesture:
 @Override  
   public boolean onTouchEvent(MotionEvent touchevent) {  
     //return super.onTouchEvent(event);  
     switch (touchevent.getAction()){  
     // when user first touches the screen we get x and y coordinate  
     case MotionEvent.ACTION_DOWN: {  
       x1 = touchevent.getX();  
       y1 = touchevent.getY();  
       break;  
     }  
     case MotionEvent.ACTION_UP: {  
       x2 = touchevent.getX();  
       y2 = touchevent.getY();  
       //if left to right sweep event on screen  
       if (x1 < x2) {                Toast.makeText(this, "Left to Right Swap Performed", Toast.LENGTH_LONG).show();       }      // if right to left sweep event on screen      if (x1 > x2){  
         Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();  
       }  
       // if UP to Down sweep event on screen  
       if (y1 < y2) {        Toast.makeText(this, "UP to Down Swap Performed", Toast.LENGTH_LONG).show();      }      //if Down to UP sweep event on screen      if (y1 > y2){  
         Toast.makeText(this, "Down to UP Swap Performed", Toast.LENGTH_LONG).show();  
       }  
       break;  
     }  
     }  
     return false;  
   }  

Find address as per input using Google Places api in android

By using Google Places API we can find particular address details. APIs thereby providing response in terms of XML or JSON format. I assume that you have API key with you.

To achieve this follow some simple steps below:












Step 1: Create PlaceSearchActivity.java class
 public class PlaceSearchActivity extends Activity{  
   PlacesTask placesTask;  
   EditText etxtPlaces;  
   ListView listViewPlaces;  
   PlaceAdapter adapter;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     try {  
       setContentView(R.layout.activity_main);  
       initializeControls();  
       handleTextChangeListner();  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private void initializeControls(){  
     try {  
       etxtPlaces = (EditText)findViewById(R.id.etxtPlaces);  
       listViewPlaces = (ListView)findViewById(R.id.listViewPlaces);  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private void handleTextChangeListner(){  
     try {  
       etxtPlaces.addTextChangedListener(new TextWatcher() {  
         @Override  
         public void onTextChanged(CharSequence s, int start, int before, int count) {          
         }  
         @Override  
         public void beforeTextChanged(CharSequence s, int start, int count,  
             int after) {  
         }  
         @Override  
         public void afterTextChanged(Editable s) {  
           // TODO Auto-generated method stub  
           placesTask = new PlacesTask();  
           placesTask.execute(s.toString());  
         }  
       });  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private class PlacesTask extends AsyncTask<String, Void, String>{  
     @Override  
     protected String doInBackground(String... place) {  
       // For storing data from web service  
       String data = "";  
       try {  
         // Obtain browser key from https://code.google.com/apis/console  
         String key = "key=YOUR API KEY";  
         String input="";  
         input = "input=" + URLEncoder.encode(place[0], "utf8");  
         // place type to be searched  
         String types = "types=geocode";  
         // Sensor enabled  
         String sensor = "sensor=false";       
         // Building the parameters to the web service  
         String parameters = input+"&"+types+"&"+sensor+"&"+key;  
         // Output format  
         String output = "json";  
         // Building the url to the web service  
         String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;  
         try {  
           data = downloadUrl(url);  
         } catch (IOException e) {  
           e.printStackTrace();  
         }  
       } catch (UnsupportedEncodingException e) {  
         e.printStackTrace();  
       }  
       return data;  
     }  
     @Override  
     protected void onPostExecute(String result) {  
       super.onPostExecute(result);  
       try {  
         parseAndBindDataToListview(result);  
       } catch (Exception e) {  
         e.printStackTrace();  
       }  
     }  
   }  
   private void parseAndBindDataToListview(String result){  
     try {  
       JSONObject jsonObject2 = new JSONObject(result);  
       JSONArray array = jsonObject2.getJSONArray("predictions");  
       JSONObject[] jsonObject = new JSONObject[array.length()];  
       for (int i = 0; i < array.length(); i++) {  
         jsonObject[i] = array.getJSONObject(i);  
       }  
       adapter = new PlaceAdapter(PlaceSearchActivity.this, R.layout.place_list_row, jsonObject);  
       listViewPlaces.setAdapter(adapter);  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   /** A method to download json data from url */  
   private String downloadUrl(String strUrl) throws IOException{  
     String data = "";  
     InputStream iStream = null;  
     HttpURLConnection urlConnection = null;  
     try{  
       URL url = new URL(strUrl);          
       // Creating an http connection to communicate with url  
       urlConnection = (HttpURLConnection) url.openConnection();  
       // Connecting to url  
       urlConnection.connect();  
       // Reading data from url  
       iStream = urlConnection.getInputStream();  
       BufferedReader br = new BufferedReader(new InputStreamReader(iStream));  
       StringBuffer sb = new StringBuffer();  
       String line = "";  
       while( ( line = br.readLine()) != null){  
         sb.append(line);  
       }  
       data = sb.toString();  
       br.close();  
     }catch(Exception e){  
       Log.d("Exception while downloading url", e.toString());  
     }finally{  
       iStream.close();  
       urlConnection.disconnect();  
     }  
     return data;  
   }    
 }  
Step 2: Create PlaceAdapter.java class
 public class PlaceAdapter extends ArrayAdapter<JSONObject>{  
   private Context context;  
   private int textViewResourceId;  
   private JSONObject[] data;  
   public PlaceAdapter(Context context, int textViewResourceId, JSONObject[] objects) {  
     super(context, textViewResourceId, objects);  
     this.context = context;  
     this.textViewResourceId = textViewResourceId;  
     data = objects;  
   }  
   @Override  
   public View getView(int position, View convertView, ViewGroup parent) {  
     Viewholder holder = null;  
     try {  
       if(convertView==null){  
         holder = new Viewholder();  
         LayoutInflater inflater = (LayoutInflater) context  
             .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
         convertView = inflater.inflate(textViewResourceId, parent, false);  
         holder.txtPlace = (TextView) convertView.findViewById(R.id.txtPlace);  
       }  
       holder.txtPlace.setText(data[position].getString("description"));  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
     return convertView;  
   }  
   static class Viewholder{  
     TextView txtPlace;  
   }  
 }  
Step 3: Create layout activity_main.xml
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity" >  
   <EditText  
     android:id="@+id/etxtPlaces"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="18dp"  
     android:ems="10" />  
   <ListView  
     android:id="@+id/listViewPlaces"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_below="@+id/etxtPlaces"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="29dp" >  
   </ListView>  
 </RelativeLayout>  
Step 4: Create layout place_list_row.xml which includes row data, how it will look
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical" >  
   <TextView  
     android:id="@+id/txtPlace"  
     android:layout_width="wrap_content"  
     android:padding="10dp"  
     android:layout_height="wrap_content"  
     android:text="TextView" />  
 </LinearLayout>  
Step 5: Mention internet permission in manifest
 <uses-permission android:name="android.permission.INTERNET"/>  
You are done 😄 🙌

Sunday, February 5, 2017

Difference between @SuppressLint vs @TargetApi

The difference is that with @TargetApi, you declare, via the parameter, what API level you have addressed in your code, so that the error can pop up again if you later modify the method to try referencing something newer than the API level cited in @TargetApi.

For example, suppose that, instead of blocking the StrictMode complaints about your networking bug, you were trying to work around the issue of AsyncTask being serialized on newer versions of Android. You have a method like this in your code to opt into the thread pool on newer devices and use the default multithread behavior on older devices:
 @TargetApi(11)  
 static public<T> void executeAsyncTask(AsyncTask<T,?,?> task,  
                      T...params){  
 if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB){  
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params);  
 }else{  
    task.execute(params);  
 }  
 }  
Having @TargetApi(11) means that if Lint detects that I am using something newer than my android:minSdkVersion, but up to API Level 11, Lint will not complain. In this case, that works. If, however, I modified this method to reference something that wasn’t added until API Level 14, then the Lint error would appear again, because my @TargetApi(11) annotation says that I only fixed the code to work on API Level 11 and below, not API Level 14 and below. Using @SuppressLint(‘NewApi’), I would lose the Lint error for any API level, regardless of what my code references and what my code is set up to handle. Hence, @TargetApi is the preferred annotation, as it allows you to tell the build tools “OK, I fixed this category of problems” in a more fine-grained fashion.

Saturday, February 4, 2017

How to call webservice in Android

Just insert code below in your project and as per requirement add Key/Value pairs in request.addProperty. Whereas StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them.

StrictMode is most commonly used to catch accidental disk or network access on the application’s main thread, where UI operations are received and animations take place. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications. By keeping your application’s main thread responsive, you also prevent ANR dialogs from being shown to users.
 public String callGetSecurityQuestions() throws Exception{  
     String NAMESPACE = "YOUR NAMESPACE HERE" //e.g. "http://namespace/";  
     String URL = "YOUR URL HERE" //e.g. "http://domainname/asmx name";  
     String METHOD_NAME = "YOUR METHOD NAME" //e.g. "GetSecurityQuestions";  
     String SOAP_ACTION = NAMESPACE+METHOD_NAME;  
     String response = "";  
     try {  
       if (android.os.Build.VERSION.SDK_INT > 9) {  
         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();  
         StrictMode.setThreadPolicy(policy);  
       }  
       SoapObject request = new SoapObject(CommonEnviornment.NAMESPACE,METHOD_NAME);  
       request.addProperty("key1", value1);        
       request.addProperty("key2", value2);  
       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);  
       envelope.dotNet = true;  
       envelope.setOutputSoapObject(request);  
       HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonEnviornment.URL);  
       androidHttpTransport.call(SOAP_ACTION, envelope);  
       SoapObject result = (SoapObject)envelope.bodyIn;  
       response = result.toString();  
       System.out.println(result.toString());  
     } catch (Exception e) {  
       throw e;  
     }  
     return response;  
   }  

Prevent user from setting previous DateTime in android

This can be achieved in two ways.
1st Way:
 package com.example.datetimedemo;  
 import java.util.Calendar;  
 import java.util.Date;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.text.format.DateFormat;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.DatePicker;  
 import android.widget.TextView;  
 import android.widget.TimePicker;  
 import android.widget.Toast;  
 public class MainActivity extends Activity{  
   DatePicker datePicker;  
   TimePicker timePicker;  
   TextView textView;  
   Date currentDate,selectedDate;  
   Calendar calendar;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     try {  
       setContentView(R.layout.main_layout);    
       textView = (TextView)findViewById(R.id.textView1);  
       datePicker = (DatePicker)findViewById(R.id.datePicker1);  
       timePicker = (TimePicker)findViewById(R.id.timePicker1);  
       calendar = Calendar.getInstance();  
       Button button = (Button)findViewById(R.id.button1);  
       button.setOnClickListener(new OnClickListener() {  
         @Override  
         public void onClick(View v) {  
           int currentDay = calendar.get(Calendar.DAY_OF_MONTH);  
           int currentMonth = calendar.get(Calendar.MONTH);  
           int currentYear = calendar.get(Calendar.YEAR) - 1900;  
           int currentHour = calendar.get(Calendar.HOUR_OF_DAY);  
           int currentMin = calendar.get(Calendar.MINUTE);  
           currentDate = new Date(currentYear, currentMonth, currentDay, currentHour, currentMin);  
           int selectedYear = datePicker.getYear();  
           int selectedDay = datePicker.getDayOfMonth();  
           int selectedMonth = datePicker.getMonth();  
           int selectedHour = timePicker.getCurrentHour();  
           int selectedMin = timePicker.getCurrentMinute();  
           selectedDate = new Date(selectedYear - 1900, selectedMonth, selectedDay, selectedHour, selectedMin);  
           if(selectedDate.compareTo(currentDate)<0){  
             Toast.makeText(getApplicationContext(), "Cannot set previous datetime.", Toast.LENGTH_SHORT).show();  
             textView.setText("");  
           }  
           else {  
             textView.setText(DateFormat.format("hh:mm a dd/MMM/yyyy", selectedDate)); //Output: 03:06 pm 07/Apr/2014  
           }  
         }  
       });  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
 }  
Create layout:
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical" >  
   <ScrollView  
     android:id="@+id/scrollView1"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content" >  
     <LinearLayout  
       android:layout_width="match_parent"  
       android:layout_height="match_parent"  
       android:gravity="center_horizontal"  
       android:orientation="vertical" >  
       <DatePicker  
         android:id="@+id/datePicker1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:calendarViewShown="false" />  
       <TimePicker  
         android:id="@+id/timePicker1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content" />  
       <Button  
         android:id="@+id/button1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:text="Done" />  
       <TextView  
         android:id="@+id/textView1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:layout_marginTop="15dp"  
         android:text="TextView" />  
     </LinearLayout>  
   </ScrollView>  
 </LinearLayout>  
2nd Way: 
2nd way of implementing above stuff is mentioned as shown below. Only slight change includes, user cannot select datetime before our predefined datetime. i.e. If we want that user should not select datetime before 20 min if he does that then will display message saying you cannot select past datetime. Assuming the same layout.
 package com.example.datetimedemo;  
 import java.text.SimpleDateFormat;  
 import java.util.Calendar;  
 import java.util.Date;  
 import android.annotation.SuppressLint;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.DatePicker;  
 import android.widget.TextView;  
 import android.widget.TimePicker;  
 import android.widget.Toast;  
 public class MainActivity extends Activity{  
   DatePicker datePicker;  
   TimePicker timePicker;  
   TextView textView;  
   Date currentDate,selectedDate;  
   Calendar calendar;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     try {  
       setContentView(R.layout.main_layout);    
       textView = (TextView)findViewById(R.id.textView1);  
       datePicker = (DatePicker)findViewById(R.id.datePicker1);  
       timePicker = (TimePicker)findViewById(R.id.timePicker1);  
       calendar = Calendar.getInstance();  
       Button button = (Button)findViewById(R.id.button1);  
       button.setOnClickListener(new OnClickListener() {  
         @SuppressLint("SimpleDateFormat")  
         @Override  
         public void onClick(View v) {  
           Calendar cal = Calendar.getInstance();  
           cal.add(Calendar.MINUTE, 20); // Set our predefined value here.   
           calendar.clear();  
           calendar.set(Calendar.YEAR, datePicker.getYear());  
           calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());  
           calendar.set(Calendar.MONTH, datePicker.getMonth());  
           calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());  
           calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());            
           if(validateTime(cal.getTimeInMillis()/1000L, calendar.getTimeInMillis()/1000L)) {  
             SimpleDateFormat format = new SimpleDateFormat("hh:mm a dd/MMM/yyyy");  
             Date date = calendar.getTime();  
             textView.setText(format.format(date).toString()); //Output: 03:06 pm 07/Apr/2014  
             Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();  
           }else {  
             Toast.makeText(MainActivity.this, "Wrong", Toast.LENGTH_SHORT).show();  
           }  
         }  
       });  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private boolean validateTime(long current, long selected) {  
     if(selected > current)  
       return true;  
     return false;  
   }  
 }  

How to use Facebook login in android studio