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

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

kotlin AS PL grimoire

power_settings_newLogin to reply
2 posters

descriptionkotlin AS PL grimoire - Page 2 EmptyKotlin get url source code as text

more_horiz

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:

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin getting JSON info

more_horiz
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

    }

}

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin get battery data

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

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin play audio files one after another

more_horiz

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


:BP:

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin hide action bar (top blue strip with app name)

more_horiz

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


:hkn: :hkn: :hkn: :alrt:

descriptionkotlin AS PL grimoire - Page 2 Emptykotloin tts

more_horiz
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()
    }

}


:NGL: :humiliation:

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin onLongClick listener

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

descriptionkotlin AS PL grimoire - Page 2 Empty[kotlin] gyroscope walkthrough

more_horiz
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()
        }
    }
}


:swt:

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:

descriptionkotlin AS PL grimoire - Page 2 EmptyKotlin Error : 'public' function exposes its 'public/*package*/' return type argument fix

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

add public modifier to the super class itself

:join:

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin walkthrough how to hide on screen keyboard programmatically

more_horiz
kotlin : hide soft keyboard of an active editText view :

Code:

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


:getsome:

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin handler time

more_horiz

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)


:hkn:

descriptionkotlin AS PL grimoire - Page 2 Emptyon done btn event

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

descriptionkotlin AS PL grimoire - Page 2 Empty[kotlin]android studio using custom font for a view such as editText

more_horiz
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

:alrt:

all ttf files name chars must be lower case !

descriptionkotlin AS PL grimoire - Page 2 EmptyKotlin GPSstep by step walkthrough

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

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin STT speech to text

more_horiz
oreo API tested

add permission :

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
add java class named LandAdapter:

Code:

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class LangAdapter extends BaseAdapter {
    Context context;
    ArrayList<String> myResult;

    public LangAdapter(Context context, ArrayList<String> myResult) {
        this.context = context;
        this.myResult = myResult;
    }

    @Override
    public int getCount() {
        return myResult.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView txt = new TextView(context);
        txt.setText(myResult.get(position));
        txt.setTextColor(Color.WHITE);
        return txt;
    }
}


kotlin main activity : add methode

Code:

private fun runSpeechRecognition() {
        //handle the speech recognition intent
        val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
        //tell the intent that we want to speak freely
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        //tell the intent that we want to use the default language
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault())
        //show the user a text to explain what we want.
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to phone")
        if (hasAudioPermission)
        {
            try
            {
                startActivityForResult(intent, RECOGNITION_RESULT)
            }
            catch (e: ActivityNotFoundException) {
                Toast.makeText(this.applicationContext, "ERROR", Toast.LENGTH_SHORT).show()
            }
            catch (e:Exception) {
                Log.e("WTF", "runSpeechRecognition: " + e.message)
            }
        }
    }


kotlin main activity : add methode

Code:

protected override fun onActivityResult(requestCode:Int, resultCode:Int, data:Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            //in case the request code is 2 - recognition intent
            RECOGNITION_RESULT -> if (resultCode == RESULT_OK && data != null)
            {
                //get array list of all our result (can be 1, can be 5)
                val result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
                val myAdapter = LangAdapter(this.applicationContext, result)
                editText.setText(result.get(0).trim().toLowerCase().substring(1,result.get(0).trim().length) + "")
                engageChobit()
                //StaticString.str =result.get(0).trim().toLowerCase().substring(1,result.get(0).trim().length) + ""
                //Toast.makeText(this.applicationContext, result.get(0).trim().toLowerCase().substring(1, result.get(0).trim().length) + "", Toast.LENGTH_SHORT).show()
            }
            else -> Toast.makeText(this.applicationContext, "the programmer is not so bright", Toast.LENGTH_SHORT).show()
        }
    }


kotlin main activity : add methode

Code:


fun onRequestPermissionsResult(requestCode:Int, @NonNull permissions:Array<String>, @NonNull grantResults:IntArray) {
        //GPS beefup
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            //STT
            if(requestCode==1){
            hasAudioPermission = true}
        }
    }

kotlin main activity : add methode

Code:

