battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.


battle programming a forum for elite programmers with extreme will power to sharpen theire skills
 
HomeSearchRegisterLog in
 

 kotlin AS PL grimoire

Go down 
Go to page : Previous  1, 2
AuthorMessage
kurosen
codding
codding
kurosen

Posts : 198
Join date : 2012-04-17

kotlin AS PL grimoire - Page 2 Empty
PostSubject: Kotlin get url source code as text   kotlin AS PL grimoire - Page 2 EmptyFri Jun 28, 2019 11:31 pm


Code:
package com.example.json3

import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import java.io.IOException
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import android.widget.Toast
import java.io.BufferedReader


class MainActivity : AppCompatActivity() {


    private var xmlString = ""
    private val XML_URL = "https://www.yotamarker.com"
    var XML_UR= "https://reqres.in/api/users/2"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getDataJSON()
        try {
            Thread.sleep(6000)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        txt1.text = xmlString


    }

    fun getDataJSON() {
        //we never use void in AsyncTask, we need to use Void
        object : AsyncTask<Void, Void, String>() {
            override fun doInBackground(vararg voids: Void): String {
                //we need to open HTTP URL Connection to our desired URL (www.boi.org.il)
                var connection: HttpURLConnection? = null
                try {
                    connection = URL(XML_URL).openConnection() as HttpURLConnection
                    val buf = BufferedReader(InputStreamReader(connection.inputStream))
                    var line: String?
                    line = buf.readLine()
                    while (line != null) {
                        line = buf.readLine()
                        xmlString += line
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                } finally {
                    connection!!.disconnect()
                }

                return xmlString
            }

            override fun onPostExecute(jsonString: String) {
                super.onPostExecute(jsonString)
                http@ http://Log.e("XML", "onPostExecute: " + jsonString);
                // display json string
                Toast.makeText(applicationContext, jsonString, Toast.LENGTH_LONG).show()

            }
        }.execute()
    }

}

in the manifest :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

chobit
Back to top Go down
kurosen
codding
codding
kurosen

Posts : 198
Join date : 2012-04-17

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotlin getting JSON info   kotlin AS PL grimoire - Page 2 EmptySat Jun 29, 2019 12:51 am

here I used the swap api to get Luke Skywalker :

here is the swap if you want to play : https://swapi.co/

txt1 is the default textbook of the kotlin empty main activity
add internet permission to the manifest

Code:
package com.example.json3

import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import java.io.IOException
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import android.widget.Toast
import java.io.BufferedReader
import org.json.JSONException




class MainActivity : AppCompatActivity() {


    private var jsonString = ""
    private val jsonURL = "https://swapi.co/api/people/1/"
    //var XML_UR= "https://reqres.in/api/users/2"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getDataJSON()
        try {
            Thread.sleep(6000)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        http://txt1.text = jsonString
        parseJson(jsonString)

    }

