Published Date : 2021年2月7日20:21

2. 成功確率を計算するAndroidアプリケーションの作成
2. Creating an Android Application to Calculate the Probability of Success


This blog has an English translation


ニコニコ動画にアップした動画のまとめ記事です。

This is a summary blog post about a video I uploaded to NicoNico.

細かい部分は動画を参考にしてください。

Please refer to the video for details.


目次

Table of Contents




① 動画の説明
① Video Description



前回の続きです。

Continued from last time.

アクティビティへの変移ボタンが押された時の処理を行うメソッドを作成します。

Create a method to handle when the transition to activity button is pressed.

グラフ用のアクティビティクラスを指定して、インテントのインスタンスを作成します。

Create an instance of the intent by specifying an activity class for the chart.

Intent intent = new Intent(this, DisplayLineChart.class);

もし変移ボタンが表示されているなら、プットエキストラメソッドを使用してユーザーによって入力された確率の値をグラフ用のアクティビティへ渡します。

If the transition button is displayed, use the put extra method to pass the value of the probability entered by the user to the activity for the chart.

if(showChartBtn.getVisibility() == View.VISIBLE) {
    intent.putExtra("SEND_DATA", (float) p);
}

そのあと、変移ボタンを非表示にして、グラフ用のアクティビティへ移動します。

Then hide the Move button and go to the activity for the chart.

showChartBtn.setVisibility(View.INVISIBLE);
startActivity(intent);

それでは折れ線グラフを表示するアクティビティの[DisplayLineChart.java]へ移動して、送られた変数を取り出し、実際にグラフを表示させるクラスファイルにその値を入れる処理を書きましょう。

Now go to the [DisplayLineChart.java] of the activity that displays the line chart, and write a process that takes the submitted variable and puts its value in the class file that actually displays the chart.

フロートの値を取り出す時はゲットフロートエキストラメソッドを使用します。

The getFloatExtra method is used to retrieve the float value.

Intent intent = getIntent();
float receivedData = intent.getFloatExtra("SEND_DATA", 0.0f);

エラーが起こるとデフォルトバリューに設定した値を使用するようになります。

If an error occurs, the default value is used.

では実際にグラフを表示させるクラスファイルの[DisplayView.java]を作成していきましょう。

Now let's create a class file [DisplayView.java] that will actually display the chart.

Viewクラスを拡張して、独自の折れ線グラフ用のViewクラスのサブクラスDisplayViewを作成しましょう。

Let's extend the View class to create a subclass of the View class, DisplayView, for our own line chart.

class DisplayView extends View {
}

DisplayViewのコンストラクタにコンテキストのオブジェクトをパラメータとして渡し、親クラスのコンストラクタに渡します。

You pass the object of the context as a parameter to the DisplayView constructor and pass it to the constructor of the parent class.

public DisplayView(Context context, float receivedData) {
    super(context);
}

このコンテキストとは、簡単に言ってしまえば、アプリ全体の環境情報等をAndroidのOS間で受け渡しをできるようにするためのインターフェイスの役割のようなものです。

To put it simply, this context is like the role of an interface that allows the environment information of the whole application to be transferred between Android OS.

そして、アンドロイド端末のディスプレイ情報(画面の幅等)を取得するために、DisplayMetricsのオブジェクトを作成しましょう。

Create a DisplayMetrics object to retrieve the display information (Screen width, etc.) of your Android device.

DisplayMetrics metrics = context.getApplicationContext().getResources().getDisplayMetrics();

テキストや図形の色等の情報を保持するPaintクラスの変数を宣言します。

Declare variables of the Paint class that hold information such as the color of text and geometry.

グラフの外枠の場合は線だけを表示する、テキストやグラフの場合は塗りつぶす等、図形やテキスト毎にスタイルを決めていく為、複数のPaint型の変数を用意します。

Multiple variables of type Paint are prepared to determine the style for each shape or text, such as displaying only lines in the case of the outer frame of the chart, or filling in the case of text or chart.

このフロートバッファー型の変数には折れ線グラフを描く為の座標が格納されます。

This FloatBuffer type variable stores coordinates for drawing line charts.

コンストラクタ内で変数を初期化していきます。

Initialize the variable in the constructor.

