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;
            }
        });


    }

}

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