Monday, 31 July 2017

Android Change Language Programmatically

If You Want To Change Language Then You Want To Make Second Directory Of Value With Language Code And You Need To Diffine Your Hindi Text And Some Classes



#ref-menu

1) LocaleHelper.Java

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }

}


2) MainApplication.Java

import android.app.Application;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;

public class MainApplication extends AppCompatActivity {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
    }

}


3) MainActivity.Java

import android.content.Context;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

   
    TextView mTitleTextView;
  
    TextView mDescTextView;

    TextView mAboutTextView; 

    Button mToTRButton;
   
    Button mToENButton;

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

        mTitleTextView = (TextView)findViewById(R.id.titleTextView);
        mDescTextView = (TextView)findViewById(R.id.descTextView);
        mAboutTextView = (TextView)findViewById(R.id.aboutTextView);
        mToTRButton = (Button) findViewById(R.id.toHIButton);
        mToENButton = (Button)findViewById(R.id.toENButton);

        mToHIButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateViews("hi");
            }
        });

        mToENButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateViews("en");
            }
        });

        setTitle(getString(R.string.main_activity_toolbar_title));

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base));
    }



    private void updateViews(String languageCode) {
        Context context = LocaleHelper.setLocale(this, languageCode);
        Resources resources = context.getResources();

 mTitleTextView.setText(resources.getString(R.string.main_activity_title));
 mDescTextView.setText(resources.getString(R.string.main_activity_desc));
 mAboutTextView.setText(resources.getString(R.string.main_activity_about));
        mToHIButton.setText(resources.getString(R.string.main_activity_to_tr_button));
        mToENButton.setText(resources.getString(R.string.main_activity_to_en_button));

        setTitle(resources.getString(R.string.main_activity_toolbar_title));
    }

}


4) Second Directory Of Value-hi

value-hi Containt Only One File "String.xml"

Normal Sring.xml File In Value Folder

<resources>
    <string name="app_name">Change Language</string>

    <string name="main_activity_title">This title is in English</string>
    <string name="main_activity_desc">This is the description text in English.</string>
    <string name="main_activity_about">This is about text in English.</string>
    <string name="main_activity_to_tr_button">हिंदी</string>
    <string name="main_activity_to_en_button">English</string>
    <string name="main_activity_toolbar_title">Title in English</string>

</resources>

Our value-hi File In Value Folder

<resources>
    <string name="app_name">भाषा बदलो</string>
    <string name="main_activity_title">यह शीर्षक हिंदी में है</string>
    <string name="main_activity_desc">यह हिंदी में वर्णन टेक्स्ट है</string>
    <string name="main_activity_about">यह हिंदी में पाठ के बारे में है</string>
    <string name="main_activity_to_tr_button">Turkish</string>
    <string name="main_activity_to_en_button">English</string>
    <string name="main_activity_toolbar_title">हिंदी में शीर्षक</string>

</resources>


Note : This Is Hindi Title You Can Change Your Language As Per Need


Download Source Code : 
https://drive.google.com/open?id=0B7p5TzrAq_QgNXVRNXZGdmdqbkk

Thursday, 13 July 2017

Android Receive SMS In TextView




1)  Add This Line In AndroidManifest.xml


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


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

In Application :
<receiver android:name=".SimpleSmsReciever">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED">
                </action>
            </intent-filter>
  </receiver>

Like :

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">

   </activity>

     <activity android:name=".MainActivity">
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
   </activity>

   <receiver android:name=".SimpleSmsReciever">
         <intent-filter>
             <action android:name="android.provider.Telephony.SMS_RECEIVED">
             </action>
         </intent-filter>
   </receiver>

/application>

</manifest>




2) SimpleSmsReciever BroadcastReceiver Class

import android.content.*;
import android.os.Bundle;
import android.telephony.*;
import android.util.Log;
import android.widget.Toast;

public class SimpleSmsReciever extends BroadcastReceiver {

