0

I have tried code from MallikarjunM, but it does not work for me :-(. I have it little rewrite it to my basic Android Studio project with empty activity with one textViev "pokusnejText".

here is my code MainActivity.kt:

package com.example.zapisdosouboru

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.TextView
import java.io.File
import java.io.PrintWriter

class MainActivity : AppCompatActivity() {

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

        val pokusnejText = findViewById<TextView>(R.id.pokusnejText)


        var answer : String = ""
        val sd_main = File(Environment.getExternalStorageDirectory().toString() + "/smazat" )
        var success = true
        if (!sd_main.exists()) {
            success = sd_main.mkdir()
            if (success) {
                answer = "folder created"
            } else {
                answer = "folder can not be created"
            }
        }

        if (success) {
            val sd = File("testingFile.txt")

            if (!sd.exists()) {
                success = sd.mkdir()
            }

            if (success) {
                // directory exists or already created
                val dest = File(sd, "testingFile.txt")

                try {
                    // response is the data written to file
                    PrintWriter(dest).use { out -> out.println(answer) }
                    answer = "writed to" + sd.toString()
                } catch (e: Exception) {
                    answer = "can not be written"
                }

            } else {
                answer = "folder or file does not exists"
            }
        }
        pokusnejText.text = answer
    }
}

and here is my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.zapisdosouboru">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

    </application>

</manifest>

first what I have rewrite was

val sd_main = File(Environment.getExternalStorageDirectory()+"/yourlocation")

to

val sd_main = File(Environment.getExternalStorageDirectory().toString() + "/yourlocation" )

because without toString() was plus marked red ... but it still does not work and answers that it can not create the folder... I have tried it in Android Studio emulator with android 6.0

Some additional questions: I am very confused with function File() used in code one time with one parameter and second times with two. Does exists for Kotlin some web page similar http://www.cplusplus.com/ - I can not find any so helpful as for c++.

Thanks for help fik236

Jack
  • 5,354
  • 2
  • 29
  • 54
fik236
  • 83
  • 6

2 Answers2

0

You are saying you tried that on emulator of Android 6. Did you explicitly ask for WRITE_EXTERNAL_STORAGE permission before writing into the external storage? What's the output in the logcat when this code executes? It should be there saying that it cannot create the file because of 'permission denied'

Regarding site similar to cplusplus.com, sure, there is Kotlin language reference which bears the same function that cpp.com and I'd say it is even better as it contains references to books, online courses, etc.

Maroš Šeleng
  • 1,600
  • 13
  • 28
  • Thank you for answer. I thougt that I have allow acces to ext storage with fourth row of my AndroidManifest.xml (my second part of code in ask). My logcat is now empty I do not know if I have something corrupt - because I have press button of trash (clear logcat) for easier search. There were some messages - but now it is empty. – fik236 Apr 14 '19 at 16:12
  • Did you read the first link I provided carefully? it says "You declare that your app needs a permission by listing the permission in the app manifest and then requesting that the user approve each permission at runtime (on Android 6.0 and higher).". You need to request the according permission dynamically, on runtime. Pleas read the attached article to find out how to handle runtime permission requests. – Maroš Šeleng Apr 15 '19 at 10:17
0

thanks to Maroš Šeleng I have some how working code. Here is it:

package com.example.zapisdosouboru

import android.Manifest
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.widget.TextView
import java.io.File
import java.io.PrintWriter

class MainActivity : AppCompatActivity() {

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



        // Here, thisActivity is the current activity
        if (checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            // Permission has already been granted
        }

        val pokusnejText = findViewById<TextView>(R.id.pokusnejText)


        var answer : String = ""
        val sd_main = File(Environment.getExternalStorageDirectory() , "smazat" )
        var success = true
        if (!sd_main.exists()) {
            success = sd_main.mkdir()
            if (success) {
                answer = "folder created"
            } else {
                answer = "folder can not be created"
            }
        }

        if (success) {
            val sd = File(sd_main,"testingFile.txt")

            if (!sd.isFile()) {
                success = sd.createNewFile()
            }

            if (success) {
                // directory exists or already created

                try {
                    answer = "writed to" + sd.toString()
                    PrintWriter(sd).use { out -> out.println("testing text") }

                } catch (e: Exception) {
                    answer = "can not be written"
                }

            } else {
                answer = "folder or file does not exists"
            }
        }
        pokusnejText.text = answer
    }
}
fik236
  • 83
  • 6