前回の時と同じように、色、画面の幅と高さ、外枠の大きさ等を決めていきます。

As before, we will decide the color, the width and height of the screen, the size of the outer frame, etc.

そして、受け取った確率の値を使って、試行回数よる確率の変化を計算します。

It then uses the received probability values to calculate the change in probability by number of trials.

しかし、受け取った確率がゼロならここの処理で無限ループになってしまいます。

However, if the probability of receiving is zero, the process will result in an infinite loop.

なので、適切な処理を[メインアクティビティ.java]の中の入力値を受け取る処理に書き足してください。

So add the appropriate processing to the processing that receives the input in [MainActivity.java].

[メインアクティビティ.java]の中でトーストを使った箇所のIf文の条件式をゼロの値を受け付けないように変えるだけです。

All you have to do is change the conditional expression in the If statement for the part of [Main Activity .java] where you used the toast so that it doesn't accept zero values.

目盛りのラインの数を10に設定します。

Set the number of graduation lines to 10.

上記で計算された試行回数が11未満なら目盛り線の数に合わせるようにします。

If the number of trials calculated above is less than 11, try to match the number of graduation lines.

折れ線グラフのラインを描画する為に、目盛りの数の4倍の値でFloatBufferを初期化します。

To draw lines in a line graph, initialize the FloatBuffer with a value four times the number of graduations.

何故4倍なのかは、For文の中身を見れば分かります。

You can see why it is quadrupling if you look inside the For statement.

この後に使われる予定の連続したラインを引くためのdrawLinesメソッドにはラインの最初のXとYの座標と最後のXとYの座標が格納されている変数が必要になります。

The drawLines method for drawing a series of lines that will be used later requires a variable containing the first and last X and Y coordinates of the line.

つまり、最初の目盛りから次の目盛りに線を引くためには、4つの座標情報が必要なので、目盛りの数に4倍の値のサイズを持つ配列変数が必要になってくるわけです。

In other words, to draw a line from the first tick mark to the next tick mark, you need four coordinates, so you need an array variable whose size is four times the number of tick marks.

実際に折れ線グラフの表示をするonDrawメソッドをオーバーライドします。

Override the onDraw method to actually display the bar chart.

onDrawメソッドには折れ線グラフの線やテキストや図形等を描画する為に必要なCanvasオブジェクトをパラメータとして渡します。

The onDraw method takes as a parameter a Canvas object which is needed to draw bar lines, text, graphics, etc.

まずはコンストラクタ内で初期化したPaintオブジェクト変数に色や線の幅、どのように図形を塗りつぶすかの情報を設定していきます。

First, you set the color, line width, and how you want to fill the shape in the Paint object variable that you initialized in the constructor.

setStyleメソッド内で使われているSTROKEは線のみを描画、FILL_AND_STROKEは線も含めて指定された座標内を指定された色で塗りつぶすことを意味しています。

STROKE, used in the setStyle method, only draws lines, while FILL_AND_STROKE means to fill the specified coordinates, including lines, with the specified color.

drawRectメソッドには左上のxとyの座標と右下のxとyの座標の四つの数値と、Paintオブジェクトを渡すことで、長方形を画面に描くことができます。

You can draw a rectangle on the screen by passing four numbers to the drawRect method, the upper left x and y coordinates, the lower right x and y coordinates, and a Paint object.

drawTextメソッドには表示したいテキストと、テキストのxとyの座標とPaintオブジェクトを渡してやれば、テキストを画面に表示できます。

You can use drawText to display text on the screen by passing the text you want to display, the x and y coordinates of the text, and a Paint object.

後は目盛り線と確率と試行回数のテキストの描画を行っていくだけです。

All you have to do is draw the scale lines and the probability and trials text.

最後に、どれだけ試行回数を重ねれば99.9%の成功確率になるのかのテキストを表示させ、折れ線グラフを先ほど説明したdrawLinesメソッドを使って描画します。

Finally, we show the text of how many tries to add up to a 99.9% probability of success, and draw a line chart using the drawLines method I described earlier.

各自で色々と試して、もっと良いアプリに仕上げてください。

Please try various things on your own and make it a better application.



以上です。お疲れ様です。

That's all. Thank you for your hard work.