I am trying to build an android app for my project in which if i input a certain number in TextView a new activity starts.
I have tried using Intent function and using getText from editText. I dont really understand whats the issue here.
I am new to android studio and also to programming, so i do not have much experience regarding it.
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.edt1);
float message = Float.valueOf(editText.getText().toString());
if (message == 123){
Intent intent = new Intent(this, SecondAcivity.class);
startActivity(intent);
}
}
public void but1script(View view) { editText.setText(editText.getText()+"1");
}
public void but2script(View view){
editText.setText(editText.getText()+"2");
}
public void but3script(View view){
editText.setText(editText.getText()+"3");
}
public void but4script(View view){
editText.setText(editText.getText()+"4");
}
public void but5script(View view){
editText.setText(editText.getText()+"5");
}
public void but6script(View view){
editText.setText(editText.getText()+"6");
}
public void but7script(View view){
editText.setText(editText.getText()+"7");
}
public void but8script(View view){
editText.setText(editText.getText()+"8");
}
public void but9script(View view) {
editText.setText(editText.getText()+"9");}
public void but0script(View view){
editText.setText(editText.getText()+"0");
}
public void butaddscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
additionscript = true;
}
else{
editText.setText("");
}
}
public void butsubscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
subtractionscript = true;
}
else{
editText.setText("");
}
}
public void butmultscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
multiplyscript = true;
}
else{
editText.setText("");
}
}
public void butdivscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
divisionscript = true;
}
else{
editText.setText("");
}
}
public void butequalscript(View view){
num2 = Float.parseFloat(editText.getText() + "");
if (additionscript == true) {
editText.setText(num1 + num2 + "");
additionscript = false;
}
else if (subtractionscript == true) {
editText.setText(num1 - num2 + "");
subtractionscript = false;
}
else if (multiplyscript == true) {
editText.setText(num1 * num2 + "");
multiplyscript = false;
}
else if (divisionscript == true) {
editText.setText(num1 / num2 + "");
divisionscript = false;
}
}
public void butclearscript(View view){
editText.setText("");
}
public void butdecscript(View view){
editText.setText(editText.getText()+".");
}
float num1;
float num2;
boolean additionscript;
boolean subtractionscript;
boolean divisionscript;
boolean multiplyscript;
EditText editText;
}
EDIT 1:
I changed my code to this but now i am facing another problem. On input of certain number the new activity starts but on switching to landscape mode the app crashes and none of the operator buttons like +,-,=,*,/ buttons are working.
The app is a basic calculator actually with a different layout in landscape mode and a certain number opens a new activity
package com.example.tanmaycalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edt1);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
float message = Float.valueOf(editText.getText().toString());
if (message == 123){
Intent intent = new Intent(MainActivity.this, EasterEgg.class);
startActivity(intent);
}
}
});
final Button but1 = (Button)findViewById(R.id.but1);
}
public void but1script(View view) { editText.setText(editText.getText()+"1");
}
public void but2script(View view){
editText.setText(editText.getText()+"2");
}
public void but3script(View view){
editText.setText(editText.getText()+"3");
}
public void but4script(View view){
editText.setText(editText.getText()+"4");
}
public void but5script(View view){
editText.setText(editText.getText()+"5");
}
public void but6script(View view){
editText.setText(editText.getText()+"6");
}
public void but7script(View view){
editText.setText(editText.getText()+"7");
}
public void but8script(View view){
editText.setText(editText.getText()+"8");
}
public void but9script(View view) {
editText.setText(editText.getText()+"9");}
public void but0script(View view){
editText.setText(editText.getText()+"0");
}
public void butaddscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
additionscript = true;
}
else{
editText.setText("");
}
}
public void butsubscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
subtractionscript = true;
}
else{
editText.setText("");
}
}
public void butmultscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
multiplyscript = true;
}
else{
editText.setText("");
}
}
public void butdivscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
divisionscript = true;
}
else{
editText.setText("");
}
}
public void butequalscript(View view){
num2 = Float.parseFloat(editText.getText() + "");
if (additionscript == true) {
editText.setText(num1 + num2 + "");
additionscript = false;
}
else if (subtractionscript == true) {
editText.setText(num1 - num2 + "");
subtractionscript = false;
}
else if (multiplyscript == true) {
editText.setText(num1 * num2 + "");
multiplyscript = false;
}
else if (divisionscript == true) {
editText.setText(num1 / num2 + "");
divisionscript = false;
}
}
public void butclearscript(View view){
editText.setText("");
}
public void butdecscript(View view){
editText.setText(editText.getText()+".");
}
float num1;
float num2;
boolean additionscript;
boolean subtractionscript;
boolean divisionscript;
boolean multiplyscript;
EditText editText;
}
UPDATE: I have found the ay to make it work i was making a mistake to take input as float instead of string. changing that has solved my problem thank you for helping me.
import androidx.appcompat.app.AppCompatActivity;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edt1);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String message = (editText.getText().toString());
if (message.equals("123")){
Intent intent = new Intent(MainActivity.this, EasterEgg.class);
startActivity(intent);
}
}
});
}
public void but1script(View view) { editText.setText(editText.getText()+"1"); }
public void but2script(View view){
editText.setText(editText.getText()+"2");
}
public void but3script(View view){
editText.setText(editText.getText()+"3");
}
public void but4script(View view){
editText.setText(editText.getText()+"4");
}
public void but5script(View view){
editText.setText(editText.getText()+"5");
}
public void but6script(View view){
editText.setText(editText.getText()+"6");
}
public void but7script(View view){
editText.setText(editText.getText()+"7");
}
public void but8script(View view){
editText.setText(editText.getText()+"8");
}
public void but9script(View view) { editText.setText(editText.getText()+"9");}
public void but0script(View view){
editText.setText(editText.getText()+"0");
}
public void butaddscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
additionscript = true;
}
else{
editText.setText("");
}
}
public void butsubscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
subtractionscript = true;
}
else{
editText.setText("");
}
}
public void butmultscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
multiplyscript = true;
}
else{
editText.setText("");
}
}
public void butdivscript(View view){
if (editText.getText() != null){
num1 = Float.parseFloat(editText.getText() + "");
editText.setText(null);
divisionscript = true;
}
else{
editText.setText("");
}
}
public void butequalscript(View view){
num2 = Float.parseFloat(editText.getText() + "");
if (additionscript == true) {
editText.setText(num1 + num2 + "");
additionscript = false;
}
else if (subtractionscript == true) {
editText.setText(num1 - num2 + "");
subtractionscript = false;
}
else if (multiplyscript == true) {
editText.setText(num1 * num2 + "");
multiplyscript = false;
}
else if (divisionscript == true) {
editText.setText(num1 / num2 + "");
divisionscript = false;
}
}
public void butclearscript(View view){
editText.setText("");
}
public void butdecscript(View view){
editText.setText(editText.getText()+".");
}
float num1;
float num2;
boolean additionscript;
boolean subtractionscript;
boolean divisionscript;
boolean multiplyscript;
EditText editText;
You are currently only checking the value once the activity is created, at which point the EditText is empty.
You need to check the value each time the Text gets changed, so take a look at this and put your current code to start the activity into the afterTextChanged method
Related
Pls, I'm having problems having a steady connection between my android app and my smartwatch, anytime the app connect with the watch, it connect and disconnect immediately. I actually use a custom crrp sdk for the project
This is the scan activity
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.crrepa.ble.CRPBleClient;
import com.crrepa.ble.conn.CRPBleDevice;
import com.crrepa.ble.conn.listener.CRPBleFirmwareUpgradeListener;
import com.crrepa.ble.scan.bean.CRPScanDevice;
import com.crrepa.ble.scan.callback.CRPScanCallback;
import com.crrepa.ble.trans.upgrade.bean.HSFirmwareInfo;
import com.crrepa.sdk.sample.PermissionUtils;
import com.crrepa.sdk.sample.R;
import com.crrepa.sdk.sample.SampleApplication;
import com.crrepa.sdk.sample.device.DeviceActivity;
import java.io.File;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ScanActivity extends AppCompatActivity {
private static final String TAG = "ScanActivity";
private static final int SCAN_PERIOD = 10 * 1000;
private static final int REQUEST_UPDATEBANDCONFIG = 4;
private static final String[] PERMISSION_UPDATEBANDCONFIG = new String[] {
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.ACCESS_COARSE_LOCATION"};
#BindView(R.id.btn_scan_toggle)
Button scanToggleBtn;
#BindView(R.id.scan_results)
RecyclerView scanResults;
#BindView(R.id.tv_firmware_fix_state)
TextView tvFirmwareFixState;
private CRPBleClient mBleClient;
private ScanResultsAdapter mResultsAdapter;
private boolean mScanState = false;
private static final String UPGRADE_APP_FILE_PATH = Environment.getExternalStorageDirectory().getPath()
+ File.separator + "crrepa" + File.separator + "app_band-hs.bin";
private static final String UPGRADE_USER_FILE_PATH = Environment.getExternalStorageDirectory().getPath()
+ File.separator + "crrepa" + File.separator + "usr.bin";
private static final String USER_START_ADDRESS = "23000";
// private static final String BAND_ADDRESS = "C1:C4:7C:DE:44:5B";
// private static final String BAND_ADDRESS = "D9:4D:C2:BB:F3:F4";
private static final String BAND_ADDRESS = "FB:09:C5:C7:1A:90";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
ButterKnife.bind(this);
mBleClient = SampleApplication.getBleClient(this);
configureResultList();
requestPermissions();
}
#Override
protected void onPause() {
super.onPause();
cancelScan();
}
#OnClick({R.id.btn_scan_toggle, R.id.btn_firmware_fix, R.id.btn_hs_upgrade})
public void onViewClicked(View view) {
if (!mBleClient.isBluetoothEnable()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBtIntent);
return;
}
switch (view.getId()) {
case R.id.btn_scan_toggle:
if (mScanState) {
cancelScan();
} else {
startScan();
}
break;
case R.id.btn_firmware_fix:
break;
case R.id.btn_hs_upgrade:
CRPBleClient bleClient = SampleApplication.getBleClient(this);
CRPBleDevice bleDevice = bleClient.getBleDevice(BAND_ADDRESS);
HSFirmwareInfo upgradeInfo = new HSFirmwareInfo();
upgradeInfo.setAppFilePath(UPGRADE_APP_FILE_PATH);
upgradeInfo.setUserFilePath(UPGRADE_USER_FILE_PATH);
upgradeInfo.setUserStartAddress(USER_START_ADDRESS);
break;
}
}
private void startScan() {
boolean success = mBleClient.scanDevice(new CRPScanCallback() {
#Override
public void onScanning(final CRPScanDevice device) {
Log.d(TAG, "address: " + device.getDevice().getAddress());
if (TextUtils.isEmpty(device.getDevice().getName())) {
return;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mResultsAdapter.addScanResult(device);
}
});
}
#Override
public void onScanComplete(List<CRPScanDevice> results) {
if (mScanState) {
mScanState = false;
updateButtonUIState();
}
}
}, SCAN_PERIOD);
if (success) {
mScanState = true;
updateButtonUIState();
mResultsAdapter.clearScanResults();
}
}
private void cancelScan() {
mBleClient.cancelScan();
}
private void configureResultList() {
scanResults.setHasFixedSize(true);
LinearLayoutManager recyclerLayoutManager = new LinearLayoutManager(this);
scanResults.setLayoutManager(recyclerLayoutManager);
mResultsAdapter = new ScanResultsAdapter();
scanResults.setAdapter(mResultsAdapter);
mResultsAdapter.setOnAdapterItemClickListener(new ScanResultsAdapter.OnAdapterItemClickListener() {
#Override
public void onAdapterViewClick(View view) {
final int childAdapterPosition = scanResults.getChildAdapterPosition(view);
final CRPScanDevice itemAtPosition = mResultsAdapter.getItemAtPosition(childAdapterPosition);
onAdapterItemClick(itemAtPosition);
}
});
}
private void onAdapterItemClick(CRPScanDevice scanResults) {
final String macAddress = scanResults.getDevice().getAddress();
mBleClient.cancelScan();
final Intent intent = new Intent(this, DeviceActivity.class);
intent.putExtra(DeviceActivity.DEVICE_MACADDR, macAddress);
startActivity(intent);
}
private void updateButtonUIState() {
scanToggleBtn.setText(mScanState ? R.string.stop_scan : R.string.start_scan);
}
CRPBleFirmwareUpgradeListener mFirmwareUpgradeListener = new CRPBleFirmwareUpgradeListener() {
#Override
public void onFirmwareDownloadStarting() {
Log.d(TAG, "onFirmwareDownloadStarting");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_download_starting));
}
#Override
public void onFirmwareDownloadComplete() {
Log.d(TAG, "onFirmwareDownloadComplete");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_download_complete));
}
#Override
public void onUpgradeProgressStarting() {
Log.d(TAG, "onUpgradeProgressStarting");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_starting));
}
#Override
public void onUpgradeProgressChanged(int percent, float speed) {
Log.d(TAG, "onUpgradeProgressChanged: " + percent);
String status = String.format(getString(R.string.dfu_status_uploading_part), percent);
updateTextView(tvFirmwareFixState, status);
}
#Override
public void onUpgradeCompleted() {
Log.d(TAG, "onUpgradeCompleted");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_completed));
}
#Override
public void onUpgradeAborted() {
Log.d(TAG, "onUpgradeAborted");
updateTextView(tvFirmwareFixState, getString(R.string.dfu_status_aborted));
}
#Override
public void onError(int errorType, String message) {
Log.d(TAG, "onError: " + errorType);
updateTextView(tvFirmwareFixState, message);
}
};
void updateTextView(final TextView view, final String con) {
runOnUiThread(new Runnable() {
#Override
public void run() {
view.setText(con);
}
});
}
void requestPermissions() {
if (!PermissionUtils.hasSelfPermissions(this, PERMISSION_UPDATEBANDCONFIG)) {
ActivityCompat.requestPermissions(
this, PERMISSION_UPDATEBANDCONFIG, REQUEST_UPDATEBANDCONFIG);
}
}
}
and the device activity here where data is transferred between the watch and the app
private static final String TAG = "DeviceActivity";
public static final String DEVICE_MACADDR = "device_macaddr";
private static final String UI_FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "crrepa" + File.separator + "ota" + File.separator
+ "eaf49ccb4dbe5df51af35803662867d5.bin";
ProgressDialog mProgressDialog;
CRPBleClient mBleClient;
CRPBleDevice mBleDevice;
CRPBleConnection mBleConnection;
boolean isUpgrade = false;
#BindView(R.id.tv_connect_state)
TextView tvConnectState;
#BindView(R.id.tv_firmware_version)
TextView tvFirmwareVersion;
#BindView(R.id.tv_battery)
TextView tvBattery;
#BindView(R.id.tv_step)
TextView tvStep;
#BindView(R.id.tv_distance)
TextView tvDistance;
#BindView(R.id.tv_calorie)
TextView tvCalorie;
#BindView(R.id.tv_restful)
TextView tvRestful;
#BindView(R.id.tv_light)
TextView tvLight;
#BindView(R.id.tv_heart_rate)
TextView tvHeartRate;
#BindView(R.id.tv_blood_pressure)
TextView tvBloodPressure;
#BindView(R.id.tv_upgrade_state)
TextView tvUpgradeState;
#BindView(R.id.btn_ble_connect_state)
Button btnBleDisconnect;
#BindView(R.id.tv_blood_oxygen)
TextView tvBloodOxygen;
#BindView(R.id.tv_new_firmware_version)
TextView tvNewFirmwareVersion;
private String bandFirmwareVersion;
private List<Integer> supportWatchFaceList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device);
ButterKnife.bind(this);
initView();
mProgressDialog = new ProgressDialog(this);
String macAddr = getIntent().getStringExtra(DEVICE_MACADDR);
//BluetoothDevice device = BluetoothAdapter.
if (TextUtils.isEmpty(macAddr)) {
finish();
return;
}
mBleClient = SampleApplication.getBleClient(this);
mBleDevice = mBleClient.getBleDevice(macAddr);
if (mBleDevice != null && !mBleDevice.isConnected()) {
connect();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBleDevice != null) {
mBleDevice.disconnect();
}
}
void initView() {
updateStepInfo(0, 0, 0);
updateSleepInfo(0, 0);
}
void connect() {
mProgressDialog.show();
mBleDevice.connect();
mBleConnection = mBleDevice.connect();
mBleConnection.setConnectionStateListener(new CRPBleConnectionStateListener() {
#Override
public void onConnectionStateChange(int newState) {
Log.d(TAG, "onConnectionStateChange: " + newState);
int state = -1;
switch (newState) {
case CRPBleConnectionStateListener.STATE_CONNECTED:
DeviceActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// state = R.string.state_connected;
mProgressDialog.dismiss();
updateTextView(btnBleDisconnect, getString(R.string.disconnect));
Toast.makeText(DeviceActivity.this, "connected", Toast.LENGTH_SHORT).show();
}
});
testSet();
break;
case CRPBleConnectionStateListener.STATE_CONNECTING:
state = R.string.state_connecting;
break;
case CRPBleConnectionStateListener.STATE_DISCONNECTED:
//closeGatt();
state = R.string.state_disconnected;
mProgressDialog.dismiss();
updateTextView(btnBleDisconnect, getString(R.string.connect));
break;
}
updateConnectState(state);
}
});
mBleConnection.setStepChangeListener(mStepChangeListener);
mBleConnection.setSleepChangeListener(mSleepChangeListener);
mBleConnection.setHeartRateChangeListener(mHeartRateChangListener);
mBleConnection.setBloodPressureChangeListener(mBloodPressureChangeListener);
mBleConnection.setBloodOxygenChangeListener(mBloodOxygenChangeListener);
mBleConnection.setFindPhoneListener(mFindPhoneListener);
mBleConnection.setECGChangeListener(mECGChangeListener, CRPEcgMeasureType.TI);
mBleConnection.setStepsCategoryListener(mStepsCategoryChangeListener);
mBleConnection.setSleepActionChangeListener(mSleepActionChangeListener);
mBleConnection.setMovementStateListener(mMovementStateListener);
mBleConnection.setTempChangeListener(mTempChangeListener);
mBleConnection.setContactListener(mContactListener);
mBleConnection.setHrvChangeListener(mHrvChangeListener);
}
private void closeGatt() {
if (mBleConnection != null) {
mBleConnection.close();
}
}```
Phone number format and custom typepad dose not working
Hi friends i am a Android Developer. Today i have fetching a simple problem. Anybody please help me.
Here is my code below and:
package com.example.grab_n_go_android;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by al-imranislam on 5/22/17.
*/
public class LoginActivity extends AppCompatActivity implements TextWatcher{
public EditText numberDisplayEditText, test2;
private TextView displayNumberLabel;
private int state = 0;
private String displayNumber = "";
private String passcodeDisplay = "";
private String passcode = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_view);
numberDisplayEditText = (EditText) findViewById(R.id.numberInput);
test2 = (EditText) findViewById(R.id.numberInput);
displayNumberLabel = (TextView) findViewById(R.id.displayLabel);
numberDisplayEditText.addTextChangedListener(this);
Log.d("LoginActivity", "onCreate() was called");
}
//For Custom Keyboard
public void n0(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"0"));
}
public void n1(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"1"));
}
public void n2(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"2"));
}
public void n3(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"3"));
}
public void n4(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"4"));
}
public void n5(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"5"));
}
public void n6(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"6"));
}
public void n7(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"7"));
}
public void n8(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"8"));
}
public void n9(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"9"));
}
public void dele(View view){
test2.setText(test2.getText().delete(test2.getText().length() -1, test2.getText().length()));
}
public void cancel(View view){
test2.setText("");
Toast.makeText(getApplicationContext(),"Cancel Activity is Successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
}
//For Custom Keyboard
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("LoginActivity", "A character was typed in");
if (state == 0) {
numberDisplayEditText.removeTextChangedListener(this);
if (displayNumber.length() == 0) {
displayNumber = displayNumber + "(";
}
if (displayNumber.length() == 4) {
displayNumber = displayNumber + ")";
}
if (displayNumber.length() == 9) {
displayNumber = displayNumber + "-";
}
displayNumber = displayNumber + s.subSequence(count - 1, count);
numberDisplayEditText.setText(displayNumber);
if(displayNumber.length() >= 14) {
displayNumberLabel.setText("Enter Your Passcode");
numberDisplayEditText.setText("");
state = 1;
numberDisplayEditText.addTextChangedListener(this);
return;
}
numberDisplayEditText.addTextChangedListener(this);
return;
}
if (state == 1){
numberDisplayEditText.removeTextChangedListener(this);
if(passcode.length() == 4){
numberDisplayEditText.setText(passcodeDisplay);
numberDisplayEditText.addTextChangedListener(this);
return;
}
passcodeDisplay = passcodeDisplay + "*";
numberDisplayEditText.setText(passcodeDisplay);
passcode = passcode + s.subSequence(count - 1, count);
if(passcode.length() == 4){
Log.d("test", displayNumber + ":" + passcode);
Intent i = new Intent(getBaseContext(), SelfCheckoutViewActivity.class);
startActivity(i);
}
numberDisplayEditText.addTextChangedListener(this);
//return;
}
}
#Override
public void afterTextChanged(Editable s) {
}
}
Please see this Google drive link below. It's a very very simple android app.
https://drive.google.com/open?id=0B-yo9VvU7jyBeS01ek9VSXpYRzg
And This is the Simple Image:
I have small problem. My problem is auto refresh to list messages.
How can instantly check data such as WhatsApp ?
If you would like to automatically update data came from.
I do not know exactly how I can do , so I'm waiting for your help .
Code
MessagingActivity.java
package com.socialnetwork.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.socialnetwork.R;
import com.socialnetwork.adapters.MessagesAdapter;
import com.socialnetwork.animation.ViewAudioProxy;
import com.socialnetwork.api.APIService;
import com.socialnetwork.api.ChatAPI;
import com.socialnetwork.api.UsersAPI;
import com.socialnetwork.data.MessagesItem;
import com.socialnetwork.data.userItem;
import com.socialnetwork.helpers.M;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MessagingActivity extends AppCompatActivity implements OnClickListener {
public Intent mIntent = null;
private MediaRecorder recorder = null;
private String outFile = null;
private TextView recordTimeText;
private ImageButton audioSendButton;
private View recordPanel;
private View slideText;
private float startedDraggingX = -1;
private float distCanMove = dp(80);
private long startTime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private Timer timer;
public int RECIPIENT_ID = 0,
CONVERSATION_ID = 0;
public LinearLayoutManager layoutManager;
private EditText messageField;
private String messageBody, USERNAME;
private MessagesAdapter messageAdapter;
private List<MessagesItem> mMessages = new ArrayList<MessagesItem>();
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
Bundle data = intent.getBundleExtra("data");
if (Integer.parseInt(data.getString("ownerID")) == RECIPIENT_ID) {
MessagesItem newMsg = new MessagesItem();
newMsg.setOwnerName(data.getString("ownerName"));
newMsg.setId(Integer.parseInt(data.getString("id")));
newMsg.setMessage(data.getString("message"));
newMsg.setDate(data.getString("date"));
newMsg.setOwnerUsername(data.getString("ownerUsername"));
newMsg.setOwnerPicture(data.getString("ownerPicture"));
newMsg.setOwnerID(Integer.parseInt(data.getString("ownerID")));
newMsg.setConversationID(Integer.parseInt(data.getString("conversationID")));
addMessage(newMsg);
} else {
Intent resultIntent = new Intent(MessagingActivity.this, MessagingActivity.class);
resultIntent.putExtra("data", intent);
M.showNotification(MessagingActivity.this, resultIntent,
data.getString("ownerUsername"),
data.getString("message"),
Integer.parseInt(data.getString("conversationID")));
}
}
};
private RecyclerView messagesList;
private LinearLayout attachLayout;
private RelativeLayout recordPannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
setContentView(R.layout.messaging);
initializer();
if (getIntent().hasExtra("conversationID")) {
CONVERSATION_ID = getIntent().getExtras().getInt("conversationID");
}
if (getIntent().hasExtra("recipientID")) {
RECIPIENT_ID = getIntent().getExtras().getInt("recipientID");
}
getUser();
getMessages();
}
}
public void initializer() {
messagesList = (RecyclerView) findViewById(R.id.listMessages);
messageAdapter = new MessagesAdapter(this, mMessages);
messagesList.setAdapter(messageAdapter);
//
layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
messagesList.setLayoutManager(layoutManager);
messageField = (EditText) findViewById(R.id.messageField);
attachLayout = (LinearLayout) findViewById(R.id.attachLayout);
recordPannel = (RelativeLayout) findViewById(R.id.record_pannel);
recordPanel = findViewById(R.id.record_panel);
recordTimeText = (TextView) findViewById(R.id.recording_time_text);
slideText = findViewById(R.id.slideText);
audioSendButton = (ImageButton) findViewById(R.id.chat_audio_send_button);
TextView textView = (TextView) findViewById(R.id.slideToCancelTextView);
textView.setText("Slide To Cancel");
//including toolbar and enabling the home button
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.attachBtn).setOnClickListener(this);
findViewById(R.id.sendBtn).setOnClickListener(this);
findViewById(R.id.micBtn).setOnClickListener(this);
audioSendButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
startRecording();
audioSendButton.getParent()
.requestDisallowInterceptTouchEvent(true);
recordPanel.setVisibility(View.VISIBLE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP
|| motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
startedDraggingX = -1;
stopRecording();
recordPannel.setVisibility(View.GONE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
float x = motionEvent.getX();
if (x < -distCanMove) {
stopRecording();
}
x = x + ViewAudioProxy.getX(audioSendButton);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
if (startedDraggingX != -1) {
float dist = (x - startedDraggingX);
params.leftMargin = dp(30) + (int) dist;
slideText.setLayoutParams(params);
float alpha = 1.0f + dist / distCanMove;
if (alpha > 1) {
alpha = 1;
} else if (alpha < 0) {
alpha = 0;
}
ViewAudioProxy.setAlpha(slideText, alpha);
}
if (x <= ViewAudioProxy.getX(slideText) + slideText.getWidth()
+ dp(30)) {
if (startedDraggingX == -1) {
startedDraggingX = x;
distCanMove = (recordPanel.getMeasuredWidth()
- slideText.getMeasuredWidth() - dp(48)) / 2.0f;
if (distCanMove <= 0) {
distCanMove = dp(80);
} else if (distCanMove > dp(80)) {
distCanMove = dp(80);
}
}
}
if (params.leftMargin > dp(30)) {
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
}
}
view.onTouchEvent(motionEvent);
return true;
}
});
}
private void getUser() {
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(RECIPIENT_ID, new Callback<userItem>() {
#Override
public void success(userItem userItem, retrofit.client.Response response) {
if (userItem.getName() != null) {
getSupportActionBar().setTitle(userItem.getName());
} else {
getSupportActionBar().setTitle(userItem.getUsername());
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
messageAdapter.stop();
}
public void getMessages() {
M.showLoadingDialog(this);
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.getMessages(CONVERSATION_ID, RECIPIENT_ID, 1, new Callback<List<MessagesItem>>() {
#Override
public void success(List<MessagesItem> messagesItems, Response response) {
mMessages = messagesItems;
messageAdapter.setMessages(messagesItems);
M.hideLoadingDialog();
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
M.L(getString(R.string.ServerError));
}
});
}
private void sendMessage() {
messageBody = messageField.getText().toString().trim();
if (!messageBody.isEmpty()) {
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.addMessage(messageBody, CONVERSATION_ID, RECIPIENT_ID, new Callback<MessagesItem>() {
#Override
public void success(MessagesItem messagesItem, Response response) {
if (messagesItem != null) {
mMessages.add(messagesItem);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
messageField.setText("");
} else {
M.T(MessagingActivity.this, getString(R.string.SomethingWentWrong));
}
}
#Override
public void failure(RetrofitError error) {
M.T(MessagingActivity.this, getString(R.string.ServerError));
}
});
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.attachBtn) {
if (attachLayout.getVisibility() == View.GONE) {
attachLayout.setVisibility(View.VISIBLE);
} else {
attachLayout.setVisibility(View.GONE);
}
if (recordPannel.getVisibility() == View.VISIBLE) {
recordPannel.setVisibility(View.GONE);
}
} else if (v.getId() == R.id.sendBtn) {
sendMessage();
} else if (v.getId() == R.id.micBtn) {
attachLayout.setVisibility(View.GONE);
recordPannel.setVisibility(View.VISIBLE);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mMessageReceiver, new IntentFilter("update_messages_list"));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mMessageReceiver);
}
public void addMessage(MessagesItem newMsg) {
mMessages.add(newMsg);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
}
private void startRecording() {
try {
startRecordingAudio();
} catch (IOException e) {
e.printStackTrace();
}
startTime = SystemClock.uptimeMillis();
timer = new Timer();
MyTimerTask myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 1000, 1000);
vibrate();
}
private void stopRecording() {
if (timer != null) {
timer.cancel();
}
if (recordTimeText.getText().toString().equals("00:00")) {
return;
}
recordTimeText.setText("00:00");
vibrate();
Toast.makeText(getApplicationContext(), "Stop Recording", Toast.LENGTH_SHORT).show();
stopRecordingAudio();
}
public void startRecordingAudio() throws IOException {
Toast.makeText(getApplicationContext(), "Start Recording...", Toast.LENGTH_SHORT).show();
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH.mm.ss");
String fileName = "audio_" + timeStampFormat.format(new Date())
+ ".mp3";
outFile = "/sdcard/";// Environment.getExternalStorageDirectory().getAbsolutePath();
stopRecordingAudio();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outFile + fileName);
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
recorder.prepare();
recorder.start();
}
public void stopRecordingAudio() {
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private void vibrate() {
// TODO Auto-generated method stub
try {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int dp(float value) {
return (int) Math.ceil(1 * value);
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
final String hms = String.format(
"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(updatedTime)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(updatedTime)),
TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime)));
long lastsec = TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime));
System.out.println(lastsec + " hms " + hms);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (recordTimeText != null)
recordTimeText.setText(hms);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
}
}
MessagesFragment.java
public class MessagesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public RecyclerView conversationList;
public ConversationsAdapter mConversationsAdapter;
public List<ConversationItem> mConversations = new ArrayList<ConversationItem>();
public Intent mIntent = null;
public int currentPage = 1;
public LinearLayoutManager layoutManager;
private View mView;
private SwipeRefreshLayout mSwipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_messages, container, false);
conversationList = (RecyclerView) mView
.findViewById(R.id.conversationsList);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.title_messages);
initializeView();
conversationList.setOnScrollListener(new HidingScrollListener(layoutManager) {
#Override
public void onHide() {
}
#Override
public void onShow() {
}
#Override
public void onLoadMore(int currentPage) {
setCurrentPage(currentPage);
getConversations();
}
});
mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeMessages);
mSwipeRefreshLayout.setOnRefreshListener(this);
getConversations();
return mView;
}
public void initializeView() {
mConversationsAdapter = new ConversationsAdapter(getActivity(),
mConversations);
conversationList.setAdapter(mConversationsAdapter);
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
conversationList.setLayoutManager(layoutManager);
}
public void getConversations() {
M.showLoadingDialog(getActivity());
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(getActivity()));
mChatAPI.getConversations(getCurrentPage(), new Callback<List<ConversationItem>>() {
#Override
public void success(List<ConversationItem> conversationItems, retrofit.client.Response response) {
M.L(response.getBody().mimeType());
mConversationsAdapter.setConversations(conversationItems);
M.hideLoadingDialog();
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
}
});
}
#Override
public void onRefresh() {
setCurrentPage(1);
getConversations();
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
WhatsApp is not instant check. It's is more like:
Screen off, check 10x after 30s, next 10x after 1m, next 3x after 5m and so on. and start again if the screen turns off again. WhatsApp is checkin in the background also when you close the app. They are using a service.
Im following the tutorial of In-app Billing from the following link:
Android Studio Google Play In-app Billing Tutorial.
Im implementing this logic in a Contact Adapter class which extends Base Adapter. In tutorial it is implemented in a class which extends Activity.
Error comes on onActivityResult(). I read several questions on this and I understand this method should be written in class which extends Activity but in my case the scenario is different.
Is there any way to solve this without writing onActivityResult method in MainActivity class.. and if not what should I do?
Heres ContactAdapter.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.neirx.myco.smsproject.util.IabHelper;
import com.neirx.myco.smsproject.util.IabResult;
import com.neirx.myco.smsproject.util.Inventory;
import com.neirx.myco.smsproject.util.Purchase;
import java.util.List;
public class ContactAdapter extends BaseAdapter {
private static final java.lang.String CLASS_NAME = "<ContactAdapter> ";
Context context;
List<Contact> objects;
LayoutInflater lInflater;
MainActivity activity;
static final String ITEM_SKU = "android.test.purchased";
IabHelper mHelper;
int count = 0;
int get_limit;
private int limit_counter = 0;
private int max_limit = 2;
boolean testbool = true;
public ContactAdapter(Context context, List<Contact> contact) {
this.context = context;
objects = contact;
lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = (MainActivity) context;
}
#Override
public int getCount() {
int selectedCount = 0;
int nonSelectedCount = 0;
int size = 0;
for(Contact contact : objects){
if(contact.isChecked()) selectedCount++;
else nonSelectedCount++;
}
if(activity.isShowSelected()) size += selectedCount;
if(activity.isShowNonSelected()) size += nonSelectedCount;
return size;
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void buyClick() {
mHelper.launchPurchaseFlow(activity, ITEM_SKU, 10001, mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (!mHelper.handleActivityResult(requestCode,resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,Purchase purchase)
{
if (result.isFailure()) {
// Handle error
Log.d("----FAILURE 1---", "FAIL 1");
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
//buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,Inventory inventory) {
if (result.isFailure()) {
// Handle failure
Log.d("----FAILURE 2---", "FAIL 2");
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,IabResult result) {
if (result.isSuccess()) {
//clickButton.setEnabled(true);
Log.d("----Success ----", "Success");
} else {
// handle error
Log.d("----FAILURE 3---", "FAIL 3");
}
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxW650UixX2dLFECVdOpTh5OpBTqHwsznQAKd/cVcqKhrXROy4+Gj6B7M6wbkhTaloNSzTOf+nw9t1LZZ19Vlr6kcwmtxP+V/HOFwjf/NB69StOONogXtGKDyRrxtVaPM5es3yGy/aP/LXWfTLFQYJvur4AePonuRXz33iufBq5ITDQJ0+0D/o/mGtadJv0ZMsP9LV/qrMqruoqpSdaIiw5TGXdzYlJTuoP3GwS9kRyZKDeG/70KZ28W/ZclVWAdnZ7aCeDURYDV3a4pmGp5/cIvKwbex6Y7KbQYENX5ObSgNoFHLdyPTdkYaeuU9O6pet2TjGUCKr8n4M5KUMZVm8QIDAQAB";
mHelper = new IabHelper(context, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d("---MY TAG---", "In-app Billing setup failed: " +
result);
} else {
Log.d("---MY TAG---", "In-app Billing is set up OK");
}
}
});
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
get_limit = limit_pref.getInt("LIMIT_KEY",0);
//Log.d("----- STORED VALUE-----", "Value is: "+get_limit);
Log.d("----- Max VALUE-----", "Value is: "+max_limit);
if (view == null) {
view = lInflater.inflate(R.layout.view_contact, parent, false);//create view file
}
if (position == 0) {
count = 0;
}
if (!activity.isShowSelected()) {
while (objects.get(position + count).isChecked()) {
count++;
}
}
if (!activity.isShowNonSelected()) {
while (!objects.get(position + count).isChecked()) {
count++;
}
}
final Contact contact = objects.get(position + count);
String contactFirstName = contact.getFirstName();
String contactSecondName = contact.getSecondName();
String contactMiddleName = contact.getMiddleName();
String[] contactNumbers = contact.getNumbers();
TextView tvName = (TextView) view.findViewById(R.id.tvName);
TextView tvNumber = (TextView) view.findViewById(R.id.tvNumber);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
if(get_limit == max_limit)
{
//checkBox.setChecked(contact.isChecked());
//testbool = false;
limit_counter = get_limit;
}
else if (get_limit == 1)
{
limit_counter = 1;
}
String fullName;
switch (MainActivity.sortMode) {
case Contact.COMPARE_SECOND_NAME:
fullName = getFullName(contactSecondName, contactFirstName);
break;
case Contact.COMPARE_MIDDLE_NAME:
fullName = getFullName(contactMiddleName, contactFirstName, contactSecondName);
break;
default:
fullName = getFullName(contactFirstName, contactSecondName);
break;
}
tvName.setText(fullName);
StringBuilder sbNumber = new StringBuilder();
for (int i = 0; i < contactNumbers.length; i++) {
sbNumber.append(contactNumbers[i]);
if (i < contactNumbers.length - 1) {
sbNumber.append(", ");
}
}
tvNumber.setText(sbNumber);
if (testbool) {
//Log.d("Check Boolean Tag 2 ", "testbool: "+testbool);
checkBox.setChecked(contact.isChecked());
}
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences selected = context.getSharedPreferences(Statical.CONTACTS_SELECTED, Context.MODE_PRIVATE);
SharedPreferences.Editor editSelected = selected.edit();
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
SharedPreferences.Editor edit_limit_pref = limit_pref.edit();
int k = 0;
if(limit_counter == max_limit)
{
checkBox.setChecked(false);
//Toast.makeText(context,"Limit reached !! ", Toast.LENGTH_SHORT).show();
Log.d("-------LIMIT REACH-----", "value: "+limit_counter);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
showAlertDialog();
}
if (contact.isChecked() && limit_counter <= max_limit && limit_counter >= 0) {
limit_counter = limit_counter - 1;
editSelected.putBoolean(contact.getContactId(), false);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(false);
Log.d("-------UN CHECKED-----", "Un Checked value: "+limit_counter);
k = -1;
}
else if(!contact.isChecked() && limit_counter < max_limit){
limit_counter = limit_counter + 1;
editSelected.putBoolean(contact.getContactId(), true);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(true);
Log.d("------- CHECKED -----", "Checked value: "+limit_counter);
k = 1;
}
editSelected.apply();
edit_limit_pref.apply();
activity.updateCount(k);
}
});
return view;
}
public void showAlertDialog()
{
Log.d("-------VALUE-----", "value: "+limit_counter);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Limit Reached!");
alertDialog.setMessage("Buy Pro Version");
alertDialog.setIcon(R.drawable.action_bar_logo);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
buyClick();
Log.d("-------OK PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("----LATER PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.show();
}
private String getFullName(String first, String second, String third) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second).append(" ");
}
if (!third.isEmpty()) {
sbName.append(third);
}
return sbName.toString();
}
private String getFullName(String first, String second) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second);
}
return sbName.toString();
}
}
I recommend you to create an activity just to process this payment and then you can back to your normal flow.
I want to make an app that will ask user for 2 numbers one by one.
then multiply them and tell user the result.
but my app crashes when i try to convert user's speech string to double.
this is my code:
num1 = Double.parseDouble(String.valueOf(matches));
(num1 is double, matches is the string form user's speech)
if you need more code just tell me.
thanks in advance!
EDIT: here's the whole activity_
package cannon.gaming.physicsdroidvoice;
import android.content.Intent;
import android.content.SharedPreferences;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import java.io.File;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends ActionBarActivity {
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
int forza, m, a;
double mass, acc, mares;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
forza = 0;
m = 0;
mass = 0;
a = 0;
acc = 0;
mares = 0;
final String abc = "Welcome to PhysicsDroid!";
final String abcc = "What do you need?";
final String abccc = "Force, Velocity, Mass, Acceleration, Distance, Time, Temperature, Work, Density, Info, or Exit?";
final String abcccc = "Just tap the screen and speak. When you are done, tap the screen again.";
final String abccccc = "Can you repeat please?";
final String force = "Which force equation would you like to use?";
final String exit = "Thank you for using PhysicsDroid, see ya!";
final String one = "First one: F=m times A. Second one: F=p times A. Or third one: Fg=G times m1m2 over r squared?";
final String ma = "What is the mass of object in kilograms?";
final String am = "What is the acceleration of object in meters per second squared?";
final String mnum = "What the...!";
final TextToSpeech home = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
//DO NOTHING
}
}
});
new Timer().schedule(
new TimerTask() {
#Override
public void run()
{
home.speak(abc, TextToSpeech.QUEUE_ADD, null);
home.speak(abcc, TextToSpeech.QUEUE_ADD, null);
home.speak(abccc, TextToSpeech.QUEUE_ADD, null);
home.speak(abcccc, TextToSpeech.QUEUE_ADD, null);
}
},
1000
);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
//Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
//Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
//Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
CharSequence cs1 = "Force";
CharSequence cs2 = "force";
CharSequence cs3 = "Exit";
CharSequence cs4 = "exit";
CharSequence cs5 = "First";
CharSequence cs6 = "first";
CharSequence cs7 = "times";
CharSequence cs8 = "equals";
Pattern p = Pattern.compile("[a-zA-Z]");
Matcher mat = p.matcher("3453443534534");
if(forza == 1 && m == 0 && a == 0)
{
if(String.valueOf(matches).contains(cs5) || String.valueOf(matches).contains(cs6) || String.valueOf(matches).contains(cs7) || String.valueOf(matches).contains(cs8))
{
home.speak(ma,TextToSpeech.QUEUE_FLUSH, null);
forza = 0;
m = 1;
}
}
else if(m == 1 && forza == 0 && a == 0)
{
if(String.valueOf(matches).matches(".*\\d.*"))
{
mass = Double.parseDouble(String.valueOf(matches));
home.speak(am,TextToSpeech.QUEUE_FLUSH, null);
m = 0;
a = 1;
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
else
{
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
}
else if(a == 1 && m == 0 && forza == 0)
{
if(String.valueOf(matches).contains("[a-zA-Z]+") || String.valueOf(matches).equals("") || String.valueOf(matches).equals(".") || String.valueOf(matches).equals("-.") || String.valueOf(matches).equals("-"))
{
home.speak(mnum,TextToSpeech.QUEUE_FLUSH, null);
}
else
{
acc = Double.parseDouble(String.valueOf(matches));
a = 0;
mares = mass * acc;
String mare = String.format("The force is %d", mares);
home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
}
}
else if(String.valueOf(matches).contains(cs1) || String.valueOf(matches).contains(cs2) && forza == 0 && m == 0 && a == 0)
{
home.speak(force,TextToSpeech.QUEUE_FLUSH, null);
home.speak(one,TextToSpeech.QUEUE_ADD, null);
forza = 1;
}
else if(String.valueOf(matches).contains(cs3) || String.valueOf(matches).contains(cs4) && forza == 0 && m == 0 && a == 0)
{
home.speak(exit,TextToSpeech.QUEUE_FLUSH, null);
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
},
4000
);
}
else
{
home.speak(abccccc,TextToSpeech.QUEUE_FLUSH, null);
}
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
SpeechRecognitionListener listener = new SpeechRecognitionListener();
mSpeechRecognizer.setRecognitionListener(listener);
RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.MainActivity);
rlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
boolean mIsListening = false;
if (!mIsListening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
else
{
mSpeechRecognizer.cancel();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Ensure that matches is not null or that it is a double.
You could use try catches to check if matches is a number at runtime. You also should not need String.valueOf if matches is a string.
try {
num1 = Double.parseDouble(matches);
} catch (NumberFormatException e) {
e.pritStackTrace();
}
Also make sure num1 is initialised.