Pages

Monday, April 21, 2014

How to get MNC(mobile network code) and MCC(Mobile country code) in android?

Hello Friends, In this post M writing code for getting Mobile network code(MNC) and Mobile country code(MCC) in android. I using TelephonyManager class to getting MNC and MCC. No need any permission for getting this.

A mobile network code (MNC) is used in combination with a mobile country code (MCC) (also known as a "MCC / MNC tuple") to uniquely identify a mobile phone operator/carrier using the GSM/LTE, CDMA, iDEN, TETRA and UMTS public land mobile networks and some satellite mobile networks. SeeHere


1. MainActivity.java class

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class MainActivity extends Activity 
{

 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  TextView txta = (TextView) findViewById(R.id.textView1);
  
  TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     String networkOperator = tel.getNetworkOperator();
     int mcc = 0, mnc = 0;
     if (networkOperator != null) {
         mcc = Integer.parseInt(networkOperator.substring(0, 3));
         mnc = Integer.parseInt(networkOperator.substring(3));
     }
     txta.setText("MCC : "+mcc+"\n"
       + "MNC : "+mnc);
 }
}


2. activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
         android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example code for getting Mobile network code(MNC) and mobile country code (MCC)"
        android:textSize="14sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="" />

</LinearLayout>


3. ScreenShot



Download APK file Here
enjoy :)
Thank you. 

Tuesday, April 15, 2014

How to get screen height, width and density of the android device?


Hello Friends, in this post, I write code for getting Screen Density and Screen DensityDPI, width and height of the android device using DisplayMetrics

DisplayMetrics
A structure describing general information about a display, such as its size, density, and font scaling.
To access the DisplayMetrics members, initialize an object like this:

 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);

density
The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).

densityDpi
The screen density expressed as dots-per-inch. May be either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH.

scaledDensity
A scaling factor for fonts displayed on the display. This is the same as density, except that it may be adjusted in smaller increments at runtime based on a user preference for the font size.

heightPixels
The absolute height of the display in pixels.

widthPixels
The absolute width of the display in pixels.


1. MainActivity.java Class

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;

public class MainActivity extends Activity 
{
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  TextView txta = (TextView) findViewById(R.id.textView);

  DisplayMetrics metrics = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(metrics);
  float screenDensity = metrics.density;
  int screenDensityDPI = metrics.densityDpi;
  float screenscaledDensity = metrics.scaledDensity;
  int width = metrics.widthPixels;
  int Height = metrics.heightPixels;

  txta.setText("Screen Density=" + screenDensity + "\n"
    + "Screen DensityDPI=" + screenDensityDPI + "\n"
    + "Screen Scaled DensityDPI=" + screenscaledDensity + "\n"
    + "Height="+ Height + "\n"
    + "Width=" + width);
 }
}


2. activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="14sp"
        android:textStyle="bold" />

</LinearLayout>


3. Screenshot(HTC Desire X)





Thursday, April 10, 2014

Contains method in an ArrayList with custom class in android?

In this post, If we use Custom class in ArrayList<> and if want to check item already in ArrayList<> or not using Contain method.

Contain Method generally match all variable of the class See.

Now I write a code for check specific variable value already contain in ArrayList<> or not.
Just we need @Override equale() and hashcode() Method in our custom class. like below.

I have created one custom class name is student. While we call contains Method then check only Student first Name. if we want to check multiple variable then we can add like below in @Override equale() and hashcode() Method.

1. Student.java

public class Student 
{
 private int s_rollNo = 0;
 private String s_fname = "";
 private String s_lname = "";
 private String s_contactNumber = "";
 
 public Student(int rollNo, String firstName, String lastName, String contactNo) 
 {
  this.setS_rollNo(rollNo);
  this.setS_fname(firstName);
  this.setS_lname(lastName);
  this.setS_contactNumber(contactNo);
 }
 
 public Student() 
 { 
 }

 public int getS_rollNo() {
  return s_rollNo;
 }
 public void setS_rollNo(int s_rollNo) {
  this.s_rollNo = s_rollNo;
 }
 public String getS_fname() {
  return s_fname;
 }
 public void setS_fname(String s_fname) {
  this.s_fname = s_fname;
 }
 public String getS_lname() {
  return s_lname;
 }
 public void setS_lname(String s_lname) {
  this.s_lname = s_lname;
 }
 public String getS_contactNumber() {
  return s_contactNumber;
 }
 public void setS_contactNumber(String s_contactNumber) {
  this.s_contactNumber = s_contactNumber;
 }
 
 /*
 * Here Equals method code perform when we try use contain method and the check only Student first name
 * Also we can check multiple variables like below
 */
 @Override
 public boolean equals(Object object) 
 {
  boolean sameSame = false;

  if (object != null && object instanceof Student)
  {
   //for match only student rollno
   //sameSame = this.s_rollNo == ((Student) object).s_rollNo;
   
   //for match only student first name
   sameSame = this.s_fname == ((Student) object).s_fname;
   
   // also we can match both paramater here. if required 
  }

  return sameSame;
 }
 
 @Override
 public int hashCode() 
 {
  int result = 17;
  
  //hash code for checking rollno
  //result = 31 * result + (this.s_rollNo == 0 ? 0 : this.s_rollNo);
  
  //hash code for checking fname
  result = 31 * result + (this.s_fname == null ? 0 : this.s_fname.hashCode());
  
  return result;
 }
}