private fun askPermission() {
        //create a list of permissions
        var listPerm = ArrayList<String>()
        //var listPerm:List<String> = ArrayList() // contains the recog results per talk
        //get permission status for audio record
        val audioPerm = ContextCompat.checkSelfPermission(this.applicationContext, Manifest.permission.RECORD_AUDIO)
        //check if the record audio permission is granted
        if (audioPerm != PackageManager.PERMISSION_GRANTED)
        {
            listPerm.add(Manifest.permission.RECORD_AUDIO)
        }
        else
        {
            hasAudioPermission = true
        }
        //check if our list is not empty, and ask permission for it's items.
        if (!listPerm.isEmpty())
        {
            //ask permission by requests.
            ActivityCompat.requestPermissions(this, listPerm.toArray(arrayOfNulls<String>(listPerm.size)), REQUEST_CODE)
        }
    }


glabal vars after class MainActivity : AppCompatActivity(),:
//STT :
   //private var context:Context?=null
   private var hasAudioPermission = false
   private val REQUEST_CODE = 1
   private val RECOGNITION_RESULT = 2

:getsome:

Last edited by kurosen on Thu Sep 10, 2020 11:51 pm; edited 1 time in total

descriptionkotlin AS PL grimoire - Page 2 EmptyRe: kotlin AS PL grimoire

more_horiz
see full MainActivity kotlin class utilizing above STT walkthrough:

Code:

package com.yotamarker.lgkotlin1

import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.location.*
import android.os.BatteryManager
import android.os.Bundle
import android.os.Handler
import android.speech.RecognizerIntent
import android.speech.tts.TextToSpeech
import android.support.annotation.NonNull
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException
import java.util.*


