Monday, November 23, 2015

Sending a JSON Request from android

Similar to sending a regular HTTP request, android-async-http can also be used for sending JSON API requests:
String url = "https://ajax.googleapis.com/";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("q", "android");
params.put("rsz", "8");
client.get(url, params, new JsonHttpResponseHandler() {         
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
       // Root JSON in response is an dictionary i.e { "data : [ ... ] }
       // Handle resulting parsed JSON response here
    }

        @Override
        public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        }
});
The request will be sent out with the appropriate parameters passed in the query string and then the response will be parsed as JSON and made available within onSuccess. Check the Converting JSON to Models guide for more details on parsing a JSON response.

Sending a Network Request in android

Now, we just create an AsyncHttpClient, and then execute a request specifying an anonymous class as a callback:
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.Header;

AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
client.get("http://www.google.com", params, new TextHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String res) {
            // called when response HTTP status is "200 OK"
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        } 
    }
);
This will automatically execute the request asynchronously and fire the onSuccess when the response returns a success code and onFailure if the response does not.

Wednesday, November 18, 2015

How to use character & in android strings.xml

Use this Code for TextView in your Xml
<TextView   
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content" 
  android:text="Backup &amp; Restore "  
  android:textSize="30dp"  
  android:textColor="#33B5E5" 
  android:id="@+id/textView"  
 />

out put
Backup & Restore

Tuesday, November 17, 2015

How to add an image header in navigation drawer layout in android

Add this code in your Mainactivity on create after add drawer item in drawerlist

View header = getLayoutInflater().inflate(R.layout.abc, null);
ImageView pro = (ImageView) header.findViewById(R.id.profile_image);
pro.setOnClickListener(new View.OnClickListener() {
    @Override 
   public void onClick(View arg0) {
        // TODO Auto-generated method stub        
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();}});
mDrawerList.addHeaderView(header);

Create abc.xml for header layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"  
 android:layout_width="match_parent"   
 android:layout_height="190dp"   
 android:background="@drawable/bgh"   
 android:orientation="vertical">

  <de.hdodenhof.circleimageview.CircleImageView
  xmlns:app="http://schemas.android.com/apk/res-auto"   
  android:id="@+id/profile_image"      
  android:layout_width="76dp"       
  android:layout_height="76dp"      
  android:layout_alignParentLeft="true"    
  android:layout_alignParentStart="true"
  android:layout_marginLeft="24dp"     
  android:layout_marginStart="24dp"     
  android:src="@drawable/p"       
  app:border_color="#FF000000" />

    <TextView    
   android:id="@+id/username"   
   android:layout_width="wrap_content"       
   android:layout_height="wrap_content"      
   android:layout_above="@+id/email"      
   android:layout_alignLeft="@+id/profile_image"   
   android:layout_alignStart="@+id/profile_image"    
   android:gravity="left"     
   android:paddingBottom="4dp"     
   android:text="Akash Bangad"      
   android:textColor="#FFF"     
   android:textSize="14sp"    
   android:textStyle="bold" />

   <TextView     
   android:id="@+id/email"    
   android:layout_width="wrap_content"    
   android:layout_height="wrap_content"     
   android:layout_alignLeft="@+id/username"     
   android:layout_alignParentBottom="true"      
   android:layout_alignStart="@+id/username"   
   android:layout_marginBottom="8dp"     
   android:gravity="left"    
   android:text="Akash.bangad93@gmail.com"    
   android:textColor="#fff"     
   android:textSize="14sp" />

</RelativeLayout>

Add this code in build.gradle
dependencies {

  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.android.support:appcompat-v7:22.2.0'  
  compile 'com.android.support:design:22.2.0'  
  compile 'de.hdodenhof:circleimageview:1.3.0'
}

Finally run and see your output

enter image description here 

Sunday, November 15, 2015

How to change Option menus background and Text color in android

Use this style  in your application  and get your change

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

    <!--To change the text styling of options menu items</item>-->  
    <item name="android:itemTextAppearance">@style/MyActionBar.MenuTextStyle</item>
    <!--To change the background of options menu-->  
    <item name="android:itemBackground">@color/orangein</item>
</style>

<style name="MyActionBar.MenuTextStyle" parent="style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/white</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">25sp</item>
</style>

Monday, November 9, 2015

Blocking a call without user intervention in android with an example