    fun getDataJSON() {
        //we never use void in AsyncTask, we need to use Void
        object : AsyncTask<Void, Void, String>() {
            override fun doInBackground(vararg voids: Void): String {
                //we need to open HTTP URL Connection to our desired URL (www.boi.org.il)
                var connection: HttpURLConnection? = null
                try {
                    connection = URL(jsonURL).openConnection() as HttpURLConnection
                    val buf = BufferedReader(InputStreamReader(connection.inputStream))
                    var line: String? = buf.readLine()
                    while (line != null) {
                        jsonString += line
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                } finally {
                    connection!!.disconnect()
                }

                return jsonString
            }

            override fun onPostExecute(jsonString: String) {
                super.onPostExecute(jsonString)
                http://Log.e("XML", "onPostExecute: $jsonString")
                parseJson(jsonString)
            }
        }.execute()
    }

    private fun parseJson(jsonString: String) {
        val jsonObj = JSONObject(jsonString)
        val namee = jsonObj.getString("name")

        txt1.text= namee

    }

}
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotlin get battery data   kotlin AS PL grimoire - Page 2 EmptyWed Jul 10, 2019 7:15 pm

it shows number of times displayed + battery level
also notice in the onReceive interface there are vals that can show
if charging, and by AC or usb charging

Code:
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    var b8TRcounter = 0
    private val mBatInfoReceiver = object : BroadcastReceiver() {
        override fun onReceive(ctxt: Context, intent: Intent) {
            val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
            b8TRcounter++;
            txtBox.setText("$level% $b8TRcounter")
            val status: Int = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
            val isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING
                    || status == BatteryManager.BATTERY_STATUS_FULL

            val chargePlug: Int = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
            val usbCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
            val acCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
            //txtBox.setText("$usbCharge")
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        this.registerReceiver(this.mBatInfoReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

}



nice cheers

_________________
MB over and out emp it up
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotlin play audio files one after another   kotlin AS PL grimoire - Page 2 EmptyWed Jul 31, 2019 8:26 pm


assumong you put the files in a raw dir that you create in the res dir


Code:
 mediaPlayer = MediaPlayer.create(this, R.raw.hadouken)
                mediaPlayer.setNextMediaPlayer(MediaPlayer.create(this, R.raw.shouryuken))
                mediaPlayer.start()

battle programming

_________________
MB over and out emp it up
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotlin hide action bar (top blue strip with app name)   kotlin AS PL grimoire - Page 2 EmptyWed Jul 31, 2019 8:34 pm

Code:
supportActionBar?.hide()

put it in the on create like this :

Code:
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportActionBar?.hide()
        this.registerReceiver(this.mBatInfoReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

hadouken hadouken hadouken alert

_________________
MB over and out emp it up
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotloin tts   kotlin AS PL grimoire - Page 2 EmptyFri Aug 16, 2019 9:25 pm

activity_main.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.tutorialkart.texttospeechapp.MainActivity">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center">
        <EditText
                android:id="@+id/edittext_input"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10" >
            <requestFocus />
        </EditText>

        <Button
                android:id="@+id/button_speak"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Speak" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

Main/activity.kt

Code:

package com.yotamarker.kotlintts

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import android.widget.Button
import android.widget.EditText
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener {

    private var tts: TextToSpeech? = null
    private var buttonSpeak: Button? = null
    private var editText: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonSpeak = this.button_speak
        editText = this.edittext_input

        buttonSpeak!!.isEnabled = false;
        tts = TextToSpeech(this, this)

        buttonSpeak!!.setOnClickListener { speakOut() }
    }

    override fun onInit(status: Int) {

        if (status == TextToSpeech.SUCCESS) {
            // set US English as language for tts
            val result = tts!!.setLanguage(Locale.US)

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS","The Language specified is not supported!")
            } else {
                buttonSpeak!!.isEnabled = true
            }

        } else {
            Log.e("TTS", "Initilization Failed!")
        }

    }

    private fun speakOut() {
        val text = editText!!.text.toString()
        tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null,"")
    }

    public override fun onDestroy() {
        // Shutdown TTS
        if (tts != null) {
            tts!!.stop()
            tts!!.shutdown()
        }
        super.onDestroy()
    }

}

not going to lie humiliation

_________________
MB over and out emp it up
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotlin onLongClick listener   kotlin AS PL grimoire - Page 2 EmptySun Nov 03, 2019 9:50 am

place this code in the MainActivity onCreate function

Code:
imageView2.setOnLongClickListener {
            mbTTS.voiceIt("hadouken")
            true
        }

1 replace imageView2 with the view yto have long click
2 replace mbTTS.voiceIt("hadouken") with the code to run when said view has been long clicked geek

in the xml I enable the onLongOnClick attribute of the view.

_________________
MB over and out emp it up
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

kotlin AS PL grimoire - Page 2 Empty
PostSubject: [kotlin] gyroscope walkthrough   kotlin AS PL grimoire - Page 2 EmptyThu Dec 12, 2019 9:26 am

kotlin AS PL grimoire - Page 2 2qb3s9



manifest :

Code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yotamarker.gyro3">
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

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



above I added :
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

add an interface to the package with main.java :

Code:

interface AccelerometerListener {

    fun onAccelerationChanged(x: Float, y: Float, z: Float)

    fun onShake(force: Float)
}

add a class named AccelerometerManager to the package with main.javaAccelerometerManager :

add a class named AccelerometerManager.kt (kotlin)

Code:
Code:

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.widget.Toast

object AccelerometerManager {

   private var context: Context? = null
   /**
   * Accuracy configuration
   */
   private var threshold = 15.0f
   private var interval = 200