class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener, AccelerometerListener{
    //STT :
    //private var context:Context?=null
    private var hasAudioPermission = false
    private val REQUEST_CODE = 1
    private val RECOGNITION_RESULT = 2
    // nightrider display emot
    val nightRider2 = NightRider();
    val nightRider3 = NightRider()
    val nightRider4 = NightRider()
    //end nightrider beefup region
    // global vars
    private var tts: TextToSpeech? = null
    val kanjiClock = KanjiClock()
    var chii:Chobit? = null
    var toggleTic = false
    var gyroX = 0.0f; var gyroY = 0.0f;var gyroCounter = 0;var gyroGate = JikanMon()
    var locationManager: LocationManager? = null //GPS beefup
    var locationListener: LocationListener? =null //GPS beefup
    //var spoke = false
    val nightRider = NightRider()
    val b8TriTimeGate = TimeGate()
    var mbTTS = TTSVoice(this)
    private val mBatInfoReceiver = object : BroadcastReceiver() {
        override fun onReceive(ctxt: Context, intent: Intent) {
            if (!b8TriTimeGate.isClosed) {
                b8TriTimeGate.close(5)
                val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
                val b8TRiStr = chii!!.doIt("", "$level charge", "")
                mbTTS.voiceIt(b8TRiStr)
                //voiceIt(b8TRiStr)
                //if (b8TRiStr != ""){editText.setText(b8TRiStr)}
                http://editText.setText(chii.doIt("","$level charge",""))
                http://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
                http://txtBox.setText("$usbCharge")
            }
        }
    }
    fun placeToString() {
        //GPS beefup
        // 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
    }
    override
    fun onRequestPermissionsResult(requestCode:Int, @NonNull permissions:Array<String>, @NonNull grantResults:IntArray) {
        //GPS beefup
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            //STT
            if(requestCode==1){
            hasAudioPermission = true}
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)
            {
                locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 1.1f, locationListener)
            }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//disables screen timeout
        // getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // reenable screen timeout
        askPermission()
        nightRider2.setMode(2);nightRider3.setMode(3);nightRider4.setMode(4)
        val handler = Handler()

        val run = object : Runnable {
            override fun run() {
                Log.i("hadouken", "A second passed by")
                var s1 = "";
                s1 = kanjiClock.timeInKanji()
                textView.setText(s1)
                when (chii!!.getSoulEmotion()) {
                    "2" -> s1 = nightRider2.getDisplay()
                    "3" -> s1 = nightRider3.getDisplay()
                    "4" -> s1 = nightRider4.getDisplay()
                    else -> {s1 = nightRider.getDisplay()
                    }
                }
                textView2.setText(s1)
                handler.postDelayed(this, 1000)
            }
        }

        handler.post(run)
        b8TriTimeGate.setPause(5)
        b8TriTimeGate.close(5)
        chii = Chobit(SharedPrefDB(this))
        tts = TextToSpeech(this, this)
        supportActionBar?.hide()
        this.registerReceiver(this.mBatInfoReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        var count = 0
        editText.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                engageChobit()
                return@OnKeyListener true
            }
            false
        })
        //GPS beefup :
        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)
        }
        //GPS beefup on create end point
    }
    fun engage(view: View){
        runSpeechRecognition()
        //engageChobit()
    }
    fun clrText(view: View){
        editText.setText("")
    }
    fun engageChobit(){
        val mgr = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        mgr.hideSoftInputFromWindow(editText.windowToken,0)
        var resultStr = chii!!.doIt(editText.text.toString(),"","")
        editText.setText("")
        mbTTS.voiceIt(resultStr)
        if (mbTTS.TTS){speakOut(resultStr)}
        //face(chii!!.getEmot())
    }
    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(leftOver:String) {
        tts!!.speak(leftOver, TextToSpeech.QUEUE_FLUSH, null,"")
    }
    public override fun onDestroy() {
        // Shutdown TTS
        if (tts != null) {
            tts!!.stop()
            tts!!.shutdown()
        }
        super.onDestroy()
        if (AccelerometerManager.isListening)
        {
            AccelerometerManager.stopListening()
            Toast.makeText(this, "onDestroy Accelerometer Stopped", Toast.LENGTH_SHORT).show()
        }
    }
    override fun onShake(force:Float) {
        Toast.makeText(this, "Motion detected", Toast.LENGTH_SHORT).show()
    }
    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)}
        }
        else{}
        gyroX=x;gyroY=y;
    }
    override protected fun onResume() {
        super.onResume()
        if (AccelerometerManager.isSupported(this))
        {
            AccelerometerManager.startListening(this)
        }
    }
    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()
        }
    }
    //STT :
    private fun askPermission() {
        //create a list of permissions
        var listPerm = ArrayList<String>()
        //var listPerm:List<String> = ArrayList() // contains the recog results per talk
        //get permission status for audio record
        val audioPerm = ContextCompat.checkSelfPermission(this.applicationContext, Manifest.permission.RECORD_AUDIO)
        //check if the record audio permission is granted
        if (audioPerm != PackageManager.PERMISSION_GRANTED)
        {
            listPerm.add(Manifest.permission.RECORD_AUDIO)
        }
        else
        {
            hasAudioPermission = true
        }
        //check if our list is not empty, and ask permission for it's items.
        if (!listPerm.isEmpty())
        {
            //ask permission by requests.
            ActivityCompat.requestPermissions(this, listPerm.toArray(arrayOfNulls<String>(listPerm.size)), REQUEST_CODE)
        }
    }
    private fun runSpeechRecognition() {
        //handle the speech recognition intent
        val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
        //tell the intent that we want to speak freely
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        //tell the intent that we want to use the default language
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault())
        //show the user a text to explain what we want.
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to phone")
        if (hasAudioPermission)
        {
            try
            {
                startActivityForResult(intent, RECOGNITION_RESULT)
            }
            catch (e: ActivityNotFoundException) {
                Toast.makeText(this.applicationContext, "ERROR", Toast.LENGTH_SHORT).show()
            }
            catch (e:Exception) {
                Log.e("WTF", "runSpeechRecognition: " + e.message)
            }
        }
    }

    protected override fun onActivityResult(requestCode:Int, resultCode:Int, data:Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            //in case the request code is 2 - recognition intent
            RECOGNITION_RESULT -> if (resultCode == RESULT_OK && data != null)
            {
                //get array list of all our result (can be 1, can be 5)
                val result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
                val myAdapter = LangAdapter(this.applicationContext, result)
                editText.setText(result.get(0).trim().toLowerCase().substring(1,result.get(0).trim().length) + "")
                engageChobit()
                http://StaticString.str =result.get(0).trim().toLowerCase().substring(1,result.get(0).trim().length) + ""
                http://Toast.makeText(this.applicationContext, result.get(0).trim().toLowerCase().substring(1, result.get(0).trim().length) + "", Toast.LENGTH_SHORT).show()
            }
            else -> Toast.makeText(this.applicationContext, "the programmer is not so bright", Toast.LENGTH_SHORT).show()
        }
    }
}


:chobit:

descriptionkotlin AS PL grimoire - Page 2 Emptykotlin getter and setter example

more_horiz
kotlin getter and setter example


Code:

protected var sentAlg = false // accessed by sub cls
        get() {val result = sentAlg
            sentAlg = false
            return result}                    // getter
        set(value) { field = value }      // setter

privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply