Tuesday, 28 November 2017

Creating a Simple Pie Chart in Android



1) build.gradle( Module:app )  Code


Please add below following repositories and dependencies code to your build.gradle( Module:app ) file and You don’t need to download manually the whole library because after adding below code it will automatically download and install the Mp Android Library into your project.

dependencies {
 compile 'com.github.PhilJay:MPAndroidChart:v2.2.4'
}

repositories {
 maven { url "https://jitpack.io" }
}


2) XML Code

<?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="payprocess.charts.PChart">

    <com.github.mikephil.charting.charts.PieChart
        android:layout_marginTop="20dp"
        android:id="@+id/piechart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

3) Java Code

public class PChart extends AppCompatActivity {
    PieChart mChart;
    private String[] xValues = {"Data 1", "Data 2", "Data 3"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pchart);

        mChart = (PieChart)findViewById(R.id.piechart);

        ArrayList<Entry> entries = new ArrayList<>();
        entries.add(new Entry(40, 0));
        entries.add(new Entry(11, 0));
        entries.add(new Entry(2, 0));

        PieDataSet dataSet =  new PieDataSet(entries, "");
        PieData data = new PieData(xValues, dataSet);

        dataSet.setColors(new int[]{Color.YELLOW, Color.CYAN, Color.GREEN});
        dataSet.setSliceSpace(5f);
        dataSet.setValueTextSize(14f);
        mChart.setUsePercentValues(true);
        mChart.setDrawHoleEnabled(false);
        mChart.setData(data);
        mChart.invalidate();

    }
}

Monday, 27 November 2017

Creating a Simple Donut Chart in Android



1) 

Please add below following repositories and dependencies code to your build.gradle( Module:app ) file and You don’t need to download manually the whole library because after adding below code it will automatically download and install the Mp Android Library into your project.

dependencies {
 compile 'com.github.PhilJay:MPAndroidChart:v2.2.4'
}

repositories {
 maven { url "https://jitpack.io" }
}

2) XML Code

<?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="payprocess.charts.Main2Activity">

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

            <com.github.mikephil.charting.charts.PieChart
                android:id="@+id/piechart"
                android:layout_width="match_parent"
                android:layout_height="230dp" />

    </HorizontalScrollView>

</RelativeLayout> 


3) Java Code

public class MainActivity extends AppCompatActivity {

    PieChart mChart;


    private int[] yValues  = {21, 2, 2};
    private String[] xValues = {"Present Days", "Absents", "Leaves"};

    public static  final int[] MY_COLORS = {
            Color.rgb(84,124,101), Color.rgb(64,64,64), Color.rgb(153,19,0),
            Color.rgb(38,40,53), Color.rgb(215,60,55)
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      

        mChart = (PieChart)findViewById(R.id.piechart);
        mChart.setDescription("");

        mChart.setRotationEnabled(true);

        mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {

            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
                // display msg when value selected
                if (e == null)
                    return;

                Toast.makeText(MainActivity.this,
                        xValues[e.getXIndex()] + " is " + e.getVal() + "", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected() {

            }
        });

        // setting sample Data for Pie Chart
        setDataForPieChart();


    }

    public void setDataForPieChart() {
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();

        for (int i = 0; i < yValues.length; i++)
            yVals1.add(new Entry(yValues[i], i));

        ArrayList<String> xVals = new ArrayList<String>();

        for (int i = 0; i < xValues.length; i++)
            xVals.add(xValues[i]);

        // create pieDataSet
        PieDataSet dataSet = new PieDataSet(yVals1, "");
        dataSet.setSliceSpace(5f);
        dataSet.setSelectionShift(5);

        // adding colors
        ArrayList<Integer> colors = new ArrayList<Integer>();

        // Added My Own colors
        for (int c : MY_COLORS)
            colors.add(c);


        dataSet.setColors(colors);

        //  create pie data object and set xValues and yValues and set it to the pieChart
        PieData data = new PieData(xVals, dataSet);
        //   data.setValueFormatter(new DefaultValueFormatter());
        //   data.setValueFormatter(new PercentFormatter());

        data.setValueFormatter(new MainActivity.MyValueFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);

        mChart.setData(data);

        // undo all highlights
        mChart.highlightValues(null);

        // refresh/update pie chart
        mChart.invalidate();

        // animate piechart
        mChart.animateXY(1400, 1400);


        // Legends to show on bottom of the graph
        Legend l = mChart.getLegend();
        l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        l.setXEntrySpace(7);
        l.setYEntrySpace(5);
    }

    public class MyValueFormatter implements ValueFormatter {

        private DecimalFormat mFormat;

        public MyValueFormatter() {
            mFormat = new DecimalFormat("###,###,##0"); // use one decimal if needed
        }

        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
            // write your logic here
            return mFormat.format(value) + ""; // e.g. append a dollar-sign
        }
    }
   
  

}



Friday, 3 November 2017

Creating a Simple Bar Graph for your Android Application

#ref-menu



1) 

Please add below following repositories and dependencies code to your build.gradle( Module:app ) file and You don’t need to download manually the whole library because after adding below code it will automatically download and install the Mp Android Library into your project.

dependencies {
 compile 'com.github.PhilJay:MPAndroidChart:v2.2.4'
}

repositories {
 maven { url "https://jitpack.io" }
}


2) Code Of XML File Layout

<?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="payprocess.charts.MainActivity">

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/barchart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</RelativeLayout>

3) Code Of Java File 

package payprocess.charts;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("SetJavaScriptEnabled")

public class MainActivity extends AppCompatActivity {


    ArrayList<BarEntry> BARENTRY ;
    ArrayList<String> BarEntryLabels ;
    BarDataSet Bardataset ;
    BarData BARDATA ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BarChart barChart = (BarChart) findViewById(R.id.barchart);

        BARENTRY = new ArrayList<>();

        BarEntryLabels = new ArrayList<String>();

        AddValuesToBARENTRY();

        AddValuesToBarEntryLabels();

        Bardataset = new BarDataSet(BARENTRY, "Projects");

        BARDATA = new BarData(BarEntryLabels, Bardataset);

        Bardataset.setColors(ColorTemplate.COLORFUL_COLORS);

        barChart.setData(BARDATA);

        barChart.animateY(3000);


    }
    public void AddValuesToBARENTRY(){

        BARENTRY.add(new BarEntry(2f, 0));
        BARENTRY.add(new BarEntry(4f, 1));
        BARENTRY.add(new BarEntry(6f, 2));
        BARENTRY.add(new BarEntry(8f, 3));
        BARENTRY.add(new BarEntry(7f, 4));
        BARENTRY.add(new BarEntry(3f, 5));

    }
    public void AddValuesToBarEntryLabels(){

        BarEntryLabels.add("January");
        BarEntryLabels.add("February");
        BarEntryLabels.add("March");
        BarEntryLabels.add("April");
        BarEntryLabels.add("May");
        BarEntryLabels.add("June");

    }


}


Thursday, 12 October 2017

Android Volley Get JSON Data

 

1) Import Dependencies

 The easiest way to add Volley to your project is to add the following dependency to your app's build.gradle file:

dependencies {
    ...
    compile 'com.android.volley:volley:1.0.0'
}

2) Add Internet Permission On Manifest File 

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

3) Main Activity Design

<?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="com.example.ismails.myapplication.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="JSON Data Here"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="104dp"
        android:id="@+id/jsonData"
        android:textColor="#000000"
        android:textStyle="bold"
        android:textSize="20dp"
        android:textAlignment="center"/>

    <Button
        android:id="@+id/btn_json"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="79dp"
        android:text="Get JSON Data" />


</RelativeLayout>


3) M
ain Activity Java

public class MainActivity extends AppCompatActivity {

    // Todo : Will show the string "data" that holds the results
    TextView results;
    // Todo :  URL of object to be parsed
    String JsonURL = "http://jsonplaceholder.typicode.com/todos/1";

    // Todo : Defining the Volley request queue that handles the URL request concurrently
    RequestQueue requestQueue;

    Button btn;

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

        // Todo :  Creates the Volley request queue

        requestQueue = Volley.newRequestQueue(this);

        // Todo : Casts results into the TextView And Button found within the main layout XML with id jsonData

        results = (TextView) findViewById(R.id.jsonData);
        btn = (Button)findViewById(R.id.btn_json);

            /*Todo : Set OnClick To Get JSON Data In TextView*/

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Todo : Creating the JsonObjectRequest class called obreq, passing required parameters:
                // Todo : GET is used to fetch data from the server, JsonURL is the URL to be fetched from.

                JsonObjectRequest jsObjRequest = new JsonObjectRequest
                        (Request.Method.GET, JsonURL, null,

                                new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {

                                /*Todo : Assign Json Value In TextView*/

                                results.setText("JSON Data Is \n: " + response.toString());
                            }
                        }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // TODO Auto-generated method stub

                            }
                        });

                // Todo : Adds the JSON object request "jsObjRequest" to the request queue

                requestQueue.add(jsObjRequest);
            }
        });


    }

}


