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

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

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

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Android

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

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Q&A

解決済

1回答

2965閲覧

Android Studio エラーの解決方法をお願いします。

caffrey

総合スコア3

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Android

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

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

0グッド

0クリップ

投稿2020/11/22 05:23

編集2020/11/22 05:29

前提・実現したいこと

小数点2桁目まで表記しようと試みたがエラーが発生した。
解決方法がないでしょうか。

発生している問題・エラーメッセージ

11/22 13:38:17: Launching 'app' on MyQ(Pixel2). $ adb shell am start -n "com.example.intentapplication/com.example.intentapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Connected to process 22745 on device 'emulator-5554'. Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page. I/tentapplicatio: Not late-enabling -Xcheck:jni (already on) E/tentapplicatio: Unknown bits set in runtime_flags: 0x8000 W/tentapplicatio: Unexpected CPU variant for X86 using defaults: x86 D/libEGL: Emulator has host GPU support, qemu.gles is set to 1. W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied) W/RenderThread: type=1400 audit(0.0:380): avc: denied { write } for name="property_service" dev="tmpfs" ino=7423 scontext=u:r:untrusted_app:s0:c137,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so W/tentapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) W/tentapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) D/HostConnection: HostConnection::get() New Host Connection established 0xd1279be0, tid 22776 D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0 D/EGL_emulation: eglCreateContext: 0xdc881860: maj 2 min 0 rcv 2 D/EGL_emulation: eglMakeCurrent: 0xdc881860: ver 2 0 (tinfo 0xdc8c7010) W/Gralloc3: mapper 3.x is not supported D/HostConnection: createUnique: call D/HostConnection: HostConnection::get() New Host Connection established 0xd127b710, tid 22776 D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 D/eglCodecCommon: allocate: Ask for block of size 0x1000 allocate: ioctl allocate returned offset 0x3ff00a000 size 0x2000 D/EGL_emulation: eglMakeCurrent: 0xdc881860: ver 2 0 (tinfo 0xdc8c7010) D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0

該当のソースコード

package com.example.intentapplication; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); setTitle("second Activity"); final Intent inIntent = getIntent(); final double hapValue = inIntent.getDoubleExtra("Num1", 0) / inIntent.getDoubleExtra("Num2", 1); Button buttonBack = (Button) findViewById(R.id.buttonBack); buttonBack.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent outIntent = new Intent(getApplicationContext(), MainActivity.class); outIntent.putExtra("Hap", String.format("%.2f", hapValue)); setResult(RESULT_OK, outIntent); finish(); } }); } }

該当のソースコード 2

package com.example.intentapplication; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("Main Activity"); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText editText1 = (EditText) findViewById(R.id.editText1); EditText editText2 = (EditText) findViewById(R.id.editText2); Intent intent = new Intent(getApplicationContext(), SecondActivity.class); intent.putExtra("Num1", Integer.parseInt(editText1.getText().toString())); intent.putExtra("Num2", Integer.parseInt(editText2.getText().toString())); startActivityForResult(intent, 0); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { int hap = data.getIntExtra("Hap", 0); Toast.makeText(getApplicationContext(), "Result" + hap, Toast.LENGTH_SHORT).show(); } } }

該当のソースコード xml

<?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" > <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="30dp" /> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="30dp" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="division" android:textSize="30dp" /> </LinearLayout>

該当のソースコード xml

<?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" > <Button android:id="@+id/buttonBack" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="30dp" android:text="Comeback" /> </LinearLayout>

試したこと

final double hapValue = inIntent.getDoubleExtra("Num1", 0)
/ inIntent.getDoubleExtra("Num2", 1);

outIntent.putExtra("Hap", String.format("%.2f", hapValue));

intからdoubleに切り替えて出力するときに表示する結果を "%.2f" これに変更したのですがエラーが発生しました。
このプログラムを回しても結果は0.0%のみ表示されます。
私が望むのは 12/23した時答えが0.52が出るように表示させることです.
解決方法をお願いします。

補足情報(FW/ツールのバージョンなど)

CPU AMD Ryzen™ 7 3700X
マザーボード B450M 박격포
メモリー 삼성 32기가
グラフィックカード 2070s
パワー 마이크로닉스 700W
SSD 삼성전자 970 EVO PLUS NVMe M.2 2280

このパソコンは韓国で買ったものですべて韓国製品です。 CPUだけ除いてです。

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

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

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

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

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

guest

回答1

0

ベストアンサー

インテント(Intent)を介して値をやり取りする上で、型の扱いに混乱があるようです。MainActivityではEditTextで値を取り出しているのですから、インテントではString型で値をそのままSecondActivityへ渡し、Double型での取り扱いはSecondActivity内で行うように整理しましょう。表示はToastを使ってMainActivityで行っているのですから、そこで表示したい形式に加工すれば良いです。

  1. MainActivity側

Java

