Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Thursday, 30 May 2019

Flutter GPS Location

In this tutorial , we try to fetch phone GPS Location.





I used this library in pubspec.yaml file under dependencies

dependencies:
  location: ^2.3.5

Android #

In order to use this plugin in Android, you have to add this permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Permission check for Android 6+ was added.

iOS #

And to use it in iOS, you have to add this permission in Info.plist :
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
Warning: there is a currently a bug in iOS simulator in which you have to manually select a Location several in order for the Simulator to actually send data. Please keep that in mind when testing in iOS simulator.

main.dart


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import 'package:flutter/material.dart';
import 'package:flutter_app_sample/GetLocationPage.dart';



void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter GPS',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: GetLocationPage(),
    );
  }
}




GetLocationPage.dart



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import 'package:flutter/material.dart';
import 'package:location/location.dart';

class GetLocationPage extends StatefulWidget {
  @override
  _GetLocationPageState createState() => _GetLocationPageState();
}

class _GetLocationPageState extends State<GetLocationPage> {
  LocationData _currentLocation;
  Location _locationService = new Location();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getLocation().then((value) {
      setState(() {
        _currentLocation = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _currentLocation == null
                ? CircularProgressIndicator()
                : Text("Location:" +
                    _currentLocation.latitude.toString() +
                    " " +
                    _currentLocation.longitude.toString()),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: RaisedButton(
                onPressed: () {
                  _getLocation().then((value) {
                    setState(() {
                      _currentLocation = value;
                    });
                  });
                },
                color: Colors.blue,
                child: Text(
                  "Get Location",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<LocationData> _getLocation() async {
    LocationData currentLocation;
    try {
      currentLocation = await _locationService.getLocation();
    } catch (e) {
      currentLocation = null;
    }
    return currentLocation;
  }
}

Friday, 16 December 2016

BottomSlider like Uber


I really like uber's Bottom Slider a lot and i want to create a view like that.After searching, I found a great library do it easily. Here is the screenshot of the sample.





Step: 1
======

Add below line to build.gradle file under app folder and sync


compile 'com.github.lawloretienne:discreteslider:0.0.9'

Credits to the Author of the Library.
Etienne Lawlor
Github Link 


Step: 2
======
create a layout like below

activity_main.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"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@color/grey_500"
        android:orientation="vertical">

    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@color/grey_100"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/tick_mark_labels_rl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp" />

        <com.etiennelawlor.discreteslider.library.ui.DiscreteSlider
            android:id="@+id/discrete_slider"
            android:layout_width="match_parent"
            android:layout_height="56dp"
            android:layout_marginBottom="4dp"
            android:background="@color/grey_100"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            app:backdropFillColor="@color/grey_200"
            app:backdropStrokeColor="@color/grey_300"
            app:backdropStrokeWidth="1dp"
            app:horizontalBarThickness="4dp"
            app:position="0"
            app:progressDrawable="@drawable/transparent_progress_drawable"
            app:tickMarkCount="4"

            app:tickMarkRadius="8dp" />

    </LinearLayout>

</LinearLayout>


Step: 3
======
create a drawable with an image like below. I have created four files like this. please see source code for reference.

ubergo.xml
=========




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

    <item>

        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="oval">

            <size
                android:width="40dp"
                android:height="40dp" />
            <stroke
                android:width="8dp"
                android:color="@color/fifty_percent_transparency_primary" />

            <solid android:color="@color/colorPrimary" />

            <corners android:radius="1dp" />

        </shape>
    </item>

    <item>

        <bitmap
            android:gravity="center"
            android:src="@drawable/ic_directions_car_black_24dp" />
    </item>


</layer-list>

Add all icons are added as an array in strings.xml file and we can use in MainActivity class.

<array name="icons">
    <item>@drawable/uber_pool</item>
    <item>@drawable/uber_moto</item>
    <item>@drawable/uber_go</item>
    <item>@drawable/uber_suv</item>
</array>


Step: 4
======
Create an Activity class and

MainActivity.java
==============


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.pratap.discreteslider;

import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.etiennelawlor.discreteslider.library.ui.DiscreteSlider;
import com.etiennelawlor.discreteslider.library.utilities.DisplayUtility;

public class MainActivity extends AppCompatActivity {


    DiscreteSlider discreteSlider;
    RelativeLayout tickMarkLabelsRelativeLayout;

    TypedArray icons;
    String[] tickMarkLabels = {"POOL", "uberMOTO", "uberGo", "uberSUV"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tickMarkLabelsRelativeLayout = (RelativeLayout) findViewById(R.id.tick_mark_labels_rl);
        discreteSlider = (DiscreteSlider) findViewById(R.id.discrete_slider);

        Resources res = getResources();
        icons = res.obtainTypedArray(R.array.icons);

        // Detect when slider position changes
        discreteSlider.setOnDiscreteSliderChangeListener(new DiscreteSlider.OnDiscreteSliderChangeListener() {
            @Override
            public void onPositionChanged(int position) {
                int childCount = tickMarkLabelsRelativeLayout.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    TextView tv = (TextView) tickMarkLabelsRelativeLayout.getChildAt(i);
                    if (i == position) {
                        tv.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                        discreteSlider.setThumb(icons.getDrawable(position));

                        // show selected item
                        Toast toast = Toast.makeText(MainActivity.this, tickMarkLabels[i], Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                    } else
                        tv.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey_700));


                }


            }
        });

        tickMarkLabelsRelativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tickMarkLabelsRelativeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                addTickMarkTextLabels();
            }
        });


    }


    private void addTickMarkTextLabels() {
        int tickMarkCount = discreteSlider.getTickMarkCount();
        float tickMarkRadius = discreteSlider.getTickMarkRadius();
        int width = tickMarkLabelsRelativeLayout.getMeasuredWidth();

        int discreteSliderBackdropLeftMargin = DisplayUtility.dp2px(this, 32);
        int discreteSliderBackdropRightMargin = DisplayUtility.dp2px(this, 32);
        float firstTickMarkRadius = tickMarkRadius;
        float lastTickMarkRadius = tickMarkRadius;
        int interval = (width - (discreteSliderBackdropLeftMargin + discreteSliderBackdropRightMargin) - ((int) (firstTickMarkRadius + lastTickMarkRadius)))
                / (tickMarkCount - 1);

        int tickMarkLabelWidth = DisplayUtility.dp2px(this, 40);

        for (int i = 0; i < tickMarkCount; i++) {
            TextView tv = new TextView(this);

            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

            tv.setText(tickMarkLabels[i]);
            tv.setGravity(Gravity.CENTER);


            if (i == discreteSlider.getPosition()) {
                tv.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                discreteSlider.setThumb(icons.getDrawable(i));

            } else
                tv.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey_700));

            //  tv.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));

            int left = discreteSliderBackdropLeftMargin + (int) firstTickMarkRadius + (i * interval) - (tickMarkLabelWidth / 2);

            layoutParams.setMargins(left,
                    0,
                    0,
                    0);
            tv.setLayoutParams(layoutParams);

            tickMarkLabelsRelativeLayout.addView(tv);
        }
    }

}