    private static final String TAG = "Message recieved";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle pudsBundle = intent.getExtras();
        Object[] pdus = (Object[]) pudsBundle.get("pdus");
        SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);
      
        // Start Application's  MainActivty activity

        Intent smsIntent=new Intent(context,MainActivity.class);

        smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        smsIntent.putExtra("MessageNumber", messages.getOriginatingAddress());

        smsIntent.putExtra("Message", messages.getMessageBody());

        context.startActivity(smsIntent);

       // Get the Sender Message : messages.getMessageBody()
      // Get the SenderNumber messages.getOriginatingAddress()
      
        Toast.makeText(context, "SMS Received From :"+messages.getOriginatingAddress()+"\n"+ messages.getMessageBody(), Toast.LENGTH_LONG).show();
    }
}

3) MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="smsread.sms.SMS_Receive">

<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="75dp"
        android:text="SMS Receiver"
        android:textColor="#000000"
        android:textStyle="bold"
        android:textSize="20dp"/>

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="34dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/address"
        android:layout_alignStart="@+id/address"
        android:layout_below="@+id/address"
        android:layout_marginTop="25dp"
        android:text="TextView" />

</RelativeLayout>


4) MainActivity.java


import android.content.Intent;

import android.content.pm.PackageManager;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


    Button msg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms__receive);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String address = extras.getString("MessageNumber");
            String message = extras.getString("Message");
            TextView addressField = (TextView) findViewById(R.id.address);
            TextView messageField = (TextView) findViewById(R.id.message);
            addressField.setText("Message From : " +address);
            messageField.setText("Messsage : "+message);
        }
        msg = (Button)findViewById(R.id.btn_msg);
        msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        });
    }

}


Wednesday, 5 July 2017

Android Read SMS And Show In ListView









Add Two Line In AndroidManifest.xml


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

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

Drawable Resource File For Rectangle Shape

rectangle_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Background Color -->
    <solid android:color="#ffffff" />

    <!-- Border Color -->
    <stroke android:width="5dp" android:color="#0b96e5" />

    <!-- Round Corners -->
    <corners android:radius="5dp" />


</shape>



MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="smsread.sms.MainActivity"
    android:padding="10dp">

    <!--   ListVivew    -->
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rectangle_style"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp"
        android:id="@+id/SMSList" />

</LinearLayout>


SMS Receiver Class

SMSReceiver.java

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;


// Todo : BroadcastReceiver Class To Receive And Read SMS

public class SMSBReceiver extends BroadcastReceiver{
    public static final String SMS_BUNDLE = "pdus";

    public void onReceive(Context context, Intent intent) {
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) {
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
            String smsMessageStr = "";
            for (int i = 0; i < sms.length; ++i) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

                String smsBody = smsMessage.getMessageBody().toString();
                String address = smsMessage.getOriginatingAddress();

                smsMessageStr += "SMS From: " + address + "\n";
                smsMessageStr += smsBody + "\n";
            }
            Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

            //this will update the UI with message
            MainActivity inst = MainActivity.instance();
            inst.updateList(smsMessageStr);
        }
    }
}


MainActivity.java

import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static MainActivity inst;
    ArrayList<String> smsMessagesList = new ArrayList<String>();
    ListView smsListView;
    ArrayAdapter arrayAdapter;

    public static MainActivity instance() {
        return inst;
    }
    @Override
    public void onStart() {
        super.onStart();
        inst = this;
    }


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

        smsListView = (ListView) findViewById(R.id.SMSList);

        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
        smsListView.setAdapter(arrayAdapter);
     

        // Add SMS Read Permision At Runtime
        // Todo : If Permission Is Not GRANTED
        if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {

            // Todo : If Permission Granted Then Show SMS
            refreshSmsInbox();

        } else {
            // Todo : Then Set Permission
            final int REQUEST_CODE_ASK_PERMISSIONS = 123;
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{"android.permission.READ_SMS"}, REQUEST_CODE_ASK_PERMISSIONS);
        }

     


    }
    public void refreshSmsInbox() {
        ContentResolver contentResolver = getContentResolver();
        Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
        int indexBody = smsInboxCursor.getColumnIndex("body");
        int indexAddress = smsInboxCursor.getColumnIndex("address");
        if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
        arrayAdapter.clear();
        do {
            String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                    "\n" + smsInboxCursor.getString(indexBody) + "\n";
            arrayAdapter.add(str);
        } while (smsInboxCursor.moveToNext());
    }

    public void updateList(final String smsMessage) {
        arrayAdapter.insert(smsMessage, 0);
        arrayAdapter.notifyDataSetChanged();
    }

    public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
        try {
            String[] smsMessages = smsMessagesList.get(pos).split("\n");
            String address = smsMessages[0];
            String smsMessage = "";
            for (int i = 1; i < smsMessages.length; ++i) {
                smsMessage += smsMessages[i];
            }

            String smsMessageStr = address + "\n";
            smsMessageStr += smsMessage;
            Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Todo : Thanks For Watching...
    }