   private var sensor: Sensor? = null
   private var sensorManager: SensorManager? = null
   // you could use an OrientationListener array instead
   // if you plans to use more than one listener
   private var listener: AccelerometerListener? = null

   /**
   * indicates whether or not Accelerometer Sensor is supported
   */
   private var supported: Boolean? = null
   /**
   * indicates whether or not Accelerometer Sensor is running
   */
   /**
   * Returns true if the manager is listening to orientation changes
   */
   var isListening = false
       private set

   private val sensorEventListener = object : SensorEventListener {

       private var now: Long = 0
       private var timeDiff: Long = 0
       private var lastUpdate: Long = 0
       private var lastShake: Long = 0

       private var x = 0f
       private var y = 0f
       private var z = 0f
       private var lastX = 0f
       private var lastY = 0f
       private var lastZ = 0f
       private var force = 0f

       override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}

       override fun onSensorChanged(event: SensorEvent) {
           // use the event timestamp as reference
           // so the manager precision won't depends
           // on the AccelerometerListener implementation
           // processing time
           now = event.timestamp

           x = event.values[0]
           y = event.values[1]
           z = event.values[2]

           // if not interesting in shake events
           // just remove the whole if then else block
           if (lastUpdate == 0L) {
               lastUpdate = now
               lastShake = now
               lastX = x
               lastY = y
               lastZ = z
               Toast.makeText(context, "No Motion detected", Toast.LENGTH_SHORT).show()

           } else {
               timeDiff = now - lastUpdate

               if (timeDiff > 0) {

                   force = Math.abs(x + y + z - lastX - lastY - lastZ)

                   if (java.lang.Float.compare(force, threshold) > 0) {

                       if (now - lastShake >= interval) {
                           // trigger shake event
                           listener!!.onShake(force)
                       } else {
                           Toast.makeText(
                               context, "No Motion detected",
                               Toast.LENGTH_SHORT
                           ).show()

                       }
                       lastShake = now
                   }
                   lastX = x
                   lastY = y
                   lastZ = z
                   lastUpdate = now
               } else {
                   Toast.makeText(context, "No Motion detected", Toast.LENGTH_SHORT).show()
               }
           }
           // trigger change event
           listener!!.onAccelerationChanged(x, y, z)
       }
   }

   /**
   * Unregisters listeners
   */
   fun stopListening() {
       isListening = false
       try {
           if (sensorManager != null && sensorEventListener != null) {
               sensorManager!!.unregisterListener(sensorEventListener)
           }
       } catch (e: Exception) {
       }

   }

   /**
   * Returns true if at least one Accelerometer sensor is available
   */
   fun isSupported(cntxt: Context): Boolean {
       context = cntxt
       if (supported == null) {
           if (context != null) {

               sensorManager = context!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager

               // Get all sensors in device
               val sensors = sensorManager!!.getSensorList(
                   Sensor.TYPE_ACCELEROMETER
               )

               supported = sensors.size > 0
           } else {
               supported = java.lang.Boolean.FALSE
           }
       }
       return supported!!
   }

   /**
   * Configure the listener for shaking
   *
   * @param threshold minimum acceleration variation for considering shaking
   * @param interval minimum interval between to shake events
   */
   fun configure(threshold: Int, interval: Int) {
       AccelerometerManager.threshold = threshold.toFloat()
       AccelerometerManager.interval = interval
   }

   /**
   * Registers a listener and start listening
   *
   * @param accelerometerListener callback for accelerometer events
   */
   fun startListening(accelerometerListener: AccelerometerListener) {

       sensorManager = context!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager

       // Take all sensors in device
       val sensors = sensorManager!!.getSensorList(
           Sensor.TYPE_ACCELEROMETER
       )

       if (sensors.size > 0) {

           sensor = sensors[0]

           // Register Accelerometer Listener
           isListening = sensorManager!!.registerListener(
               sensorEventListener, sensor,
               SensorManager.SENSOR_DELAY_GAME
           )

           listener = accelerometerListener
       }
   }