Monday, 25 September 2017

Android Add Images On Spinner











1) 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="spinnerimage.spinnerimage.MainActivity">


    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="88dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="@drawable/spinner"/>

</RelativeLayout>

2) MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        ArrayList<ItemData> list=new ArrayList<>();
        list.add(new ItemData("Bank",R.drawable.bank_icon));
        list.add(new ItemData("Entertainment",R.drawable.entertainment_icon));
        list.add(new ItemData("Fashion",R.drawable.fashion_icon));
        list.add(new ItemData("Govt",R.drawable.govt_icon));
        Spinner sp=(Spinner)findViewById(R.id.spinner);
        SpinnerAdapter adapter=new SpinnerAdapter(this,
                R.layout.spinner_layout,R.id.txt,list);
        sp.setAdapter(adapter);
    }
}

3) ItemData.java

public class ItemData {
    String text;
    Integer imageId;
    public ItemData(String text, Integer imageId){
        this.text=text;
        this.imageId=imageId;
    }

    public String getText(){
        return text;
    }

    public Integer getImageId(){
        return imageId;
    }
}

4) SpinnerAdapter.java

public class SpinnerAdapter extends ArrayAdapter<ItemData> {
    int groupid;
    Activity context;
    ArrayList<ItemData> list;
    LayoutInflater inflater;
    public SpinnerAdapter(Activity context, int groupid, int id, ArrayList<ItemData>
            list){
        super(context,id,list);
        this.list=list;
        inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.groupid=groupid;
    }

    public View getView(int position, View convertView, ViewGroup parent ){
        View itemView=inflater.inflate(groupid,parent,false);
        ImageView imageView=(ImageView)itemView.findViewById(R.id.img);
        imageView.setImageResource(list.get(position).getImageId());
        TextView textView=(TextView)itemView.findViewById(R.id.txt);
        textView.setText(list.get(position).getText());
        return itemView;
    }

    public View getDropDownView(int position, View convertView, ViewGroup
            parent){
        return getView(position,convertView,parent);

    }
}

Thursday, 14 September 2017

Android Recyclerview Cards With Images In Gridview Style


#ref-menu

1)Cards.Java

class Cards {
    Integer Img;
    String category;


    public Cards(Integer img, String category ) {

        Img = img;
        this.category = category;
    }



    public String getCategory() {
        return category;
    }

    public int getImg() {
        return Img;
    }
}

2)Cards_Adapter.java

Class Cards_Adapter extends RecyclerView.Adapter<Cards_Adapter.ViewHolder>
{
    List<Cards> list;
    Context context;

    public Cards_Adapter(List<Cards> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_category_cards, parent, false);
        return new Cards_Adapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
       Cards Cards = list.get(position);
        final int img = Cards.getImg();
        final String categiry = Cards.getCategory();

        holder.sms_cat_img.setImageResource(img);
        holder.sms_category.setText(categiry);

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        ImageView sms_cat_img;
        TextView sms_category;
        public ViewHolder(View itemView) {
            super(itemView);

            sms_cat_img = (ImageView)itemView.findViewById(R.id.sms_cat_img);
            sms_category = (TextView) itemView.findViewById(R.id.sms_category);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, MainActivity.class);
                    Bundle extras = new Bundle();
                    extras.putString("category_msg",sms_category.getText().toString());
                    intent.putExtras(extras);
                    view.getContext().startActivity(intent);
                }
            });
        }
    }
}

3)Cards.xml

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


<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/card_shadow">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/card_shadow">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:id="@+id/sms_cat_img"
            android:padding="10dp"
            android:src="@drawable/bank_icon"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:id="@+id/sms_category"
            android:text="Category Name"
            android:textSize="18dp"
            android:textColor="@color/black"
            android:textStyle="bold"/>

    </LinearLayout>



</android.support.v7.widget.CardView>
</LinearLayout>

 4) MyData.Java

public class MyData {
    static String[] nameArray = {"Property","Offers","Travel","Self-Help","GOVT","Bank","Investment",
            "Entertainment","Fashion","OTP","Wallet","Income Tax","Insurance", "Uncategorized"};

    static Integer[] drawableArray = {
            R.drawable.property_icon,
            R.drawable.offers_icon,
            R.drawable.travel_icon,
            R.drawable.self_help_icon,
            R.drawable.govt_icon,
            R.drawable.bank_icon,
            R.drawable.investment_icon,
            R.drawable.entertainment_icon,
            R.drawable.fashion_icon,
            R.drawable.otp_icon,
            R.drawable.wallet_icon,
            R.drawable.tax_icon,
            R.drawable.insurance_icon,
            R.drawable.uncategorized};

}

5) 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="sms.smsrec.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/sms_category_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        >
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>


5)MainActivity.java

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private List<Cards> Cardss;
    private RecyclerView.LayoutManager mLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        recyclerView = (RecyclerView) findViewById(R.id.sms_category_recycler_view);
        recyclerView.setHasFixedSize(true);

       //  To Set Gridview Style
        mLayoutManager = new GridLayoutManager(getApplicationContext(),2);
        recyclerView.setLayoutManager(mLayoutManager);
        Cardss = new ArrayList<>();
        SMS_Category();
    }

    private void SMS_Category()
    {
        for (int i = 0; i < MyData.nameArray.length; i++) {
            Cardss.add(new Cards(
                    MyData.drawableArray[i],
                    MyData.nameArray[i]
            ));
        }

        adapter = new Cards_Adapter(Cardss, getApplicationContext());
        recyclerView.setAdapter(adapter);
    }
}

Friday, 8 September 2017

Android Drag And Drop Image And Buttons



1)  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="sms.moveimage.MainActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/image"/>


</RelativeLayout>


2)  MainActivity.java

import android.graphics.PointF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    ImageView image;
    PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
    PointF StartPT = new PointF(); // Record Start Position of 'image'

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

        image = (ImageView)findViewById(R.id.image);

        image.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int eid = event.getAction();
                switch (eid)
                {
                    case MotionEvent.ACTION_MOVE :
                        PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y);
                        image.setX((int)(StartPT.x+mv.x));
                        image.setY((int)(StartPT.y+mv.y));
                        StartPT = new PointF( image.getX(), image.getY() );
                        break;
                    case MotionEvent.ACTION_DOWN :
                        DownPT.x = event.getX();
                        DownPT.y = event.getY();
                        StartPT = new PointF( image.getX(), image.getY() );
                        break;
                    case MotionEvent.ACTION_UP :
                        // Nothing have to do
                        break;
                    default :
                        break;
                }
                return true;
            }
        });


    }

}

Thursday, 24 August 2017

Android Call Logs And Make A New Call






1) Android Manifest.XML File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="log.call.calllog">


    <uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
    <uses-permission android:name="android.permission.READ_CALL_LOG"/>
    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


2) MainActivity.XML

<?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="match_parent">

    <!--Todo : MainActivity.XML File -->
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/linear_call"
        android:layout_marginTop="5dp"
        android:background="#E708F5">


        <Button
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:background="#F7DC6F"
            android:id="@+id/call_logs"
            android:layout_marginLeft="25dp"
            android:text="Call Logs"
            android:textStyle="bold"/>
        <Button
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:text="Calls"
            android:id="@+id/call"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="25dp"
            android:background="#F7DC6F"
            android:textStyle="bold"/>


    </LinearLayout>

<!--For Change Screen -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/linear_call"
        android:id="@+id/change_frame"
        android:orientation="horizontal">

    </LinearLayout>


</RelativeLayout>

3) MainActivity.JAVA

public class MainActivity extends Activity{
   
       Button call, call_logs;

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

        call_logs = (Button)findViewById(R.id.call_logs);
        call = (Button)findViewById(R.id.call);

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

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

    private void loadFragment(Fragment fr) {

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

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

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


}

4) Call_Log.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="log.call.calllog.Call_Log">

    <!-- TODO: Update blank fragment layout -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"
        android:id="@+id/tv_call_logs"
        android:textSize="12dp"
        android:textColor="#000000"
        android:textStyle="bold"/>

    </ScrollView>

</FrameLayout>

5) Call_Log.JAVA

public class Call_Log extends Fragment {