2. Activity class is MainActivity.java  and I have some dummy data for testing

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity 
{
 ArrayList arrStudents = new ArrayList();

 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  TextView txt = (TextView) findViewById(R.id.textView1);
 
  // here add some data in ArrayList herer
  arrStudents.add(new Student(1,"Ajay","asdasd","3215461321"));
  arrStudents.add(new Student(2,"Rahul","ghdtd","1231231231"));
  arrStudents.add(new Student(3,"Jigar","fg","9998468465"));
  arrStudents.add(new Student(4,"Megha","ldZ","1212712545"));
  arrStudents.add(new Student(5,"Ravi","eyr","1224575131"));
  arrStudents.add(new Student(6,"Rajesh","asd","3416461213"));

  // create new student for check in Arraylist Student first Name contain or not
  Student std = new Student(8,"Rajesh","adfgdfg","123123123");
  //Student std = new Student(4123,"Rajesh","123123","123123123");

  if(arrStudents.contains(std))
  {
   txt.setText(std.toString() +"\n\nNew student First Name already contain in ArrayList index no: "+arrStudents.indexOf(std));
  }
  else 
  {
   arrStudents.contains(std);
   txt.setText(std.toString() +"\n\nNew student successfully add");
  }
 }
}


3. activity_main.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example code for check Student First name in arraylist Using contains method"
        android:textSize="14sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="SampleText" />

</LinearLayout>


4. ScreenShot




This code working Perfectly. Enjoy :) Thank you..


Other Post

- Sorting ArrayList (String ArrayList and custom class)


Wednesday, April 9, 2014

DatePickerDialog in android DialogFragment?

This post I write code for display DatePickerDialog using FragmentDialog.

Generally we display DatePickerDialog using  "onCreateDialog (int id)" Method like below.

//.....
static final int DATE_DIALOG_ID = 999;

//
//

call below code to display DatePickerDialog
showDialog(DATE_DIALOG_ID);

//
//

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
       // set date picker as current date
       return new DatePickerDialog(this, datePickerListener, year, month, day);
    }
   return null;
}
//
//

//we use DatePickerDialog.OnDateSetListener Listner to get selected date like below
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener()
{
    public void onDateSet(DatePicker view, int selectedYear,  int selectedMonth, int selectedDay) {
    }
};




But now "Dialog onCreateDialog(int id)" method deprecated in API level 8. 
So now we can use DialogFragment to display DatePickerDialog and this code working to all android version. I finding DatePickerDialogFragmetn.java class from here.


1. Copy DatePickerDialogFragment.java in your application package.

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.widget.DatePicker;


public class DatePickerDialogFragment extends DialogFragment 
{    
    public static final String YEAR = "Year";
    public static final String MONTH = "Month";
    public static final String DATE = "Day";
    
    private OnDateSetListener mListener;
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mListener = (OnDateSetListener) activity;
    }
    
    @Override
    public void onDetach() {
        this.mListener = null;
        super.onDetach();
    }
    
    @TargetApi(11)
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) 
    {
        Bundle b = getArguments();
        int y = b.getInt(YEAR);
        int m = b.getInt(MONTH);
        int d = b.getInt(DATE);
            
        final DatePickerDialog picker = new DatePickerDialog(getActivity(), getConstructorListener(), y, m, d);
        
        if (hasJellyBeanAndAbove()) {
            picker.setButton(DialogInterface.BUTTON_POSITIVE, 
                    getActivity().getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DatePicker dp = picker.getDatePicker();
                    mListener.onDateSet(dp, 
                            dp.getYear(), dp.getMonth(), dp.getDayOfMonth());
                }
            });
            picker.setButton(DialogInterface.BUTTON_NEGATIVE,
                    getActivity().getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {}
            });
        }
        return picker;
    }
    
    private static boolean hasJellyBeanAndAbove() 
    {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }
    
    private OnDateSetListener getConstructorListener() {
        return hasJellyBeanAndAbove() ? null : mListener;
    }
}


2. Create MainActivity.java

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.DialogFragment;
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;

public class MainActivity extends Activity implements OnDateSetListener
{
 private TextView tvDisplayDate;
 private Button btnChangeDate;

 private int year;
 private int month;
 private int day;

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  setCurrentDate();
  button_clickEvent();
 }

 // display current date
 public void setCurrentDate() 
 {
  tvDisplayDate = (TextView) findViewById(R.id.tvDate);
  
  final Calendar c = Calendar.getInstance();
  year = c.get(Calendar.YEAR);
  month = c.get(Calendar.MONTH);
  day = c.get(Calendar.DAY_OF_MONTH);

  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(c.getTime());
  
  tvDisplayDate.setText(s);  
 }

 public void button_clickEvent() 
 {
  btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
  btnChangeDate.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    Bundle b = new Bundle();
    b.putInt(DatePickerDialogFragment.YEAR, year);
    b.putInt(DatePickerDialogFragment.MONTH, month);
    b.putInt(DatePickerDialogFragment.DATE, day);
    DialogFragment picker = new DatePickerDialogFragment();
    picker.setArguments(b);
    picker.show(getFragmentManager(), "fragment_date_picker");
   }
  });
 }
 
 @Override
 public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) 
 {
  this.year = year;
  this.month = monthOfYear;
  this.day = dayOfMonth;
  
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.YEAR, year);
  calendar.set(Calendar.MONTH, monthOfYear);
  calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
  
  Format formatter = new SimpleDateFormat("dd-MM-yyyy");
  String s = formatter.format(calendar.getTime());
  
  tvDisplayDate.setText(s);
 }
}


3. activity_main.xml

<?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:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Current Date (dd-MM-yyyy): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="asdasd"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Change Date" />

</LinearLayout>


4. ScreenShot





Download APK file Here

Reference link for new version DatePickerDialog issues.

- Jelly Bean DatePickerDialog — is there a way to cancel?
- android-android-4-1-emulator-invoking-ondateset-twice-from-datepicker-dialog