   /**
   * Configures threshold and interval
   * And registers a listener and start listening
   *
   * @param accelerometerListener callback for accelerometer events
   * @param threshold minimum acceleration variation for considering shaking
   * @param interval minimum interval between to shake events
   */
   fun startListening(accelerometerListener: AccelerometerListener, threshold: Int, interval: Int) {
       configure(threshold, interval)
       startListening(accelerometerListener)
   }
}

activity_main.xml :

Code:

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Main Screen"
        android:textColor="@android:color/black"
        android:textSize="32sp"/>
</LinearLayout>

MainActivity.kt

Code:
package com.yotamarker.testgyro

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() , AccelerometerListener{
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
    override protected fun onResume() {
        super.onResume()
        if (AccelerometerManager.isSupported(this))
        {
            AccelerometerManager.startListening(this)
        }
    }
    override fun onAccelerationChanged(x:Float, y:Float, z:Float) {
        tv1.setText("x: = " + x + " y= " + y + " z = " + z)
    }
    override fun onShake(force:Float) {
        Toast.makeText(this, "Motion detected", Toast.LENGTH_SHORT).show()
    }

    override fun onStop() {
        super.onStop()
        //Check device supported Accelerometer senssor or not
        if (AccelerometerManager.isListening())
        {
            //Start Accelerometer Listening
            AccelerometerManager.stopListening()
            Toast.makeText(this, "onStop Accelerometer Stopped", Toast.LENGTH_SHORT).show()
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        if (AccelerometerManager.isListening())
        {
            AccelerometerManager.stopListening()
            Toast.makeText(this, "onDestroy Accelerometer Stopped", Toast.LENGTH_SHORT).show()
        }
    }
}

sweet

optional upgrade :

stabilize gyro input:

add JikanMon.kt :

Code:
class JikanMon {
    private val playGround = PlayGround()
    private var x = -1
    private var timePause = 3
    val isBlocked:Boolean
        get() {
            val nowSeconds = playGround.getSecondsAsInt()
            if ((x < 0 || nowSeconds > x) || (x > 60 && nowSeconds > (x - 60)))
            {
                x = -1
                return false
            }
            return true
        }
    fun block() {
        this.x = playGround.getSecondsAsInt() + timePause
    }
    fun setTimePause(timePause:Int) {
        if ((timePause > 0) && (timePause < 30))
        {
            this.timePause = timePause
        }
    }
}

in the main activity add global vars :
var gyroX = 0.0f; var gyroY = 0.0f;var gyroCounter = 0;var gyroGate = JikanMon()

update this function as such :

Code:
override fun onAccelerationChanged(x:Float, y:Float, z:Float) {
        // *add gyroy below
        if((gyroX - x) > 2 && !gyroGate.isBlocked){
            gyroCounter++
            gyroGate.block()
            Toast.makeText(this, "moved $gyroCounter", Toast.LENGTH_SHORT).show()
            // out put uses this 4 lines :
            //var resultStr = chii.doIt("","shake","")
            //editText.setText("")
            //mbTTS.voiceIt(resultStr)
            //if (mbTTS.TTS){speakOut(resultStr)}
            //face(chii.getEmot())
             }
        else{}
        gyroX=x;gyroY=y;
    }

grimoire

_________________
MB over and out emp it up
Back to top Go down
kurosen
codding
codding
kurosen

Posts : 198
Join date : 2012-04-17

kotlin AS PL grimoire - Page 2 Empty
PostSubject: Kotlin Error : 'public' function exposes its 'public/*package*/' return type argument fix   kotlin AS PL grimoire - Page 2 EmptySat Dec 21, 2019 6:48 am

Kotlin Error : 'public' function exposes its 'public/*package*/' return type argument

add public modifier to the super class itself

joining
Back to top Go down
kurosen
codding
codding
kurosen

Posts : 198
Join date : 2012-04-17

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotlin walkthrough how to hide on screen keyboard programmatically   kotlin AS PL grimoire - Page 2 EmptySat Jan 04, 2020 12:58 am

kotlin : hide soft keyboard of an active editText view :

Code:
val mgr = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        mgr.hideSoftInputFromWindow(editText.windowToken,0)

get some
Back to top Go down
kurosen
codding
codding
kurosen

Posts : 198
Join date : 2012-04-17

kotlin AS PL grimoire - Page 2 Empty
PostSubject: kotlin handler time   kotlin AS PL grimoire - Page 2 EmptyWed Jan 08, 2020 10:00 am

Code:
val handler = Handler()

        val run = object : Runnable {
            override fun run() {
                Log.i("hadouken", "A second passed by")

                handler.postDelayed(this, 1000)
            }
        }

        handler.post(run)

hadouken
Back to top Go down
kurosen
codding
codding
kurosen

Posts : 198
Join date : 2012-04-17

kotlin AS PL grimoire - Page 2 Empty
PostSubject: on done btn event   kotlin AS PL grimoire - Page 2 EmptyFri Jan 10, 2020 9:12 am

kotlin on done button clicked in soft keyboard of editText event :

Code:
editText.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                // code goes here
                return@OnKeyListener true
            }
            false
        })