Source Code
==========
Link

ScreenShots
==========













Friday, 27 November 2015

Android HttpURLConnection code for GET and POST Methods



package com.infodat.selltis2;

import android.util.Log;

import com.infodat.selltis2.utils.Constants;
import com.infodat.selltis2.utils.Utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class HttpWebServiceHandlerSample {

    static String response = null;


    public HttpWebServiceHandlerSample() {

    }


    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     */


    // Get Request using HttpURLConnection  Code
    public String makeGetServiceCall(String requestURL, HashMap<String, String> postDataParams) {

        InputStream inputStream = null;

        HttpURLConnection conn = null;

        String response = "";
        try {
                /* forming th java.net.URL object */


            String newRequestURL = requestURL + getQueryString(postDataParams);

            URL url = new URL(newRequestURL);
            Log.i("URL ", newRequestURL);

            conn = (HttpURLConnection) url.openConnection();

                 /* optional request header */
            conn.setRequestProperty("Content-Type", "application/json");

                /* optional request header */
            conn.setRequestProperty("Accept", "application/json");

            //  urlConnection.setConnectTimeout(100000);

                /* for Get request */
            conn.setRequestMethod("GET");

            int statusCode = conn.getResponseCode();

                /* 200 represents HTTP OK */
            if (statusCode == 200) {

                inputStream = new BufferedInputStream(conn.getInputStream());

                response = convertInputStreamToString(inputStream);


            } else {
                response = Constants.NetWorkErrorMSG;
            }

        } catch (Exception e) {
            //    Log.i("Selltis N/w Error", e.getLocalizedMessage());
            response = Constants.NetWorkErrorMSG;

        } finally {

            if (conn != null)
                conn.disconnect();
        }

        Log.i("RESPONSE", response);
        return response; // return response

    }


    // Convert all key/Value pairs to URL request parameters
    private String getQueryString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }


    // convert InputStream to String
    private String convertInputStreamToString(InputStream inputStream) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";
        String result = "";

        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }

            /* Close Stream */
        if (null != inputStream) {
            inputStream.close();
        }

        return result;
    }


    // POST Request using HttpURLConnection  Code
    public String makePostServiceCall(String requestURL, String postJosnData) {
        InputStream inputStream = null;
        URL url;
        String response = "";
        HttpURLConnection conn = null;
        try {
            url = new URL(requestURL);

            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

                 /* optional request header */
            conn.setRequestProperty("Content-Type", "application/json");

                /* optional request header */
            conn.setRequestProperty("Accept", "application/json");

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(postJosnData);

            //    Log.i("POST URL", url.toString());
            //   Log.i("POST DATA", postJosnData);

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                inputStream = new BufferedInputStream(conn.getInputStream());

                response = convertInputStreamToString(inputStream);


            } else {
                response = Utils.ServerErrorMessage;

            }
        } catch (Exception e) {

            //   Log.i("Selltis N/w Error", e.getLocalizedMessage());
            response = Utils.ServerErrorMessage;
        } finally {

            if (conn != null)
                conn.disconnect();
        }

        return response;

    }


}