I was very much in search of the way in which we can control calls in Android and faced a lot of difficulties implementing it at the beginning. So I thought to share some knowledge about the same which I gained in the journey.
Now, let’s start.
First create a package in the ‘src’ folder in your project named com.android.internal.telephony and within that package create a file and copy paste the interface ITelephony(I’ve given the interface below) and save the file as ITelephony.aidl. When you compile the project you will get a corresponding java file for the ITelephony in the ‘gen’ folder.
Code for ITelephony.aidl:
package com.w7app.internal.telephony;
interface ITelephony {

 boolean endCall();

 void answerRingingCall();

 void silenceRinger();
}
com.android.internal.telephony is an internal hidden class in the Android Telephony framework. As com.android.internal.telephony is not a public class in the sdk, we use java reflections for retrieving the internal class’s methods.
Now let’s see the permissions needed in the Manifest file:
<uses-permission android:name=”android.permission.READ_PHONE_STATE”/>
<uses-permission android:name=”android.permission.MODIFY_PHONE_STATE”/>
<uses-permission android:name=”android.permission.CALL_PHONE”/>
Now let’s look at the XML file where I’ve added a checkbox enabling which would block the incoming calls.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
<CheckBox
 android:id="@+id/cbBlockAll"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Block all Calls" />
</LinearLayout>
First, we need to use a BroadcastReceiver which responds to the incoming call with action android.intent.action.PHONE_STATE  to detect the incoming call and also we need a PhoneStateListener  to listen to the call state and check whether the state is CALL_STATE_RINGINGIf yes, then end the call using endcall() method.
BroadcastReceiver CallBlocker;
To get the Telephony services,
TelephonyManager telephonyManager;
To get the ITelephony methods:
ITelephony telephonyService;
Now look at the code snippet below which blocks calls when the checkbox is enabled.
blockAll_cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 // TODO Auto-generated method stub
 CallBlocker =new BroadcastReceiver()
 {
 @Override
 public void onReceive(Context context, Intent intent) {
 // TODO Auto-generated method stub
 telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
 //Java Reflections
 Class c = null;
 try {
 c = Class.forName(telephonyManager.getClass().getName());
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 Method m = null;
 try {
 m = c.getDeclaredMethod("getITelephony");
 } catch (SecurityException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 m.setAccessible(true);
 try {
 telephonyService = (ITelephony)m.invoke(telephonyManager);
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 telephonyManager.listen(callBlockListener, PhoneStateListener.LISTEN_CALL_STATE);
 }//onReceive()
 PhoneStateListener callBlockListener = new PhoneStateListener()
 {
 public void onCallStateChanged(int state, String incomingNumber)
 {
 if(state==TelephonyManager.CALL_STATE_RINGING)
 {
 if(blockAll_cb.isChecked())
 {
 try {
 telephonyService.endCall();
 } catch (RemoteException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }
 }
 };
 };//BroadcastReceiver
 IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
 registerReceiver(CallBlocker, filter);
 }
 });
Here we use java reflections to get the instance of com.android .intenal.telephony class.
The code snippet is shown below:
Class c = null;
 try {
 c = Class.forName(telephonyManager.getClass().getName());
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 Method m = null;
 try {
 m = c.getDeclaredMethod("getITelephony");
 } catch (SecurityException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 m.setAccessible(true);
 try {
 telephonyService = (ITelephony)m.invoke(telephonyManager);
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
Now use the internal methods in the internal class to block calls as shown below:
Here endcall() is used to end a call without user intervention.
telephonyService.endCall();
Register the receiver as shown below:
IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
 registerReceiver(CallBlocker, filter);
We need to unregister the receiver after use. This is done in the onDestroy() callback.
protected void onDestroy() {
 // TODO Auto-generated method stub
 super.onDestroy();
 if (CallBlocker != null)
 {
 unregisterReceiver(CallBlocker);
 CallBlocker = null;
 }
 }
Now the whole code:
package com.w7app.mycallcontroller;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.android.internal.telephony.ITelephony;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MyCallControllerActivity extends Activity {
 /** Called when the activity is first created. */
 CheckBox blockAll_cb;//,blockcontacts_cb;
 BroadcastReceiver CallBlocker;
 TelephonyManager telephonyManager;
 ITelephony telephonyService;
@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 initviews();
 blockAll_cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 // TODO Auto-generated method stub
 CallBlocker =new BroadcastReceiver()
 {
 @Override
 public void onReceive(Context context, Intent intent) {
 // TODO Auto-generated method stub
 telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
 //Java Reflections
 Class c = null;
 try {
 c = Class.forName(telephonyManager.getClass().getName());
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 Method m = null;
 try {
 m = c.getDeclaredMethod("getITelephony");
 } catch (SecurityException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 m.setAccessible(true);
 try {
 telephonyService = (ITelephony)m.invoke(telephonyManager);
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 telephonyManager.listen(callBlockListener, PhoneStateListener.LISTEN_CALL_STATE);
 }//onReceive()
 PhoneStateListener callBlockListener = new PhoneStateListener()
 {
 public void onCallStateChanged(int state, String incomingNumber)
 {
 if(state==TelephonyManager.CALL_STATE_RINGING)
 {
 if(blockAll_cb.isChecked())
 {
 try {
 telephonyService.endCall();
 } catch (RemoteException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }
 }
 };
 };//BroadcastReceiver
 IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
 registerReceiver(CallBlocker, filter);
 }
 });
}
 public void initviews()
 {
 blockAll_cb=(CheckBox)findViewById(R.id.cbBlockAll);
 //blockcontacts_cb=(CheckBox)findViewById(R.id.cbBlockContacts);
 }
 @Override
 protected void onDestroy() {
 // TODO Auto-generated method stub
 super.onDestroy();
 if (CallBlocker != null)
 {
 unregisterReceiver(CallBlocker);
 CallBlocker = null;
 }
 }
}
Now the Screen Shots:
Hope this helped :) Happy Coding :)

Toggle Button in android

Today I thought of posting something which I came across recently. Toggle button.
As its name suggests, it toggles or switches between two states namely, ‘on’ and ‘off’. It is similar to a radio button.
Now, let’s see how this is implemented. I’ve given a simple example below to make you understand Togglebutton easily.
Firstly let’s go to our UI part. Inside our XML file we can add ToggleButton widget and set its attributes.
The XML code is shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
          <ToggleButton
              android:id="@+id/tglbtn"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textOn="ON"
              android:textOff="OFF"
              />
</LinearLayout>
The attribute   android:textOn=”ON” means  that the text on the button is  ‘ON’ when the it is in the ‘on’ state and   android:textOff=”OFF” specifies that the text on the button is ‘OFF’ when it is in the ‘off’ state.
Next step.
When the user clicks the button some action has to be done.
Here, I’ve given a Toast when the user clicks the button.
Here is the code. Just have a look.
package com.w7app.mytogglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MyToggleButtonActivity extends Activity {
    /** Called when the activity is first created. */
    ToggleButton toggle;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        toggle=(ToggleButton)findViewById(R.id.tglbtn);
        toggle.setOnClickListener(new OnClickListener() {
              public void onClick(View v) {
               // TODO Auto-generated method stub
              if(toggle.isChecked())
              {
               Toast.makeText(getApplicationContext(), "The state is changed to on", Toast.LENGTH_LONG).show();
               }
                else
                {
                  Toast.makeText(getApplicationContext(), "The state is changed to off", Toast.LENGTH_LONG).show();
                 }
                 }
                 });
    }
}
The Output looks like this:
When checked:
When Unchecked:

How to change the usual icon of your application in Android?

Usually when you run your application in your emulator, you may see the usual ic_launcher image as its icon. You can, of course change the icon of your application with the image you want. For that make these changes in the Manifest file.
Within application tag
<application
android:icon=“@drawable/flower” >
</application>
Here, flower is an image with extension .png(You can use images with extension .jpg, .gif, .png, .bmp, or .webp)
This is how the icon looks in your emulator:
Check the icon of the application named Deepthi in the picture below.
I just thought of blogging about this as I was curious about how the usual icon is changed at the beginning. Hope this post  was useful.

Tuesday, November 3, 2015

how to Link web page from android

Use this bellow code in xml layout

<TextView   
 android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:autoLink="web"   
  android:textSize="15sp"  
  android:layout_marginTop="10dp"  
  android:layout_centerHorizontal="true" 
  android:text="google.com"   
  android:textColor="#000"   
  android:layout_below="@+id/textView"  
  android:textStyle="italic"/>




Use this bellow code in android manifest


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