Monday, 3 July 2017

Android Fragment Example

A Fragment is a piece of an application's user interface or
 behavior that can be placed in an Activity.
 Interaction with fragments is done through
 FragmentManager, which can be obtained via
 Activity.getFragmentManager() and Fragment.getFragmentManager().


The Fragment class can be used many ways to achieve a wide variety 
of results. In its core, it represents a particular operation or i-
nterface that is running within a larger Activity. A Fragment is 
closely tied to the Activity it is in, and can not be used apart
from one.Though Fragment defines  its own lifecycle, that 
lifecycle  is dependent on its activity: if the activity is 
stopped, no fragments inside of it can be started; 
when the activity is destroyed, all fragments will be destroyed.
   

 
Source Code : 

MainActivity.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="sabziapp.ibridge.com.fregment.MainActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fregment 1"
            android:id="@+id/btn_freg1"
            android:textAllCaps="false"
            android:layout_marginLeft="45dp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fregment 2"
            android:id="@+id/btn_freg2"
            android:textAllCaps="false"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fregment 3"
            android:id="@+id/btn_freg3"
            android:textAllCaps="false"/>
    </LinearLayout>

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/change_frame"
       android:orientation="vertical"/>

</LinearLayout>


MainActivity.java



import android.app.FragmentManager;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import layout.FragmentOne;
import layout.FragmentThree;
import layout.FragmentTwo;

public class MainActivity extends AppCompatActivity {
    Button btn_freg1, btn_freg2, btn_freg3;

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

        // get the reference of Button's        btn_freg1 = (Button) findViewById(R.id.btn_freg1);
        btn_freg2 = (Button) findViewById(R.id.btn_freg2);
        btn_freg3 = (Button) findViewById(R.id.btn_freg3);

        btn_freg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFragment(new FragmentOne());
            }
        });

        btn_freg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFragment(new FragmentTwo());
            }
        });

        btn_freg3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFragment(new FragmentThree());
            }
        });


    }

    // loadFragment Function for Load fragment activity

    private void loadFragment(Fragment fr) {

        // create a FragmentManager        FragmentManager fm = getFragmentManager();

        // create a FragmentTransaction to begin the transaction and replace the Fragment       
       android.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();

        // replace the FrameLayout with new Fragment        
        fragmentTransaction.replace(R.id.change_frame, fr);
        fragmentTransaction.commit(); // save the changes    }
}


FragmentOne.xml



<FrameLayout 
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="layout.FragmentOne">

    <!-- TODO: This Is  fragment layout -->   
 <ImageView        
android:layout_width="match_parent"        
android:layout_height="match_parent"       
android:background="@drawable/your_Iamge_Path"/>


</FrameLayout>



FragmentOne.java



import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import sabziapp.ibridge.com.fregment.R;

public class FragmentOne extends Fragment {

private OnFragmentInteractionListener mListener;


  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
 {
  // Inflate the layout for this fragment      
  return inflater.inflate(R.layout.fragment_fragment_one, container, false
 }


public interface OnFragmentInteractionListener {
   // TODO: Update argument type and name       
   void onFragmentInteraction(Uri uri);
 }
}


FragmentTwo And Three Are Same

Download Source Code :
https://drive.google.com/file/d/0B7p5TzrAq_QgQjZwUTJieUlZQUk/view?usp=sharing


Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file     implementation 'com.google.android.gms:play-services-location:18.0.0' 2. Add this p...