Wednesday, 10 June 2015

Create Form Programmatically in Android



Step: 1

create a new xml layout with scrollview and LinearLayout . We create child view dynamically through code , added to the LinearLayout.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="false"
    android:scrollbars="none"
    android:layout_margin="16dp">

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

</ScrollView>

Step: 2

create new Activity class


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package com.pratap.dynamicforms;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

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

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * Created by pratap.kesaboyina on 10-06-2015.
 */
public class DynamicForm extends AppCompatActivity {


    LinearLayout layout1;
    private static int viewsCount = 0;
    private List<View> allViews = new ArrayList<View>();
    LinearLayout.LayoutParams params;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dynamic_form);

        // To set Margin for the child Views
       params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(5, 5, 5, 5);

        // LinearLayout acts as parent Layout , we will add child Views to this Layout dynamically
        layout1 = (LinearLayout) findViewById(R.id.layout1);
        // Sample Data for Spinner
        ArrayList<String> spinnerList = new ArrayList<String>();
        spinnerList.add("Select");
        spinnerList.add("Hyderabad");
        spinnerList.add("Banglore");
        spinnerList.add("Chennai");
        spinnerList.add("Delhi");
        spinnerList.add("Mumbai");

// create edittext dynamically , added to LinearLayout
        createEditText("First Name");
        createEditText("Last Name");
        createEditText("Age");
        createEditText("Address");
        createSpinner(spinnerList);
        createEditText("State");


// create spinners dynamically , added to LinearLayout


// create checkbox dynamically , added to LinearLayout
        createCheckBox("Key Contact");
        createCheckBox("Target contact");
        saveButton();

    }

// create a button to show/save data , entered in the Form
    private void saveButton() {
        Button saveButton = new Button(this);
        saveButton.setHeight(WRAP_CONTENT);
        saveButton.setText("Save");
        saveButton.setOnClickListener(submitListener);
        layout1.addView(saveButton,params);
    }

    // Access the value of the EditText

    private View.OnClickListener submitListener = new View.OnClickListener() {
        public void onClick(View view) {
            StringBuilder stringBuilder = new StringBuilder();
            for (View singView : allViews) {

                String className = Utils.getClassName(singView.getClass());

                if (className.equalsIgnoreCase("EditText")) {
                    EditText editText = (EditText) singView;
                    stringBuilder.append(" "+editText.getText().toString());
                } else if (className.equalsIgnoreCase("Spinner")) {
                    Spinner spiner = (Spinner) singView;
                    stringBuilder.append(" "+spiner.getSelectedItem());
                }
                else if (className.equalsIgnoreCase("CheckBox")) {
                    CheckBox checkBox = (CheckBox) singView;
                    stringBuilder.append(" "+checkBox.isChecked());
                }

            }
            Log.i("All Data ", stringBuilder.toString());

            Utils.showAlertDialog(view.getContext(), "Data", stringBuilder.toString());
        }
    };


    public void createEditText(String hint) {
        EditText editText = new EditText(this);
        editText.setId(viewsCount++);
        editText.setHint(hint);
        allViews.add(editText);
        layout1.addView(editText,params);

    }

    public void createSpinner(List<String> spinnerList) {



        Spinner spinner = new Spinner(this);
        spinner.setId(viewsCount++);
        spinner.setBackgroundResource(R.drawable.dropdown_normal_holo_light);
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerList);
        spinner.setAdapter(spinnerArrayAdapter);
        allViews.add(spinner);
        layout1.addView(spinner,params);
    }


    public void createCheckBox(String label) {

        final CheckBox checkBox = new CheckBox(this);
        checkBox.setId(viewsCount++);
        checkBox.setText(label);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });
        allViews.add(checkBox);
        layout1.addView(checkBox,params);
    }




}

Util.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.pratap.dynamicforms;

import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class Utils

{


    public static void showAlertDialog(Context context, String title,
                                       String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        if (title != null)
            builder.setTitle(title);
        builder.setMessage(message);
        builder.setNegativeButton("OK", null);
        builder.show();
    }

    /**
     *
     * @param c
     * @return
     */

    public static String getClassName(Class c) {
        String className = c.getName();
        int firstChar;
        firstChar = className.lastIndexOf('.') + 1;
        if (firstChar > 0) {
            className = className.substring(firstChar);
        }
        return className;
    }
}

Screen Shot






















Download Source Code Link