Black screen on android studio - java

Hi this is one of my old apps I am trying to fix, when I run this code I get a black screen but the app does not close. There are no errors and the fonts are fine so why is it not working? It works up until I start a new activity with this class. Thanks in advance. Also if you are able to suggest a better timer to use that would be great as when I used to use this app it did not work correctly.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:gravity="end">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/MainQuestion"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/SecondsLeft"
android:layout_gravity="center_horizontal"
/>
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Question1"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Question2"
android:text=""
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Choice3"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Choice4"
android:layout_gravity="center_horizontal" />
</LinearLayout>
package com.steam.mytriviaapp;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.*;
import android.os.CountDownTimer;
import android.content.Intent;
//necessary imports//
public class SportsCat extends AppCompatActivity {//extension needed for app//
TextView Question;//new textview variable to show the random question//
Button Choice1;//new button variable for answers//
Button Choice2;//^//
Button Choice3;//^//
Button Choice4;//^//
TextView SecondsLeft;//new textview variable//
int QuestionCounter =0;//question counter int set to 0//
public static Integer Points = 0;// points set/reset to 0 depending on if it is first game since it was opened //
boolean[] numbers = new boolean [4];//new boolean array with 4 numbers and are auto set to false, then later if true, they cannot be used, so it will not use samequestion//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sports_cat);//all of these linked to their respective xml variable to change sizing etc//
SecondsLeft = findViewById(R.id.SecondsLeft);
Question = findViewById(R.id.MainQuestion);
Choice1 = findViewById(R.id.Question1);
Choice2 = findViewById(R.id.Question2);
Choice3 = findViewById(R.id.Choice3);
Choice4 = findViewById(R.id.Choice4);
for(int k=0;k<=4;k++)
{
Body();
}
}
public void Body() {//new object//
String[] ArraySportsQuestions = {"Which NBA team holds the record for the most season wins in the Eastern Conference in history?",
"Which of these soccer players has won the most FIFA Ballon d'Ors after 2010?",
"Since what year was table tennis an Olympic sport?", "Which of these athletes had a video game made in honour of him?", "How many national sports does Canada have?"};//questions to be used//
final String[] ArraySportsQ1 = {"Boston Celtics", "Miami Heat", "Chicago Bulls", "Cleveland Cavaliers"};//question answers//
final String[] ArraySportsQ2 = {"Lionel Messi", "Cristiano Ronaldo", "Neymar", "Luis Suarez"};
final String[] ArraySportsQ3 = {"1988", "1974", "1984", "1996"};
final String[] ArraySportsQ4 = {"Shaun White", "Micheal Jordan", "Lionel Messi", "Shaun Federer"};
final String[] ArraySportsQ5 = {"2", "1", "3", "4"};
String[][] arrayofQs = {ArraySportsQ1, ArraySportsQ2, ArraySportsQ3,
ArraySportsQ4, ArraySportsQ5};//2D array//
QuestionCounter++;
Random gen = new Random();//new random generator gen//
int num = gen.nextInt(4);
while(numbers[num] = true)//makes sure it is not the same number//
{
num = gen.nextInt(4);
}
numbers[num] = true;
int x = gen.nextInt(3);
int y = gen.nextInt(3);
while(y==x) //^//
{
y = gen.nextInt(3);
}
int z = gen.nextInt(3);
while(z==x||z==y) {
z = gen.nextInt(3);
}
int u = gen.nextInt(3);
while(u==x||u==y||u==z) {
u = gen.nextInt(3);
}
new CountDownTimer(10000, 1000) {//android made countdown timer that icustomised//
public void onTick(long millisUntilFinished) {
SecondsLeft.setText("seconds remaining: " + millisUntilFinished /
1000);
}
public void onFinish() {
SecondsLeft.setText("done!");
}
}.start();
Typeface font2 = Typeface.createFromAsset(getAssets(), "subway.ttf");
Question.setTypeface(font2);
Question.setText(ArraySportsQuestions[num]);//randomising of questions andanswers//
Choice1.setText(arrayofQs[num][x]);//sets the answer to the set for thequestion, for example is num = 3, answer set 3, and then the buttons below to randomstrings in this inner array//
Choice2.setText(arrayofQs[num][y]);
Choice3.setText(arrayofQs[num][z]);
Choice4.setText(arrayofQs[num][u]);
Choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))// these are the answers//
{
Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();//a notification type message at the bottom of the screendisappearing after//
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else
{
Body();
}
}
}
});
Choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}
}
});
Choice3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}
}
});
Choice4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
}
}
});
}}

Related

How can I always remember the latest value from each sensor and write them into a file?