1// MainActivity 2package com.example.intentapplication; 3 4import androidx.appcompat.app.AppCompatActivity; 5import android.content.Intent; 6import android.os.Bundle; 7import android.view.View; 8import android.widget.Button; 9import android.widget.EditText; 10import android.widget.Toast; 11 12public class MainActivity extends AppCompatActivity { 13 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_main); 18 setTitle("Main Activity"); 19 20 Button button = (Button) findViewById(R.id.button); 21 22 button.setOnClickListener(new View.OnClickListener() { 23 @Override 24 public void onClick(View view) { 25 EditText editText1 = (EditText) findViewById(R.id.editText1); 26 EditText editText2 = (EditText) findViewById(R.id.editText2); 27 28 Intent intent = new Intent(getApplicationContext(), SecondActivity.class); 29 /* 旧コード 30 intent.putExtra("Num1", Integer.parseInt(editText1.getText().toString())); 31 intent.putExtra("Num2", Integer.parseInt(editText2.getText().toString())); 32 */ 33 // EditTextのgetText().toString()の値をそのまま渡す 34 intent.putExtra("Num1", editText1.getText().toString()); 35 intent.putExtra("Num2", editText2.getText().toString()); 36 startActivityForResult(intent, 0); 37 } 38 }); 39 } 40 41 @Override 42 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 43 super.onActivityResult(requestCode, resultCode, data); 44 if (resultCode == RESULT_OK) { 45 /* 旧コード 46 int hap = data.getIntExtra("Hap", 0); 47 Toast.makeText(getApplicationContext(), "Result" + hap, Toast.LENGTH_SHORT).show(); 48 */ 49 50 // 素直にDoubleの値で取得する。 51 Double hap = data.getDoubleExtra("Hap", 0); 52 // ここで表示したい形式に加工する。 53 String s = String.format("%.2f", hap); 54 Toast.makeText(getApplicationContext(), "Result: " + s, Toast.LENGTH_SHORT).show(); 55 } 56 } 57}
  1. SecondActivity側

Java

1// SecondActivity 2package com.example.intentapplication; 3 4import android.content.Intent; 5import android.os.Bundle; 6import android.util.Log; 7import android.view.View; 8import android.widget.Button; 9 10import androidx.appcompat.app.AppCompatActivity; 11 12public class SecondActivity extends AppCompatActivity { 13 14 // フィールドにする。 15 private double hapValue = 0.0; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.second); 21 setTitle("second Activity"); 22 23 /* 旧コード 24 // ここでfinalで宣言しても意味がない。 25 final Intent inIntent = getIntent(); 26 final double hapValue = inIntent.getDoubleExtra("Num1", 0) 27 / inIntent.getDoubleExtra("Num2", 1); 28 */ 29 30 Intent inIntent = getIntent(); 31 if (inIntent != null) { 32 try { 33 String s; 34 // MainActivityからのIntentの値を素直にStringで取得する。 35 s = inIntent.getStringExtra("Num1"); 36 Double num1 = Double.parseDouble(s); 37 s = inIntent.getStringExtra("Num2"); 38 Double num2 = Double.parseDouble(s); 39 hapValue = num1 / num2; 40 Log.d("SecondActivity: ", 41 String.format("num1=%lf, num2=%lf, hapValue=%lf", num1, num2, hapValue)); 42 } catch (Exception ex) { 43 // Double.parseDouble()で発生する可能性のある例外はちゃんとハンドリングすること。 44 // この例では簡単に Exception で捕捉している。 45 Log.e("SecondActivity: ", ex.getMessage()); 46 } 47 } 48 49 Button buttonBack = (Button) findViewById(R.id.buttonBack); 50 buttonBack.setOnClickListener(new View.OnClickListener() { 51 public void onClick(View view) { 52 Intent outIntent = new Intent(getApplicationContext(), 53 MainActivity.class); 54 /* 旧コード 55 outIntent.putExtra("Hap", String.format("%.2f", hapValue)); 56 */ 57 // すでにDoubleの値になっているのだから、そのまま渡す 58 outIntent.putExtra("Hap", hapValue); 59 setResult(RESULT_OK, outIntent); 60 finish(); 61 } 62 }); 63 } 64} 65

投稿2020/11/22 07:05

dodox86

総合スコア9183

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

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

dodox86

2020/11/22 07:14

回答ではMainActivityからNum1, Num2をStringのまま渡していますが、SecondActivityが「2つの値で何らかの計算をする」位置づけであれば、Doubleの値に変換してから渡すことでも良いと思います。インテントで渡す値の「型」をどこで意識すべきか、との設計の問題です。
dodox86

2020/11/22 07:20

質問自体は「エラーの解決方法を教えて」ですが、エラーを誘発するようなデータフローであることが根本の原因だ、との観点からの回答です。
caffrey

2020/11/22 07:36

うわ、コードを完全に直してくださるとは思いませんでした。 今現在勉強している本が昔の本だからそうかもしれません。 エラーが発生して、いくら直そうと思ってもダメなので諦めていたんですがおかげで直せて気持ちいいです。 ありがとうございます。
caffrey

2020/11/22 07:39

更に、コードの説明までしてくださり、勉強にとても役立つと思います。
dodox86

2020/11/22 08:35

お役に立てたようで良かったです。引き続きがんばって、作りたいものを作ってください。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問