    TextView call_logs;
   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_call__log, container, false);

    ContentResolver resolver = getActivity().getContentResolver();
    Context context = getActivity();
    call_logs = (TextView) v.findViewById(R.id.tv_call_logs);
    StringBuffer sb = new StringBuffer();
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CALL_LOG) !=  
PackageManager.PERMISSION_GRANTED)
 {

   final int REQUEST_CODE_ASK_PERMISSIONS = 123;
   ActivityCompat.requestPermissions(getActivity(), new String[]{"android.permission.READ_CALL_LOG"},  REQUEST_CODE_ASK_PERMISSIONS);
   ActivityCompat.requestPermissions(getActivity(), new String[]{"android.permission.WRITE_CALL_LOG"}, REQUEST_CODE_ASK_PERMISSIONS);
  }

  Cursor cur = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, android.provider.CallLog.Calls.DATE + " DESC");

   int number = cur.getColumnIndex( CallLog.Calls.NUMBER );
   int type = cur.getColumnIndex(CallLog.Calls.TYPE);
   int date = cur.getColumnIndex(CallLog.Calls.DATE);
   int duration = cur.getColumnIndex( CallLog.Calls.DURATION);
   sb.append( "Call Details : \n");
   while ( cur.moveToNext() ) {
   String phNumber = cur.getString( number );
   String callType = cur.getString(type);
   String callDate = cur.getString(date);
   Date callDayTime = new Date(Long.valueOf(callDate));
   String callDuration = cur.getString( duration );
   String dir = null;
   int dircode = Integer.parseInt(callType);
   switch (dircode) {
    case CallLog.Calls.OUTGOING_TYPE:
      dir = "OUTGOING";
      break;

    case CallLog.Calls.INCOMING_TYPE:
      dir = "INCOMING";
      break;

    case CallLog.Calls.MISSED_TYPE:
      dir = "MISSED";
      break;
     }

  sb.append( "\nPhone Number:--- "+phNumber +"\nCall Type:--- " + dir +" \nCall Date:--- " + callDayTime+" \nCall duration in sec :--- "+callDuration );
            sb.append("\n----------------------------------");
        }
   cur.close();
   call_logs.setText(sb);
   return v;


    }

}

6) Call.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="log.call.calllog.Call">

    <!-- TODO: Update blank fragment layout -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <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="97dp"
            android:text="Android Call"
            android:textStyle="bold"
            android:textColor="#000000"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/et_num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="48dp"
            android:ems="10"
            android:inputType="phone"
            android:hint="Phone Number"
            android:gravity="center"/>

        <Button
            android:id="@+id/btn_call"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/et_num"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="37dp"
            android:text="Call"
            />
    </RelativeLayout>

</FrameLayout>


6) Call.JAVA

public class Call extends Fragment {

    Button btn_call;
    EditText et_num;
    String phn_no;
    private static final int MAKE_CALL_PERMISSION_REQUEST_CODE = 1;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_call, container, false);
        btn_call = (Button)v.findViewById(R.id.btn_call);
        et_num = (EditText)v.findViewById(R.id.et_num);
        if (checkPermission(Manifest.permission.CALL_PHONE)) {
            btn_call.setEnabled(true);
        } else {
            btn_call.setEnabled(false);
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, MAKE_CALL_PERMISSION_REQUEST_CODE);
        }

        btn_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                phn_no = et_num.getText().toString();

                if (!TextUtils.isEmpty(phn_no)) {
                    if (checkPermission(Manifest.permission.CALL_PHONE)) {
                        String dial = "tel:" + phn_no;
                        //  startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial)));
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse("tel:"+phn_no));//change the number
                        startActivity(callIntent);
                    } else {
                        Toast.makeText(getActivity(), "Permission Call Phone denied", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getActivity(), "Enter a phone number", Toast.LENGTH_SHORT).show();
                }
            }
        });
        return v;
    }
    private boolean checkPermission(String permission) {
        return ContextCompat.checkSelfPermission(getActivity(), permission) == PackageManager.PERMISSION_GRANTED;
    }
}

Thursday, 10 August 2017

Android Rotate Image







1) Manifests.xml


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

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

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

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


2) Splashscreen.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="language.rotateimage.Splashscreen">


    <TextView android:text="@string/app_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textStyle="bold"
        android:textSize="45sp"
        android:id="@+id/txt"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="28dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/android_icon" />

    <!--SplashScreen Xml File-->

</RelativeLayout>

3) Splashscreen.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class Splashscreen extends AppCompatActivity {

    ImageView imageView ;
    Animation animation_1 ;

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

        imageView = (ImageView)findViewById(R.id.imageView);
        animation_1 = AnimationUtils.loadAnimation(Splashscreen.this,R.anim.rotate);
         imageView.startAnimation(animation_1);
        animation_1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                imageView.startAnimation(animation_1);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imageView.startAnimation(animation_1);
                finish();
                Intent i = new Intent(getBaseContext(),MainActivity.class);
                startActivity(i);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /*Todo : Thanks For Watching*/

}

4) 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="language.rotateimage.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:textColor="#000000"
        android:textSize="35sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="219dp" />

</RelativeLayout>


4) MainActivity.java

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

}



5) anim(Folder)


i) rotate.xml


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="1000"
        android:repeatMode="reverse"
        android:repeatCount="2"
        android:interpolator="@android:anim/cycle_interpolator"></rotate>
</set>

 




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

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...