I develop an android app for my final year project. This app must collect sensor smartphone information from accelerometer, gyroscope and magnetometer and to save them into a file. So far I have done everything, but now I have some problem with sampling rate frequency of sensors, I do not exactly know how to deal with that.
I tried to use runnable method to delay 10ms for accelerometer and gyroscope and other runnable method to delay 100ms for magnetometer. I did that because with approximation I guess that the values for ACC and GYR are changing every 10 ms. while for MAG this value is changing every 100 ms.
I have NEVER used this runnable method, I am a beginner. My code works, it creates the file, but it has 0 bytes, which means that my code is not entering properly into the RUNNABLE method. What should I change?
package localhost.dev.liverpoolsensorsfusion;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class RecordDataActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mGyroscope;
private Sensor mMagnetometer;
Handler handler10;
Runnable runnable10;
Handler handler100;
Runnable runnable100;
CheckBox checkAcc;
CheckBox checkGyro;
CheckBox checkMagne;
TextView accX;
TextView accY;
TextView accZ;
TextView magneX;
TextView magneY;
TextView magneZ;
TextView gyroX;
TextView gyroY;
TextView gyroZ;
String FILENAME;
String content1;
String content2;
String content3;
FileOutputStream out;
Button startButton;
Button stopButton;
boolean startFlag = false;
EditText textData;
private Chronometer chronometer;
private boolean running_chronometer;
boolean isFirstSet = true;
private long currentTime;
private long startTime;
float[] acceleration = new float[3];
float[] gyroscope = new float[3];
float[] magnetometer = new float[3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_data);
// define sensors
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
// define text views
accX = (TextView) findViewById(R.id.raw_value_acc_x);
accY = (TextView) findViewById(R.id.raw_value_acc_y);
accZ = (TextView) findViewById(R.id.raw_value_acc_z);
magneX = (TextView) findViewById(R.id.raw_value_magne_x);
magneY = (TextView) findViewById(R.id.raw_value_magne_y);
magneZ = (TextView) findViewById(R.id.raw_value_magne_z);
gyroX = (TextView) findViewById(R.id.raw_value_gyro_x);
gyroY = (TextView) findViewById(R.id.raw_value_gyro_y);
gyroZ = (TextView) findViewById(R.id.raw_value_gyro_z);
// define checkboxes
checkAcc=(CheckBox)findViewById(R.id.checkBox);
checkGyro=(CheckBox)findViewById(R.id.checkBox2);
checkMagne=(CheckBox)findViewById(R.id.checkBox3);
// file name to be entered
textData = (EditText) findViewById(R.id.edit_text);
textData.setHint("Enter File Name here...");
// define chronometer
chronometer = findViewById(R.id.chronometer);
chronometer.setFormat("Recording: %s");
chronometer.setBase(SystemClock.elapsedRealtime());
// define start button
startButton = (Button) findViewById(R.id.button_record);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// create file
FILENAME= textData.getText() + ".csv";
if(!checkAcc.isChecked() && !checkGyro.isChecked() && !checkMagne.isChecked()) {
Toast.makeText(getBaseContext(), "Please select at least one sensor!",
Toast.LENGTH_LONG).show();
}else if(FILENAME.equals(".csv")){
Toast.makeText(getBaseContext(), "Please insert a valid name for the file to be created!",
Toast.LENGTH_LONG).show();
}else {
// set the recording button ON
startFlag = true;
// make the chronometer run
if (!running_chronometer) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
running_chronometer = true;
checkAcc.setClickable(false);
checkGyro.setClickable(false);
checkMagne.setClickable(false);
}
// add screen message to confirm that the app is recording
try{
textData.getText().clear();
Toast.makeText(getBaseContext(), "Start recording the data set", Toast.LENGTH_SHORT).show();
}catch(Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
// Turn off the record button
startButton.setClickable(false);
}
}
}); // starts button ends here
// define stop button
stopButton=(Button)findViewById(R.id.button_stop);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set the recording button OFF
// Stop writing on file
startFlag = false;
isFirstSet = true;
// if there is no file created state the following message
if(FILENAME==null || FILENAME.equals(".csv")){
Toast.makeText(getBaseContext(), "There is no recording taken in this moment!",
Toast.LENGTH_LONG).show();
}else{
// stop the chronometer
chronometer.stop();
running_chronometer = false;
checkAcc.setClickable(true);
checkGyro.setClickable(true);
checkMagne.setClickable(true);
// add screen message to confirm that the app has saved the data set
try{
Toast.makeText(getBaseContext(), "Saved to " + getFilesDir() + "/" + FILENAME,
Toast.LENGTH_LONG).show();
}catch(Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
// Turn back on the Record button
startButton.setClickable(true);
}
}); // stop button ends here
} // onCreate class ends here
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
#Override
public final void onSensorChanged(SensorEvent event) {
// when recording is ON do this
if (startFlag) {
if (checkAcc.isChecked() && event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
acceleration[0] = event.values[0];
acceleration[1] = event.values[1];
acceleration[2] = event.values[2];
}
if (checkGyro.isChecked() && event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
gyroscope[0] = event.values[0];
gyroscope[1] = event.values[1];
gyroscope[2] = event.values[2];
}
if (checkMagne.isChecked() && event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetometer[0] = event.values[0];
magnetometer[1] = event.values[1];
magnetometer[2] = event.values[2];
}
// initialise the content that will be written in the file
if (isFirstSet) {
startTime = System.currentTimeMillis();
isFirstSet = false;
}
currentTime = System.currentTimeMillis();
content1 = (currentTime - startTime) + "," + "ACC" + "," + acceleration[0] + "," + acceleration[1] + "," + acceleration[2] + "\n";
content2 = (currentTime - startTime) + "," + "GYR" + "," + gyroscope[0] + "," + gyroscope[1] + "," + gyroscope[2] + "\n";
content3 = (currentTime - startTime) + "," + "MAG" + "," + magnetometer[0] + "," +magnetometer[1] + "," + magnetometer[2] + "\n";
// as long the recording is ON
for (int i = 0; i < 1; i++){
try {
// create the file
out = openFileOutput(FILENAME, Context.MODE_APPEND);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// write to the file
if (checkAcc.isChecked() && checkGyro.isChecked() && checkMagne.isChecked()) {
if (startFlag) {
handler10 = new Handler();
runnable10 = new Runnable() {
#Override
public void run() {
handler10.postDelayed(this, 10);
updateAccText();
updateGyroText();
try {
out.write(content1.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
handler100 = new Handler();
runnable100 = new Runnable() {
#Override
public void run() {
handler100.postDelayed(this, 100);
updateMagneText();
try {
out.write(content3.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
} else if (checkAcc.isChecked() && checkGyro.isChecked()) {
if (startFlag) {
runnable10 = new Runnable() {
#Override
public void run() {
handler10.postDelayed(this, 10);
updateAccText();
updateGyroText();
try {
out.write(content1.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
} else if (checkAcc.isChecked() && checkMagne.isChecked()) {
if (startFlag) {
runnable10 = new Runnable() {
#Override
public void run() {
handler10.postDelayed(this, 10);
updateAccText();
try {
out.write(content1.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
runnable100 = new Runnable() {
#Override
public void run() {
handler100.postDelayed(this, 100);
updateMagneText();
try {
out.write(content3.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
} else if (checkGyro.isChecked() && checkMagne.isChecked()) {
if (startFlag) {
runnable10 = new Runnable() {
#Override
public void run() {
handler10.postDelayed(this, 10);
updateGyroText();
try {
out.write(content2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
runnable100 = new Runnable() {
#Override
public void run() {
handler100.postDelayed(this, 100);
updateMagneText();
try {
out.write(content3.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
} else if (checkAcc.isChecked()) {
if (startFlag) {
runnable10 = new Runnable() {
#Override
public void run() {
handler10.postDelayed(this, 10);
updateAccText();
try {
out.write(content1.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
} else if (checkGyro.isChecked()) {
if (startFlag) {
runnable10 = new Runnable() {
#Override
public void run() {
handler10.postDelayed(this, 10);
updateGyroText();
try {
out.write(content2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
} else if (checkMagne.isChecked()) {
if (startFlag) {
runnable100 = new Runnable() {
#Override
public void run() {
handler100.postDelayed(this, 100);
updateMagneText();
try {
out.write(content3.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
}
} // for loop end
}
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
protected void updateAccText(){
// Update the gyroscope data
accX.setText(String.format("%.6f", acceleration[0]));
accY.setText(String.format("%.6f", acceleration[1]));
accZ.setText(String.format("%.6f", acceleration[2]));
}
protected void updateGyroText(){
// Update the gyroscope data
gyroX.setText(String.format("%.6f", gyroscope[0]));
gyroY.setText(String.format("%.6f", gyroscope[1]));
gyroZ.setText(String.format("%.6f", gyroscope[2]));
}
protected void updateMagneText(){
// Update the gyroscope data
magneX.setText(String.format("%.6f", magnetometer[0]));
magneY.setText(String.format("%.6f", magnetometer[1]));
magneZ.setText(String.format("%.6f", magnetometer[2]));
}
}
When I press the record (start) button, I expect to create a .csv file that saves every single value from each checked (chosen) sensor before it was changed and so on until the user is pressing the save (stop) button.
You create a runnable code block, but never execute it. Call this when you create a runnable and want to set it running:
new Thread(myRunnable).start();
In the end I have managed to do it.
I save the value for GYR every 5 ms and MAG every 100 ms, and if the saved value is still equal with the new value then wait and write when they are different. I think this is a good example.
I will let the code here, maybe it could help other people:
Java:
package localhost.dev.liverpoolsensorsfusion;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class RecordDataActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mGyroscope;
private Sensor mMagnetometer;
CheckBox checkAcc;
CheckBox checkGyro;
CheckBox checkMagne;
TextView accX;
TextView accY;
TextView accZ;
TextView magneX;
TextView magneY;
TextView magneZ;
TextView gyroX;
TextView gyroY;
TextView gyroZ;
String FILENAME;
String content1;
String content2;
String content3;
FileOutputStream out;
Button startButton;
Button stopButton;
boolean isFirstSet = true;
boolean startFlag = false;
EditText textData;
private Chronometer chronometer;
private boolean running_chronometer;
private long currentTime;
private long startTime;
float[] acceleration = new float[3];
float[] gyroscope = new float[3];
float[] magnetometer = new float[3];
float[] new_gyroscope = new float[3];
float[] new_magnetometer = new float[3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_data);
// define sensors
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
// define text views
accX = (TextView) findViewById(R.id.raw_value_acc_x);
accY = (TextView) findViewById(R.id.raw_value_acc_y);
accZ = (TextView) findViewById(R.id.raw_value_acc_z);
magneX = (TextView) findViewById(R.id.raw_value_magne_x);
magneY = (TextView) findViewById(R.id.raw_value_magne_y);
magneZ = (TextView) findViewById(R.id.raw_value_magne_z);
gyroX = (TextView) findViewById(R.id.raw_value_gyro_x);
gyroY = (TextView) findViewById(R.id.raw_value_gyro_y);
gyroZ = (TextView) findViewById(R.id.raw_value_gyro_z);
// define checkboxes
checkAcc=(CheckBox)findViewById(R.id.checkBox);
checkGyro=(CheckBox)findViewById(R.id.checkBox2);
checkMagne=(CheckBox)findViewById(R.id.checkBox3);
// file name to be entered
textData = (EditText) findViewById(R.id.edit_text);
textData.setHint("Enter File Name here...");
// define chronometer
chronometer = findViewById(R.id.chronometer);
chronometer.setFormat("Recording: %s");
chronometer.setBase(SystemClock.elapsedRealtime());
// define start button
startButton = (Button) findViewById(R.id.button_record);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// create file
FILENAME= textData.getText() + ".csv";
if(!checkAcc.isChecked() && !checkGyro.isChecked() && !checkMagne.isChecked()) {
Toast.makeText(getBaseContext(), "Please select at least one sensor!",
Toast.LENGTH_LONG).show();
}else if(FILENAME.equals(".csv")){
Toast.makeText(getBaseContext(), "Please insert a valid name for the file to be created!",
Toast.LENGTH_LONG).show();
}else {
// set the recording button ON
startFlag = true;
// make the chronometer run
if (!running_chronometer) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
running_chronometer = true;
checkAcc.setClickable(false);
checkGyro.setClickable(false);
checkMagne.setClickable(false);
}
// add screen message to confirm that the app is recording
try{
textData.getText().clear();
Toast.makeText(getBaseContext(), "Start recording the data set", Toast.LENGTH_SHORT).show();
}catch(Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
// Turn off the record button
startButton.setClickable(false);
}
}
}); // starts button ends here
// define stop button
stopButton=(Button)findViewById(R.id.button_stop);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set the recording button OFF
// Stop writing on file
startFlag = false;
// if there is no file created state the following message
if(FILENAME==null || FILENAME.equals(".csv")){
Toast.makeText(getBaseContext(), "There is no recording taken in this moment!",
Toast.LENGTH_LONG).show();
}else{
// stop the chronometer
chronometer.stop();
running_chronometer = false;
checkAcc.setClickable(true);
checkGyro.setClickable(true);
checkMagne.setClickable(true);
// add screen message to confirm that the app has saved the data set
try{
Toast.makeText(getBaseContext(), "Saved to " + getFilesDir() + "/" + FILENAME,
Toast.LENGTH_LONG).show();
}catch(Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
// Turn back on the Record button
startButton.setClickable(true);
}
}); // stop button ends here
} // onCreate class ends here
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
#Override
public final void onSensorChanged(SensorEvent event) {
if (startFlag) {
if (checkAcc.isChecked() && event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
acceleration[0] = event.values[0];
acceleration[1] = event.values[1];
acceleration[2] = event.values[2];
}
if (checkGyro.isChecked() && event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
gyroscope[0] = event.values[0];
gyroscope[1] = event.values[1];
gyroscope[2] = event.values[2];
}
if (checkMagne.isChecked() && event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetometer[0] = event.values[0];
magnetometer[1] = event.values[1];
magnetometer[2] = event.values[2];
}
// when recording is ON do this
// initialise the content that will be written in the file
if (isFirstSet) {
startTime = System.currentTimeMillis();
isFirstSet = false;
}
currentTime = System.currentTimeMillis();
content1 = (currentTime-startTime) + "," + "ACC" + "," + acceleration[0] + "," + acceleration[1] + "," + acceleration[2] + "\n";
content2 = (currentTime-startTime) + "," + "GYR" + "," + gyroscope[0] + "," + gyroscope[1] + "," + gyroscope[2] + "\n";
content3 = (currentTime-startTime) + "," + "MAG" + "," + magnetometer[0] + "," +magnetometer[1] + "," + magnetometer[2] + "\n";
// as long the recording is ON
for (int i = 0; i < 1; i++){
try {
// create the file
out = openFileOutput(FILENAME, Context.MODE_APPEND);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// write to the file
if (checkAcc.isChecked() && checkGyro.isChecked() && checkMagne.isChecked() && startFlag) {
updateAccText();
writeAcc();
updateGyroText();
HandleGyr();
if(new_gyroscope[0]==gyroscope[0] && new_gyroscope[1]== gyroscope[1] && new_gyroscope[2]==gyroscope[2]){
writeGyr();
}
updateMagneText();
HandleMag();
if(new_magnetometer[0]==magnetometer[0] && new_magnetometer[1] == magnetometer[1] && new_magnetometer[1] == magnetometer[1]){
writeMag();
}
} else if (checkAcc.isChecked() && checkGyro.isChecked() && startFlag) {
updateAccText();
updateGyroText();
writeAcc();
HandleGyr();
if(new_gyroscope[0]==gyroscope[0] && new_gyroscope[1]== gyroscope[1] && new_gyroscope[2]==gyroscope[2]){
writeGyr();
}
} else if (checkAcc.isChecked() && checkMagne.isChecked() && startFlag) {
updateAccText();
updateMagneText();
writeAcc();
HandleMag();
if(new_magnetometer[0]==magnetometer[0] && new_magnetometer[1] == magnetometer[1] && new_magnetometer[1] == magnetometer[1]){
writeMag();
}
} else if (checkGyro.isChecked() && checkMagne.isChecked() && startFlag) {
updateGyroText();
updateMagneText();
HandleGyr();
HandleMag();
if(new_gyroscope[0]==gyroscope[0] && new_gyroscope[1]== gyroscope[1] && new_gyroscope[2]==gyroscope[2]){
writeGyr();
}
if(new_magnetometer[0]==magnetometer[0] && new_magnetometer[1] == magnetometer[1] && new_magnetometer[1] == magnetometer[1]){
writeMag();
}
} else if (checkAcc.isChecked() && startFlag) {
updateAccText();
writeAcc();
} else if (checkGyro.isChecked() && startFlag) {
updateGyroText();
writeGyr();
} else if (checkMagne.isChecked()) {
updateAccText();
writeAcc();
}
} // for loop end
}
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
protected void updateAccText(){
// Update the gyroscope data
accX.setText(String.format("%.6f", acceleration[0]));
accY.setText(String.format("%.6f", acceleration[1]));
accZ.setText(String.format("%.6f", acceleration[2]));
}
protected void updateGyroText(){
// Update the gyroscope data
gyroX.setText(String.format("%.6f", gyroscope[0]));
gyroY.setText(String.format("%.6f", gyroscope[1]));
gyroZ.setText(String.format("%.6f", gyroscope[2]));
}
protected void updateMagneText(){
// Update the gyroscope data
magneX.setText(String.format("%.6f", magnetometer[0]));
magneY.setText(String.format("%.6f", magnetometer[1]));
magneZ.setText(String.format("%.6f", magnetometer[2]));
}
// Adjust sampling rate for Gyroscope
public void HandleGyr(){
Handler handlerGyroscope = new Handler();
handlerGyroscope.postDelayed(new Runnable() {
#Override
public void run() {
new_gyroscope[0]=gyroscope[0];
new_gyroscope[1]=gyroscope[1];
new_gyroscope[2]=gyroscope[2];
}
}, 5);
}
// Adjust sampling rate for Magnetometer
public void HandleMag(){
Handler handlerMagnetometer = new Handler();
handlerMagnetometer.postDelayed(new Runnable() {
#Override
public void run() {
new_magnetometer[0]=magnetometer[0];
new_magnetometer[1]=magnetometer[1];
new_magnetometer[2]=magnetometer[2];
}
}, 100);
}
public void writeAcc(){
try {
out.write(content1.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeGyr(){
try {
out.write(content2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeMag(){
try {
out.write(content3.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RecordDataActivity">
<TextView
android:id="#+id/raw_label_acc_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/checkBox"
android:layout_marginStart="133dp"
android:paddingRight="20dp"
android:text="X:"
android:textColor="#color/graphX" />
<TextView
android:id="#+id/raw_label_acc_y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="133dp"
android:layout_below="#+id/raw_label_acc_x"
android:paddingRight="20dp"
android:text="Y:"
android:textColor="#color/graphY" />
<TextView
android:id="#+id/raw_label_acc_z"
android:layout_width="wrap_content"
android:layout_marginStart="133dp"
android:layout_height="wrap_content"
android:layout_below="#+id/raw_label_acc_y"
android:paddingRight="20dp"
android:text="Z:"
android:textColor="#color/graphZ" />
<TextView
android:id="#+id/raw_value_acc_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_acc_x"
android:layout_alignBottom="#+id/raw_label_acc_x"
android:layout_toEndOf="#+id/raw_label_acc_x"
android:textColor="#color/graphX" />
<TextView
android:id="#+id/raw_value_acc_y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_acc_y"
android:layout_alignBottom="#+id/raw_label_acc_y"
android:layout_toEndOf="#+id/raw_label_acc_y"
android:textColor="#color/graphY" />
<TextView
android:id="#+id/raw_value_acc_z"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_acc_z"
android:layout_alignBottom="#+id/raw_label_acc_z"
android:layout_toEndOf="#+id/raw_label_acc_z"
android:textColor="#color/graphZ" />
<TextView
android:id="#+id/raw_label_gyro_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/checkBox2"
android:layout_marginStart="133dp"
android:paddingRight="20dp"
android:text="X:"
android:textColor="#color/graphX" />
<TextView
android:id="#+id/raw_label_gyro_y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="133dp"
android:layout_below="#+id/raw_label_gyro_x"
android:paddingRight="20dp"
android:text="Y:"
android:textColor="#color/graphY" />
<TextView
android:id="#+id/raw_label_gyro_z"
android:layout_width="wrap_content"
android:layout_marginStart="133dp"
android:layout_height="wrap_content"
android:layout_below="#+id/raw_label_gyro_y"
android:paddingRight="20dp"
android:text="Z:"
android:textColor="#color/graphZ" />
<TextView
android:id="#+id/raw_value_gyro_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_gyro_x"
android:layout_alignBottom="#+id/raw_label_gyro_x"
android:layout_toEndOf="#+id/raw_label_gyro_x"
android:textColor="#color/graphX" />
<TextView
android:id="#+id/raw_value_gyro_y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_gyro_y"
android:layout_alignBottom="#+id/raw_label_gyro_y"
android:layout_toEndOf="#+id/raw_label_gyro_y"
android:textColor="#color/graphY" />
<TextView
android:id="#+id/raw_value_gyro_z"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_gyro_z"
android:layout_alignBottom="#+id/raw_label_gyro_z"
android:layout_toEndOf="#+id/raw_label_gyro_z"
android:textColor="#color/graphZ" />
<TextView
android:id="#+id/raw_label_magne_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/checkBox3"
android:layout_marginStart="133dp"
android:paddingRight="20dp"
android:text="X:"
android:textColor="#color/graphX" />
<TextView
android:id="#+id/raw_label_magne_y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="133dp"
android:layout_below="#+id/raw_label_magne_x"
android:paddingRight="20dp"
android:text="Y:"
android:textColor="#color/graphY" />
<TextView
android:id="#+id/raw_label_magne_z"
android:layout_width="wrap_content"
android:layout_marginStart="133dp"
android:layout_height="wrap_content"
android:layout_below="#+id/raw_label_magne_y"
android:paddingRight="20dp"
android:text="Z:"
android:textColor="#color/graphZ" />
<TextView
android:id="#+id/raw_value_magne_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_magne_x"
android:layout_alignBottom="#+id/raw_label_magne_x"
android:layout_toEndOf="#+id/raw_label_magne_x"
android:textColor="#color/graphX" />
<TextView
android:id="#+id/raw_value_magne_y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_magne_y"
android:layout_alignBottom="#+id/raw_label_magne_y"
android:layout_toEndOf="#+id/raw_label_magne_y"
android:textColor="#color/graphY" />
<TextView
android:id="#+id/raw_value_magne_z"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/raw_label_magne_z"
android:layout_alignBottom="#+id/raw_label_magne_z"
android:layout_toEndOf="#+id/raw_label_magne_z"
android:textColor="#color/graphZ" />
<Chronometer
android:id="#+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="193dp"
android:textSize="22sp" />
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="58dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="#drawable/rounded_edittext"
android:inputType="" />
<Button
android:id="#+id/button_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="126dp"
android:background="#drawable/button_quit"
android:shadowColor="#8A8A8A"
android:shadowDx="0"
android:shadowDy="1"
android:text="#string/record"
android:textColor="#FFF1D6"
android:textSize="18sp"
tools:ignore="OnClick"
tools:text="Record" />
<Button
android:id="#+id/button_stop"
android:layout_width="181dp"
android:layout_height="38dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="79dp"
android:background="#drawable/button_bulb_led"
android:shadowColor="#8A8A8A"
android:shadowDx="0"
android:shadowDy="1"
android:text="#string/save"
android:textColor="#FFF1D6"
android:textSize="18sp"
tools:ignore="OnClick"
tools:text="Save" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/accelerometer"
android:textSize="20sp" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/button_record"
android:layout_below="#+id/raw_label_acc_z"
android:text="#string/gyroscope"
android:textSize="20sp" />
<CheckBox
android:id="#+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/raw_label_gyro_z"
android:layout_centerHorizontal="true"
android:text="#string/magnetometer"
android:textSize="20sp" />
</RelativeLayout>

android.view.InflateException Binary XML file line #26 Error inflating class EditText

I am getting tired fixing this problem. the app does not execute it always show me this error Binary XML file line #26: Error inflating class EditText. I don't understand how to fix this problem.
This is my activity_members.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.constraint.ConstraintLayout
android:id="#+id/newMeetScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
tools:layout_editor_absoluteX="384dp">
<ImageView
android:id="#+id/imageView3"
android:layout_width="0dp"
android:layout_height="54dp"
android:src="#drawable/gradient"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/edit_search"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="11dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="13dp"
android:layout_marginBottom="7dp"
android:background="#drawable/radius_edit_text"
android:drawableLeft="#drawable/ic_search"
android:drawablePadding="3dp"
android:hint="Поиск"
android:imeOptions="actionGo"
android:inputType="text"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#9b9a9a"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btnDone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/btnDone"
android:layout_width="52dp"
android:layout_height="50dp"
android:background="#android:drawable/list_selector_background"
android:src="#drawable/ic_done"
android:textColor="#color/colorProjectTextWhite"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/edit_search"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
<android.support.v7.widget.RecyclerView
android:background="#color/colorBackgroundLight"
android:id="#+id/membersList"
android:scrollbars="vertical"
android:layout_marginTop="0dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
And this is my MembersActivity.java class.
public class MembersActivity extends AppCompatActivity {
private static final int REQUEST_CODE_READ_CONTACTS = 1;
private static boolean READ_CONTACTS_GRANTED = false;
RecyclerView members;
ArrayList<String> contacts = new ArrayList<String>();
ArrayList<String> tell = new ArrayList<String>();
UserAdapter adapter;
User user;
ArrayList<User> users = new ArrayList<>();
ImageButton btnDone;
StringBuilder stringBuilder = null;
EditText editSearch;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_members);
members = findViewById(R.id.membersList);
btnDone = findViewById(R.id.btnDone);
editSearch = findViewById(R.id.edit_search);
int hasReadContactPermission = ContextCompat.checkSelfPermission(Objects.requireNonNull(this), Manifest.permission.READ_CONTACTS);
if (hasReadContactPermission == PackageManager.PERMISSION_GRANTED) {
READ_CONTACTS_GRANTED = true;
} else {
ActivityCompat.requestPermissions(Objects.requireNonNull(this), new
String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE_READ_CONTACTS);
}
if (READ_CONTACTS_GRANTED) {
getContacts();
}
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stringBuilder = new StringBuilder();
int i=0;
char ch = ',';
do{
User user = adapter.checkedUsers.get(i);
if(i == adapter.checkedUsers.size()-1) ch = '.';
stringBuilder.append(user.getName() + ch);
if(i != adapter.checkedUsers.size() -1) {
stringBuilder.append("\n");
}
i++;
} while (i < adapter.checkedUsers.size());
if(adapter.checkedUsers.size() > 0) {
Intent intent = new Intent();
intent.putExtra("names", stringBuilder.toString());
setResult(RESULT_OK, intent);
finish();
} else {
Toast.makeText(MembersActivity.this, "Пожалуйста, выберите друзей", Toast.LENGTH_LONG).show();
}
}
});
editSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
adapter.getFilter().filter(charSequence);
return;
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_READ_CONTACTS:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
READ_CONTACTS_GRANTED = true;
}
}
if (READ_CONTACTS_GRANTED) {
getContacts();
}
else {
Toast.makeText(this, "Требуется установить разрешения", Toast.LENGTH_LONG).show();
}
}
public void getContacts() {
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI =
ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID =
ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = Objects.requireNonNull(this).getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
contacts.add(name);
Cursor phoneCursor =
contentResolver.query(PhoneCONTENT_URI, null,
Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
tell.add(phoneNumber);
}
}
}
}
if(tell.size() > contacts.size()) {
for(int i=0; i <contacts.size(); i++) {
user = new User(tell.get(i), contacts.get(i));
users.add(user);
}
} else {
for(int i=0; i < tell.size(); i++) {
user = new User(tell.get(i), contacts.get(i));
users.add(user);
}
}
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
adapter = new UserAdapter(users, this);
members.setLayoutManager(mLayoutManager);
members.setItemAnimator(new DefaultItemAnimator());
members.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
members.setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
Please, help me fix this problem.
You need to set the width and height of your EditText in your layout file you cannot set these properties to 0dp. If you want to set this according to screen size then you can use layout_weight in your xml.Here you can know about layout_weight usage
If you are using constraintLayout in your layout you can see this link. Responsive layout designing with constraint layout

Android app - Inputting integers from buttons depending on number of presses

I'm writing a calculator app for android using android studio. I want to used 4 buttons for inputting values and functions. However the way I am currently doing it takes the input from the text written on the button. So for my button 1/2/3 when this is pressed 1/2/3 is passed to the textView.
Below is my MainActivity:
package com.example.myfirstapp;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Equal button
/*findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});*/
}
}
and my activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="right|center_vertical"
android:maxLength="16"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:typeface="serif" />
<!--<Button-->
<!--android:id="#+id/equal1"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="100dp"-->
<!--android:text="="-->
<!--/>-->
<Button
android:id="#+id/equal2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="="
android:layout_alignParentBottom="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/txtScreen"
android:orientation="vertical"
android:layout_above="#id/equal2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/onetwothree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1/2/3"/>
<Button
android:id="#+id/fourfivesix"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4/5/6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/seveneightninezero"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7/8/9/0"/>
<Button
android:id="#+id/operators"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="+-*/"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Will it be possible for me to get the input of 1, 2 or 3 from my first button for example? So on 1 press you get 1, 2 press gives 2 etc.
Any suggestions/ ideas on how I can move forward with this are greatly appreciated.
Kind Regards,
Ben
You could use a timer or delay variable to detect single, double or triple taps. This post may be of interest. If the time interval is not a factor, you could just keep track of the last pressed button and if the same button is being pressed again, update the text accordingly.
If you follow approach one, the code for the click listener for button onetwothree may be something like this (I commented out setNumericOnClickListener() and setOperatorOnClickListener(); in mainActivity onCreate and added the following):
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return true;
}
});
Complete MainActivity:
package com.example.myfirstapp;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
// setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
// setOperatorOnClickListener();
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return false;
}
});
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
}
}
You can take all numbers when doing some operation
(Button) plusBtn = (Button) findViewById(R.id.plusBtn);
plusBtn.setOnClickListener(new OnClickListener(){
#Override
public voidonClick(View v){
number1 = Integer.parseInt(txtScreen.getText().toString());
});
Where number1 is global int. But I don't know how it can help you and if it is a good approach. You could find a better solution, just remember how to parse the String from your TextView to Integer for your calculation.

Valor Wave F7020 android device

Hi everyone is there anybody who has ever worked with Valor Wave F7020? I want to be able to use the fingerprint capability of the device but most of the stuff are in chinese. I have their sample code but I don't know how to make it work.
When I run it whatever I press I get a response in chinese and the captions also are in in chinese
package com.hdsoft.fingerprint;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.pwv.gpctrl.fctrl;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
//import android.util.Log;
//import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class LibFpDemo extends Activity {
private static final int MSG_CMD = 0;
private static final int MSG_EXIT = 1;
private static final int MSG_INFO = 2;
private static final int MSG_FIND = 3;
private static final int MSG_CANCEL = 4;
private boolean bContinue = true;
private fctrl gpctrl = new fctrl();
private Button btOpen, btImage, btEnrol, btMatch, btEmpty, btCancel;
private TextView tvInfo;
private static final String TAG = "finger";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpctrl.SetValue(32, 1);
gpctrl.GetValue(32);
tvInfo = (TextView)findViewById(R.id.tvInfo);
// btOpen = (Button)findViewById(R.id.btOpen);
btImage = (Button)findViewById(R.id.btImage);
btEnrol = (Button)findViewById(R.id.btEnrol);
btMatch = (Button)findViewById(R.id.btMatch);
btEmpty = (Button)findViewById(R.id.btEmpty);
btCancel = (Button)findViewById(R.id.btCancel);
final ImageView iv = (ImageView)findViewById(R.id.imageView1);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_CMD:
tvInfo.setText(LibFp.GetError(msg.arg1));
if (msg.arg1 == LibFp.FP_OK) {
optFinish();
}
else if (msg.arg1 == LibFp.FP_ERROR_DRIVE) {
closeDrive();
}
break;
case MSG_EXIT:
tvInfo.setText(LibFp.GetError(msg.arg1));
if (msg.arg1 == LibFp.FP_ERROR_DRIVE) {
closeDrive();
}
else {
optFinish();
}
break;
case MSG_INFO:
switch (msg.arg1) {
case 0:
tvInfo.setText("¼ÈëÖ¸ÎÆ, Çë°´ÊÖÖ¸...");
break;
case 1:
tvInfo.setText("ÇëÒÆ¿ªÊÖÖ¸...");
break;
case 2:
tvInfo.setText("Ö¸ÎƳɹ¦Èë¿â, µØÖ·±àºÅ = " + msg.arg2 + ", Çë°´ÊÖÖ¸¼ÌÐø¼Èë...");
break;
default:
break;
}
break;
case MSG_FIND:
optFinish();
tvInfo.setText("Ö¸ÎÆÆ¥Åä³É¹¦, ´æ·ÅµØÖ· = " + msg.arg1 + "±È¶ÔµÃ·Ö = " + msg.arg2);
break;
case MSG_CANCEL:
bContinue = true;
optFinish();
switch (msg.arg1) {
case 0:
tvInfo.setText("²Ù×÷ÒÑÈ¡Ïû...");
break;
default:
break;
}
break;
default:
break;
}
super.handleMessage(msg);
}
};
openDrive();
// btOpen.setOnClickListener(new View.OnClickListener()
// {
// #Override
// public void onClick(View v)
// {
// int nRet = LibFp.FpOpenEx((short)0x2109, (short)0x7638);
// Toast.makeText(LibFpDemo.this,nRet+"111", Toast.LENGTH_SHORT).show();
// if (nRet == LibFp.FP_ERROR_OPEN) {
// LibFp.GetRootRight();
// Toast.makeText(LibFpDemo.this,nRet+"22222222", Toast.LENGTH_SHORT).show();
// nRet = LibFp.FpOpenEx((short)0x2109, (short)0x7638);
// Toast.makeText(LibFpDemo.this,nRet+"444444444444444444", Toast.LENGTH_SHORT).show();
// }
// Toast.makeText(LibFpDemo.this,nRet+"5555555555555555555555555555555", Toast.LENGTH_SHORT).show();
// if (nRet == LibFp.FP_OK) {
// openDrive();
// }
// else {
// System.out.println(nRet+"444444444444444444");
// tvInfo.setText(LibFp.GetError(nRet));
// }
// }
// });
btImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
open();
optStart();
bContinue = true;
new Thread(new Runnable() {
public void run() {
byte bmpData[] = new byte[256*288+1078];
int bmpSize[] = new int[1];
while (bContinue) {
int nRet = LibFp.FpGetImage(0xffffffff, 10000);
if (nRet == LibFp.FP_OK) {
if ((nRet = LibFp.FpUpBMP(0xffffffff, bmpData, 256*288 + 1078, bmpSize, 10000)) == LibFp.FP_OK) {
final Bitmap bm = BitmapFactory.decodeByteArray(bmpData, 0, 256*288 + 1078);
iv.post(new Runnable() {
public void run() {
iv.setImageBitmap(bm);
}
});
}
}
else{
sendInfo(handler, MSG_CMD, 2);
}
// if (nRet == LibFp.FP_NO_FINGER) {
// try {
// Thread.sleep(150);
// } catch (InterruptedException e) {
// }
// }
// else {
// return;
// }
}
sendInfo(handler, MSG_CANCEL, 0);
}}).start();
}
});
btEnrol.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
open();
optStart();
bContinue = true;
new Thread(new Runnable() {
public void run() {
byte nBufferId = 1;
byte bmpData[] = new byte[256*288+1078];
int bmpSize[] = new int[1];
short nPageId[] = new short[1];
if (LibFp.FpValidTempleteNum(0xffffffff, nPageId, 10000) != LibFp.FP_OK) return;
sendInfo(handler, MSG_INFO, 0);
while (bContinue) {
int nRet = LibFp.FpGetImage(0xffffffff, 10000);
if (nRet == LibFp.FP_OK) {
if ((nRet = LibFp.FpGenChar(0xffffffff, nBufferId, 10000)) == LibFp.FP_OK) {
if ((nRet = LibFp.FpGetImage(0xffffffff, 10000)) == LibFp.FP_OK) {
if ((nRet = LibFp.FpUpBMP(0xffffffff, bmpData, 256*288 + 1078, bmpSize, 10000)) == LibFp.FP_OK) {
final Bitmap bm = BitmapFactory.decodeByteArray(bmpData, 0, 256*288 + 1078);
iv.post(new Runnable() {
public void run() {
iv.setImageBitmap(bm);
}
});
sendInfo(handler, MSG_INFO, 1);
while ((nRet = LibFp.FpGetImage(0xffffffff, 10000)) != LibFp.FP_NO_FINGER) {
if (nRet != LibFp.FP_OK) {
sendInfo(handler, MSG_EXIT, nRet);
return;
}
if (!bContinue) {
sendInfo(handler, MSG_CANCEL, 0);
return;
}
try {
Thread.sleep(150);
} catch (InterruptedException e) {
}
}
}
}
if (nBufferId == 2) {
if ((nRet = LibFp.FpRegModel(0xffffffff, 10000))== LibFp.FP_OK) {
if ((nRet = LibFp.FpStoreChar(0xffffffff, nBufferId, nPageId[0], 10000)) == LibFp.FP_OK) {
sendInfo(handler, MSG_INFO, 2, nPageId[0]);
nBufferId = 1;
nPageId[0] += 1;
}
}
if (nRet != LibFp.FP_OK) {
sendInfo(handler, MSG_EXIT, nRet);
return;
}
}
else {
nBufferId = 2;
sendInfo(handler, MSG_INFO, 0);
}
}
}
if (nRet != LibFp.FP_OK && nRet != LibFp.FP_NO_FINGER) {
sendInfo(handler, MSG_EXIT, nRet);
return;
}
}
sendInfo(handler, MSG_CANCEL, 0);
}
}).start();
}
});
btMatch.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
open();
optStart();
bContinue = true;
new Thread(new Runnable() {
public void run() {
byte bmpData[] = new byte[256*288+1078];
int bmpSize[] = new int[1];
short nNum[] = new short[1];
short nAddr[] = new short[1];
short nScore[] = new short[1];
if (LibFp.FpValidTempleteNum(0xffffffff, nNum, 10000) != LibFp.FP_OK) return;
while (bContinue) {
int nRet = LibFp.FpGetImage(0xffffffff, 10000);
if (nRet == LibFp.FP_OK) {
if ((nRet = LibFp.FpGenChar(0xffffffff, (byte)1, 10000)) == LibFp.FP_OK) {
if ((nRet = LibFp.FpGetImage(0xffffffff, 10000)) == LibFp.FP_OK) {
if ((nRet = LibFp.FpUpBMP(0xffffffff, bmpData, 256*288 + 1078, bmpSize, 10000)) == LibFp.FP_OK) {
final Bitmap bm = BitmapFactory.decodeByteArray(bmpData, 0, 256*288 + 1078);
iv.post(new Runnable() {
public void run() {
iv.setImageBitmap(bm);
}
});
if ((nRet = LibFp.FpSearch(0xffffffff, (byte)1, (short)0, nNum[0], nAddr, nScore, 10000)) == LibFp.FP_OK) {
sendInfo(handler, MSG_FIND, nAddr[0], nScore[0]);
}
else {
sendInfo(handler, MSG_EXIT, nRet);
}
return;
}
}
}
}
if (nRet == LibFp.FP_NO_FINGER) {
sendInfo(handler, MSG_CMD, nRet);
}
else if (nRet != LibFp.FP_OK) {
sendInfo(handler, MSG_EXIT, nRet);
return;
}
}
sendInfo(handler, MSG_CANCEL, 0);
}
}).start();
}
});
btEmpty.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
open();
short nNum[] = new short[1];
int nRet = LibFp.FpValidTempleteNum(0xffffffff, nNum, 10000);
if (nRet == LibFp.FP_OK) {
if ((nRet = LibFp.FpEmpty(0xffffffff, 10000)) == LibFp.FP_OK) {
tvInfo.setText("Çå¿ÕÖ¸ÎÆ¿âÍê³É£¬×ܹ²Çå¿ÕÖ¸ÎÆ " + nNum[0]+ " Ïî");
return;
}
}
tvInfo.setText(LibFp.GetError(nRet));
}
});
btCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
bContinue = false;
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestroy");
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
public void onPause()
{
bContinue = false;
try {
Thread.sleep(600);
} catch (InterruptedException e) {
}
closeDrive();
super.onPause();
LibFp.FpClose();
}
private void sendInfo(Handler handler, int nMsg, int arg1){
Message msg = handler.obtainMessage();
msg.what = nMsg;
msg.arg1 = arg1;
handler.sendMessage(msg);
System.out.println("sendInfo1");
}
private void sendInfo(Handler handler, int nMsg, int arg1, int arg2){
Message msg = handler.obtainMessage();
msg.what = nMsg;
msg.arg1 = arg1;
msg.arg2 = arg2;
handler.sendMessage(msg);
System.out.println("sendInfo2");
}
private void optStart() {
btImage.setEnabled(false);
btEnrol.setEnabled(false);
btMatch.setEnabled(false);
btEmpty.setEnabled(false);
btCancel.setEnabled(true);
}
private void optFinish() {
btImage.setEnabled(true);
btEnrol.setEnabled(true);
btMatch.setEnabled(true);
btEmpty.setEnabled(true);
btCancel.setEnabled(false);
}
private void openDrive() {
//btOpen.setEnabled(false);
btImage.setEnabled(true);
btEnrol.setEnabled(true);
btMatch.setEnabled(true);
btEmpty.setEnabled(true);
btCancel.setEnabled(false);
tvInfo.setText("É豸ÒÑ´ò¿ª...");
}
private void closeDrive() {
//btOpen.setEnabled(true);
btImage.setEnabled(false);
btEnrol.setEnabled(false);
btMatch.setEnabled(false);
btEmpty.setEnabled(false);
btCancel.setEnabled(false);
tvInfo.setText("ÒѹرÕÉ豸£¬ÇëÖØдò¿ª...");
}
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
gpctrl.SetValue(32, 0);
gpctrl.GetValue(32);
this.finish();
}
public void open(){
int nRet = LibFp.FpOpenEx((short)0x2109, (short)0x7638);
if (nRet == LibFp.FP_ERROR_OPEN) {
LibFp.GetRootRight();
nRet = LibFp.FpOpenEx((short)0x2109, (short)0x7638);
}
if (nRet == LibFp.FP_OK) {
}
else {
tvInfo.setText(LibFp.GetError(nRet));
}
}
}
******************* activity_main.xml ****************
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- <LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/btOpen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/a1" />
</LinearLayout>
-->
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:orientation="horizontal" >
<Button
android:id="#+id/btImage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="#string/a2" />
<Button
android:id="#+id/btEnrol"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="#string/a3" />
<Button
android:id="#+id/btMatch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="#string/a4" />
<Button
android:id="#+id/btEmpty"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="#string/a5" />
<Button
android:id="#+id/btCancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="#string/a6" />
</LinearLayout>
<TextView
android:id="#+id/tvInfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout2"
android:layout_marginTop="29dp"
android:text="#string/hello_world"
tools:context=".MainActivity" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvInfo"
android:layout_marginLeft="58dp"
android:layout_marginTop="22dp"/>
<!-- android:src="#drawable/logo" -->
</RelativeLayout>
***************** strings.xml *****************
<resources>
<string name="app_name">fingerprint</string>
<string name="hello_world">Demo程序, 仅供参考!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="a1">打开设备</string>
<string name="a2">获取图像</string>
<string name="a3">录入指纹</string>
<string name="a4">指纹匹配</string>
<string name="a5">清空指纹库</string>
<string name="a6">取消操作</string>
</resources>
Here are the translations of the UI captions in the code snippet you posted.
A1 Open Device 打开设备
A2 Get Image 获取图像
A3 Fingerprint Entry 录入指纹
A4 Fingerprint Matching 指纹匹配
A5 Empty Fingerprint Database 清空指纹库
A6 Cancel 取消操作
Demo Program 程序
Hello world For reference only 仅供参考

Android Studio (Java): Continue prime number for loop on button press

I want to be able to display the next prime number each time the button is clicked but cannot find a way for it to work. Anybody help please?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button primeButton = (Button) findViewById(R.id.primeButton);
primeButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
TextView primeText = (TextView) findViewById(R.id.primeText);
int max = 500;
for(int i=2; i<=max; i++) {
boolean isPrimeNumber = true;
for (int j = 2; j <= i; j++) {
if (i % j == 0 ) {
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber){
primeText.setText(Integer.toString(i));
}
}
}
}
);
}
}
Try this
public class MainActivity extends Activity {
Button b;
int max = 500;
TextView vTextView;
int j = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
vTextView = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
vTextView.setText(i+"");
j = i+1;
break;
}
}
}
});
}
public boolean isPrimeNumber(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
To find out a prime number, prime numbers between two numbers and sum of a prime number
public class MainActivity extends AppCompatActivity {
private EditText etInput;
private EditText et_from, et_to;
private Button btnCheck, btn_print;
private TextView tvResult;
private int inputnumber;
private int fromNumber, toNumber;
private boolean isPrimeNumber = true;
private TextView tv_prime_sum;
private int primeNumbersSum;
private TextView tv_check;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(etInput.getText().toString().trim() != null && etInput.getText().toString().trim().length() > 0)) {
etInput.setError("Please enter the number");
} else {
inputnumber = Integer.parseInt(etInput.getText().toString());
for (int i = 2; i <= inputnumber / 2; i++) {
if (inputnumber % i == 0) {
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber) {
tv_check.setText("The given number " + inputnumber + " is a prime number");
} else {
tv_check.setText("The given number " + inputnumber + " is not a prime number");
}
isPrimeNumber = true;
}
}
});
btn_print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(et_from.getText().toString().trim() != null && et_from.getText().toString().trim().length() > 0)) {
et_from.setError("Please enter the number");
} else if (!(et_to.getText().toString().trim() != null && et_to.getText().toString().trim().length() > 0)) {
et_to.setError("Please enter the number");
} else {
fromNumber = Integer.parseInt(et_from.getText().toString());
toNumber = Integer.parseInt(et_to.getText().toString());
if (fromNumber > toNumber) {
fromNumber = fromNumber - toNumber;
toNumber = fromNumber + toNumber;
fromNumber = toNumber - fromNumber;
}
StringBuilder stringBuilder = new StringBuilder();
for (int j = fromNumber; j <= toNumber; j++) {
for (int i = 2; i <= j / 2; i++) {
if (j % i == 0) {
isPrimeNumber = false;
break;
} else {
isPrimeNumber = true;
}
}
if (isPrimeNumber) {
Log.v("Primenumber", "list" + j);
primeNumbersSum = primeNumbersSum + j;
stringBuilder.append(j);
stringBuilder.append(",");
} else {
}
}
tvResult.setText(stringBuilder.toString());
tv_prime_sum.setText("Total sum of prime numbers: " + primeNumbersSum);
isPrimeNumber = true;
primeNumbersSum = 0;
}
}
});
}
private void findViews() {
etInput = findViewById(R.id.et_input);
btnCheck = findViewById(R.id.btn_check);
tvResult = findViewById(R.id.tv_result);
tv_prime_sum = findViewById(R.id.tv_prime_sum);
et_from = findViewById(R.id.et_from);
et_to = findViewById(R.id.et_to);
btn_print = findViewById(R.id.btn_print);
tv_check = findViewById(R.id.tv_check);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/et_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="enter the number"
android:inputType="number"
android:visibility="visible" />
<Button
android:id="#+id/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_input"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="Check" />
<TextView
android:id="#+id/tv_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_check"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="print the number is prime or not" />
<EditText
android:id="#+id/et_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_check"
android:hint="from number"
android:inputType="number" />
<EditText
android:id="#+id/et_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et_from"
android:hint="to number"
android:inputType="number" />
<Button
android:id="#+id/btn_print"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_to"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="Print" />
<TextView
android:id="#+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_print"
android:layout_centerHorizontal="true"
android:text="prints the list of prime numbers" />
<TextView
android:id="#+id/tv_prime_sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_result"
android:layout_centerHorizontal="true"
android:layout_margin="10dp" />
</RelativeLayout>

Categories

Resources