finisher
Back to top Go down
kurosen
codding
codding
kurosen

Posts : 198
Join date : 2012-04-17

kotlin AS PL grimoire - Page 2 Empty
PostSubject: [kotlin]android studio using custom font for a view such as editText   kotlin AS PL grimoire - Page 2 EmptyFri Jan 10, 2020 4:17 pm

DL a custom font .ttf file.
open a dir named font in the res directory
and choose resource type : font

place said .ttf file in said dir.
select the font from said views font family attribute

alert

all ttf files name chars must be lower case !
Back to top Go down
Moti Barski
super
super
Moti Barski

Posts : 445
Join date : 2011-08-02

kotlin AS PL grimoire - Page 2 Empty
PostSubject: Kotlin GPSstep by step walkthrough   kotlin AS PL grimoire - Page 2 EmptyWed Feb 19, 2020 4:48 pm

get GPS info in an app [kotlin] step by step walkthrough.

1 add manifest permissions :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

you cam omit <uses-permission android:name="android.permission.INTERNET" />

add Tokoro class, this will save all the GPS info into static variables
which are accessible from anywhere in the project. :

public class Tokoro {
public static double lat = 51.4061;
public static double lon = 30.0571;
public static String placeName = "pripyat";
}

OR if all your classes are kt, you can use Tokoro in it's kotlin form :

object Tokoro {
 var lat = 51.4061
 var lon = 30.0571
 var placeName = "pripyat"
}

3 in the MainActivity add functions :
Code:

fun placeToString() {
        // convert gps coordinates into place name
        var returnString = ""
        val gcdLocale = Geocoder(this, Locale.ENGLISH) //new Geocoder(this, Locale.ENGLISH)
        var localeAdd:List<Address>? = null
        try
        {

            localeAdd = gcdLocale.getFromLocation(Tokoro.lat, Tokoro.lon, 1)
        }
        catch (e: IOException) {
            e.printStackTrace()
        }
        //if localeAdd is null (false) get out of the function (method)
        assert(localeAdd != null)
        if (localeAdd!!.size > 0)
        {
            val myAdd = localeAdd.get(0).getAddressLine(0)
            returnString = myAdd
        }
        Tokoro.placeName = returnString
    }
add global vars :
var locationManager: LocationManager? = null
var locationListener: LocationListener? =null

add function :
Code:

override
   fun onRequestPermissionsResult(requestCode:Int, @NonNull permissions:Array<String>, @NonNull grantResults:IntArray) {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults)
       if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
       {
           if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)
           {
               locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 1.1f, locationListener)
           }
       }
   }
4 still in the MainActivity, add this in the onCreate function :

Code:

locationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        locationListener = object:LocationListener {
            override
            fun onLocationChanged(location: Location) {
                try {
                    Log.i("Location", "latcpp: " + location.getLatitude() + "lon: " + location.getLongitude()) // modify hya
                    Tokoro.lat = location.getLatitude();Tokoro.lon = location.getLongitude()
                    placeToString()
                } catch (e: Exception) {
                }


            }
            override
            fun onStatusChanged(s:String, i:Int, bundle:Bundle) {
            }
            override
            fun onProviderEnabled(s:String) {
            }
            override
            fun onProviderDisabled(s:String) {
            }
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !== PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION), 1)
        }
        else
        {
            locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 1f, locationListener)
        }

notice this code line :
val gcdLocale = Geocoder(this, Locale.ENGLISH)
this translates the location results from any language to english
val gcdLocale = Geocoder(this) will return in your phones default langauge.

king

_________________
MB over and out emp it up
Back to top Go down
 
kotlin AS PL grimoire
Back to top 
Page 2 of 2Go to page : Previous  1, 2

Permissions in this forum:You cannot reply to topics in this forum
battle programmers alliance :: battle programming alliance :: battle programming-
Jump to: