質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

Q&A

0回答

921閲覧

Android/Kotlin 別アクティビティからのインテントが受け取れない

退会済みユーザー

退会済みユーザー

総合スコア0

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

0グッド

0クリップ

投稿2021/11/15 22:51

困っていること/やりたいこと

お世話になります。

MainActivityから呼び出したアクティビティで処理した内容を、MainActivityに渡して処理したいのですが、MainActivityに処理内容が上手く渡せず困っています。

コード

具体的にはFolderPicker.ktのlistClickやselectの関数の箇所の
receivedIntent?.putExtra("data", data)
setResult(RESULT_OK, receivedIntent)
のdataがMainActivityにnullとして渡されてしまいます。

FolderPicker.ktで処理した時点ではdataには選択したファイル/フォルダのパスが正しく格納されているのを確認しているため、なぜかインテントとして投げるとnullになってしまう?みたいです。

MainActivity

1private const val FILE_PICKER_CODE = 1 2private const val FOLDER_PICKER_CODE = 2 3private const val MULTIFILE_PICKER_CODE = 3 4 5class MainActivity : AppCompatActivity() { 6 private var filepath = "" 7 override fun onCreate(savedInstanceState: Bundle?) { 8 super.onCreate(savedInstanceState) 9 setContentView(R.layout.activity_main) 10 11 findViewById<View>(R.id.onepick).setOnClickListener { pickFile() } 12 findViewById<View>(R.id.folderpick).setOnClickListener { pickFolder() } 13 findViewById<View>(R.id.multipick).setOnClickListener { pickmultiFile() } 14 } 15 16 private fun pickFile() { 17 val intent = Intent(this, FolderPicker::class.java) 18 intent.putExtra("title", "Select file ") 19 intent.putExtra("pickFiles", true) 20 startActivityForResult(intent, FILE_PICKER_CODE) 21 } 22 23 private fun pickFolder() { 24 val intent = Intent(this, FolderPicker::class.java) 25 intent.putExtra("title", "Select folder ") 26 intent.putExtra("pickFolder", true) 27 startActivityForResult(intent, FOLDER_PICKER_CODE) 28 } 29 30 override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { 31 super.onActivityResult(requestCode, resultCode, intent) 32 33 if (requestCode == FILE_PICKER_CODE) { // dataに値が渡されない 34 if (resultCode == RESULT_OK && intent!!.hasExtra("data")) { 35 filepath = intent.extras!!.getString("data").toString() 36 Toast.makeText(applicationContext, intent.extras!! 37 .getString("data")+"を選択した", Toast.LENGTH_SHORT).show() 38 } 39 else Toast.makeText(applicationContext, intent.toString(),Toast.LENGTH_SHORT).show() 40 } 41 else if (requestCode == FOLDER_PICKER_CODE){ 42 if (resultCode == RESULT_OK && intent!!.hasExtra("data")) { 43 filepath = intent.extras!!.getString("data").toString() 44 Toast.makeText(applicationContext, intent.extras!! 45 .getString("data")+"を選択した", Toast.LENGTH_SHORT).show() 46 } else if (resultCode == RESULT_CANCELED) { 47 Toast.makeText(applicationContext, "フォルダ選択をキャンセルした",Toast.LENGTH_SHORT).show() 48 } 49 } 50 } 51}

FolderPicker.kt

1 2data class FilePojo(var name: String? = null,var folder: Boolean = false) 3 4class FolderPicker : Activity() { 5 private var folderAndFileList = mutableListOf<FilePojo>() 6 private var foldersList = mutableListOf<FilePojo>() 7 private var filesList = mutableListOf<FilePojo>() 8 private var multifileList = mutableListOf("") 9 private var tvtitle: TextView? = null 10 private var tvlocation: TextView? = null 11 private var location = "/storage/emulated/0" 12 private var pickFiles = false 13 private var pickmultiFiles = false 14 private var receivedIntent: Intent? = null 15 16 private val isExternalStorageReadable: Boolean 17 get() { 18 val state = Environment.getExternalStorageState() 19 return Environment.MEDIA_MOUNTED == state || Environment.MEDIA_MOUNTED_READ_ONLY == state 20 } 21 22 override fun onCreate(savedInstanceState: Bundle?) { 23 super.onCreate(savedInstanceState) 24 setContentView(R.layout.fp_main_layout) 25 26 if (!isExternalStorageReadable) { 27 Toast.makeText(this, "Storage access permission not given", Toast.LENGTH_LONG).show() 28 finish() 29 } 30 31 tvtitle = findViewById<View>(R.id.fp_tv_title) as TextView 32 tvlocation = findViewById<View>(R.id.fp_tv_location) as TextView 33 34 try { // ファイルピッカー呼び出し時のオプション処理部分 35 val receivedIntent = intent 36 if (receivedIntent.hasExtra("title")) { 37 val receivedTitle = receivedIntent.extras!!.getString("title") 38 if (receivedTitle != null) { 39 tvtitle!!.text = receivedTitle 40 } 41 } 42 if (receivedIntent.hasExtra("location")) { 43 val reqLocation = receivedIntent.extras!!.getString("location") 44 if (reqLocation != null) { 45 val requestedFolder = File(reqLocation) 46 if (requestedFolder.exists()) location = reqLocation 47 } 48 } 49 if (receivedIntent.hasExtra("pickFiles")) { 50 pickFiles = receivedIntent.extras!!.getBoolean("pickFiles") 51 if (pickFiles) { 52 findViewById<View>(R.id.fp_btn_select).visibility = View.GONE 53 findViewById<View>(R.id.fp_btn_new).visibility = View.GONE 54 } 55 } 56 else if (receivedIntent.hasExtra("pickmultiFiles")) { 57 pickmultiFiles = receivedIntent.extras!!.getBoolean("pickmultiFiles") 58 } 59 } catch (e: Exception) { 60 e.printStackTrace() 61 } 62 loadLists(location) 63 } 64 65 @SuppressLint("SetTextI18n") 66 fun loadLists(location: String) { 67 try { 68 val folder = File(location) 69 if (!folder.isDirectory) exit() 70 tvlocation!!.text = "Location : " + folder.absolutePath 71 val files = folder.listFiles() 72 foldersList = mutableListOf() 73 filesList = mutableListOf() 74 for (currentFile in files!!) { 75 if (currentFile.isDirectory) { 76 val filePojo = FilePojo(currentFile.name, true) 77 foldersList.add(filePojo) 78 } else { 79 val filePojo = FilePojo(currentFile.name, false) 80 filesList.add(filePojo) 81 } 82 } 83 folderAndFileList = mutableListOf() //初期化 84 Collections.sort(foldersList, comparatorAscending) 85 folderAndFileList.addAll(foldersList) 86 87 if (pickFiles || pickmultiFiles) { 88 Collections.sort(filesList, comparatorAscending) 89 folderAndFileList.addAll(filesList) 90 } 91 showList() 92 } catch (e: Exception) { 93 e.printStackTrace() 94 } 95 } // load List 96 97 private var comparatorAscending: Comparator<FilePojo> = 98 Comparator<FilePojo> { f1, f2 -> f1.component1()!!.compareTo(f2.component1()!!)} 99 100 private fun showList() { 101 try { 102 val folderAdapter = FolderAdapter(this, folderAndFileList) 103 val listView = findViewById<View>(R.id.fp_listView) as ListView 104 listView.adapter = folderAdapter 105 listView.onItemClickListener = 106 OnItemClickListener { _, _, position, _ -> listClick(position) } 107 } catch (e: Exception) { 108 e.printStackTrace() 109 } 110 } 111 112 private fun listClick(position: Int) { 113 if (pickFiles && !folderAndFileList[position].component2()) {//ファイル選択したらそれを取得 114 val data = location + File.separator + folderAndFileList[position].component1() 115 receivedIntent?.putExtra("data", data) 116 setResult(RESULT_OK, receivedIntent) 117 finish() 118 } 119 else if (pickmultiFiles && !folderAndFileList[position].component2()){ //ファイル選択したらリストに入れる 120 val data = location + File.separator + folderAndFileList[position].component1() 121 multifileList.add(data) 122 Toast.makeText(this, multifileList.toString(), Toast.LENGTH_LONG).show() 123 124 } 125 else { 126 location = location + File.separator + folderAndFileList[position].component1() 127 loadLists(location) 128 } 129 } 130 131 override fun onBackPressed() { 132 goBack(null) 133 } 134 135 fun goBack(@Suppress("UNUSED_PARAMETER") v: View?) { 136 if (location != "" && location != "/") { 137 val start = location.lastIndexOf('/') 138 val newLocation = location.substring(0, start) 139 location = newLocation 140 loadLists(location) 141 } else { 142 exit() 143 } 144 } 145 146 private fun exit() { 147 setResult(RESULT_CANCELED, receivedIntent) 148 finish() 149 } 150 151 private fun createNewFolder(filename: String) { 152 try { 153 val file = File(location + File.separator + filename) 154 file.mkdirs() 155 loadLists(location) 156 } catch (e: Exception) { 157 e.printStackTrace() 158 159 } 160 } 161 162 fun newFolderDialog(@Suppress("UNUSED_PARAMETER") v: View?) { 163 val dialog = AlertDialog.Builder(this).create() 164 dialog.setTitle("Enter Folder Name") 165 val et = EditText(this) 166 dialog.setView(et) 167 dialog.setButton( 168 DialogInterface.BUTTON_POSITIVE, "Create" 169 ) { _, _ -> createNewFolder(et.text.toString()) } 170 dialog.setButton( 171 DialogInterface.BUTTON_NEGATIVE, "Cancel" 172 ) { _, _ -> } 173 dialog.show() 174 } 175 176 fun select(@Suppress("UNUSED_PARAMETER")v: View?) { 177 if (pickmultiFiles) { 178 Toast.makeText(this, "未実装", Toast.LENGTH_LONG).show() 179 } else { 180 receivedIntent?.putExtra("data", location) 181 setResult(RESULT_OK, receivedIntent) 182 //Toast.makeText(this, location + "を選択した", Toast.LENGTH_LONG).show() 183 finish() 184 } 185 } 186}

やってみたこと

data自体がnullなのか検証 → インテントを投げる時点ではnullではなかった

よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2021/11/16 03:34

setResult に指定する Intent は、receivedIntent ではなく、新たに作ったものを渡すべきでは。
jimbe

2021/11/16 04:31

FolderPicker クラスの receivedIntent フィールドに intent を入れているのはどこでしょうか。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問