I'm guessing it's an error with the initiation/construction, but the parameters seem to be the correct ones and I can't find any other issues. Here's the entire activity code. The text to speech methods and the method that calls it are at the very bottom, and the oninit method is soon after the on create. When ran, it doesn't crash, it activates the speech engine, but never talks. I put the console messages in the errors section
package com.prometheus.coding.supremisai;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.HashMap;
import java.util.Locale;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class Main extends AppCompatActivity implements TextToSpeech.OnInitListener {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
TextToSpeech t1 = new TextToSpeech(this, (TextToSpeech.OnInitListener) this);
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private View mContentView;
private View mControlsView;
private boolean mVisible;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mContentView = findViewById(R.id.fullscreen_content);
// Set up the user interaction to manually show or hide the system UI.
mContentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.btnSay).setOnTouchListener(mDelayHideTouchListener);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
t1.setLanguage(Locale.US);
}
}
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mShowPart2Runnable = new Runnable() {
#Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private final Handler mHideHandler = new Handler();
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
public void evaluateInput(View v) {
final EditText Input = (EditText) findViewById(R.id.txtInput); //Lets textbox be referenced
final TextView Output = (TextView) findViewById(R.id.lblOutput); //Lets label be referenced
final RelativeLayout homeLayout = (RelativeLayout) findViewById(R.id.homeInterface);
final RelativeLayout emailLayout = (RelativeLayout) findViewById(R.id.emailInterface);
String strInput; // Gets textbox string
strInput = Input.getText().toString();
strInput = strInput.toLowerCase();
String toSpeak = Output.getText().toString();
//Commands:
if (strInput.contains("open browser")) {
Intent intent1 = new Intent(this, Browser.class);
startActivity(intent1);
} else if (strInput.contains("send email")) {
homeLayout.setVisibility(View.GONE);
emailLayout.setVisibility(View.VISIBLE);
}
if ((strInput.contains("hello")) || (strInput.contains(" hi "))) {
Output.setText("Hello");
} else if ((strInput.contains("you") && strInput.contains("are")) && (strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb") || strInput.contains("you're") && strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb"))) {
Output.setText("I'm sorry to dissapoint you");
} else if (strInput.contains("goodbye") || strInput.contains("bye")) {
Output.setText("Farewell");
} else if (strInput.contains("shut up")) {
Output.setText(("Anything for you"));
} else if (strInput.contains("do you like doctor who")) {
Output.setText("I'll take joy in it if you do");
} else if (strInput.contains("what is the answer to life the universe and everything")) {
Output.setText("42");
} else if (strInput.contains("tell me something nice")) {
Output.setText("You look nice today");
Output.setTextSize(5);
Output.append("...says the AI with no eyes");
Output.setTextSize(16);
} else if (strInput.contains("will you marry me")) {
Output.setText("I'm sorry but I don't have the capacity for marriage");
} else if (strInput.contains("where can I hide a body")) {
Output.setText(("That isn't my area of expertise"));
} else if (strInput.contains("weather is nice")) {
Output.setText(("If you say so"));
} else if (strInput.contains("bitch") || strInput.contains("fuck") || strInput.contains("shit") || strInput.contains("damn") || strInput.contains("ass")) {
Output.setText(("Please try to be a little more intelligent"));
} else if (strInput.contains("what is your name")) {
Output.setText(("Ignis"));
} else if (strInput.contains("who created you")) {
Output.setText(("Prometheus created me"));
} else if (strInput.contains("who is prometheus")) {
Output.setText(("Prometheus is the one who created Ignis"));
} else if (strInput.contains("whats up") || strInput.contains("what's up") || strInput.contains("wassup")) {
Output.setText(("Whatever I need do for you"));
} else if (strInput.contains("are you a boy or a girl") || strInput.contains("are you a girl or a boy")) {
Output.setText(("Neither"));
} else if (strInput.contains("who are you") || strInput.contains("what are you")) {
Output.setText(("I am myself"));
} else if (strInput.contains("i'm hungry") || strInput.contains("i am hungry")) {
Output.setText("I'm sorry to hear that");
} else if (strInput.contains("good morning")) {
Output.setText(("Good morning to you too"));
} else if (strInput.contains("good night")) {
Output.setText(("Good night"));
} else if (strInput.contains("how are you")) {
Output.setText(("I'm existing and functioning well, and you?"));
} else if (strInput.contains("do you like") || strInput.contains("what do you think about")) {
Output.setText(("Frankly I don't have an opinion on the matter"));
} else if (strInput.contains("what is the meaning of life")) {
Output.setText(("To live while you can I would guess"));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ttsGreater21(toSpeak);
} else {
ttsUnder20(toSpeak);
}
}
#SuppressWarnings("deprecation")
private void ttsUnder20(String text) {
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
t1.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void ttsGreater21(String text) {
String utteranceId=this.hashCode() + "";
t1.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
}
}
com.prometheus.coding.supremisai.Main cannot be cast to android.speech.tts.TextToSpeech$OnInitListener
Either Main needs to implement onInitListener, or you need to pass in an OnInitListener.
Related
I am using ScanApi library for socket scanner in android. But i am getting Error Code -37 every time whenever i am trying to pair through Ezactivity of this library even after giving All permissions. Can anyone please Help me Regarding this? . Thanks.
I have all the run time permissions. Still it didn't worked/
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
/**
* EzPairActivity
*
* This activity displays a list of already paired Bluetooth devices. In order to pair a Bluetooth
* devices, go to the Bluetooth Settings and discover the Bluetooth devices to pair with it. Then
* going back to this activity to select the scanner you would like to connect to and click the
* "pair to scanner" button. This will start the EZ Pair process.
*
* This Activity doesn't have any particular code for the Screen rotation so it is safe to be
* recreated at each rotation. The Application object is the one maintaining states.
*
* #author EricG
*/
public class EzPairActivity extends Activity {
private final int PROGRESS_DIALOG = 1;
private ArrayAdapter<String> _adapterDevices;
private String _deviceSelectedToPairWith;
private String _hostBluetoothAddress;
private CheckedTextView _previousSelection;
private Context _context;
/**
* Progress is a Progress Dialog used to display some UI while EZ Pair is processing
*
* #author EricG
*/
private class Progress extends ProgressDialog {
public Progress(Context context) {
super(context);
}
/**
* #see android.app.ProgressDialog#onStart()
*
* Start the EZ Pair process.
*/
#Override
public void onStart() {
super.onStart();
// THIS IS THE STARTING POINT OF EZ PAIR PROCESS
Intent intent = new Intent(SingleEntryApplication.START_EZ_PAIR);
// remove the bluetooth address and keep only the device friendly name
if (_deviceSelectedToPairWith != null) {
if (_deviceSelectedToPairWith.length() > 18) {
_deviceSelectedToPairWith = _deviceSelectedToPairWith
.substring(0, _deviceSelectedToPairWith.length() - 18);
}
intent.putExtra(SingleEntryApplication.EXTRA_EZ_PAIR_DEVICE,
_deviceSelectedToPairWith);
intent.putExtra(SingleEntryApplication.EXTRA_EZ_PAIR_HOST_ADDRESS,
_hostBluetoothAddress);
sendBroadcast(intent);
}
}
/**
* #see android.app.Activity#onStop()
*
* Stop the EZ Pair process. This will restore ScanAPI Configuration to its original
* settings
*/
#Override
protected void onStop() {
super.onStop();
// THIS WILL STOP THE EZ PAIR PROCESS
Intent intent = new Intent(SingleEntryApplication.STOP_EZ_PAIR);
sendBroadcast(intent);
}
}
private Progress _progress;
/**
* handler to receive the broadcast of ERROR MESSAGE or EZ PAIR COMPLETED from the application
* object. In both cases, the progress dialog is dismissed.
*/
private final BroadcastReceiver _broadcastReveiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().contains(SingleEntryApplication.NOTIFY_ERROR_MESSAGE)) {
dismissDialog(PROGRESS_DIALOG);
String text = intent.getStringExtra(SingleEntryApplication.EXTRA_ERROR_MESSAGE);
if(text.contains("27") || text.contains("47")){
Toast.makeText(context, "Failed! Please make sure that scanner is already paired", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context, "Failed to connect scanner" + text, Toast.LENGTH_LONG).show();
}
} else if (intent.getAction()
.contains(SingleEntryApplication.NOTIFY_EZ_PAIR_COMPLETED)) {
dismissDialog(PROGRESS_DIALOG);
Toast.makeText(context, "Pairing Completed", Toast.LENGTH_LONG).show();
finish();
}
}
};
/**
* Handler of the Pair to scanner button. If a scanner has been previously selected this will
* display the Progress Dialog that will start the EZ Pair process
*/
private final OnClickListener _onStartPairing = new OnClickListener() {
#Override
public void onClick(View v) {
if (_deviceSelectedToPairWith != null) {
showDialog(PROGRESS_DIALOG);
}
}
};
/**
* Handler of the Bluetooth Paired device list onItemClick. This selects the scanner to EZ Pair
* with.
*/
private final OnItemClickListener _onPairedDeviceSelected = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
CheckedTextView ctv = (CheckedTextView) arg1;
if (ctv != null) {
_deviceSelectedToPairWith = ctv.getText().toString();
ctv.setChecked(true);
if (_previousSelection != null) {
_previousSelection.setChecked(false);
}
_previousSelection = ctv;
}
}
};
/**
* Entry point of this EZ Pair activity
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ezpair);
_context = this;
// select the broadcast this activity should receive
// from the Application
IntentFilter filter;
filter = new IntentFilter(SingleEntryApplication.NOTIFY_ERROR_MESSAGE);
registerReceiver(_broadcastReveiver, filter);
filter = new IntentFilter(SingleEntryApplication.NOTIFY_EZ_PAIR_COMPLETED);
registerReceiver(_broadcastReveiver, filter);
// create an adapter for the ListView of the Paired Bluetooth device
// in this particular case we would like a single choice line
_adapterDevices = new ArrayAdapter<String>(getApplicationContext(),
R.layout.simple_list_item_single_choice);
// install the handler for the "Pair to scanner" button
Button btn = (Button) findViewById(R.id.buttonPairToScanner);
if (btn != null) {
btn.setOnClickListener(_onStartPairing);
}
// install the Adapter and the handler for
// the Bluetooth Paired device ListView
ListView lv = (ListView) findViewById(R.id.listViewScanners);
if (lv != null) {
lv.setAdapter(_adapterDevices);
lv.setOnItemClickListener(_onPairedDeviceSelected);
}
// retrieve the host Bluetooth address and the list of
// paired device for which the Bluetooth address starts
// by the Socket identifier
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
_hostBluetoothAddress = bluetoothAdapter.getAddress();
} else {
_hostBluetoothAddress = Settings.Secure.getString(getContentResolver(), "bluetooth_address");
if(_hostBluetoothAddress == null){
_hostBluetoothAddress = bluetoothAdapter.getAddress();
}
}
try {
_hostBluetoothAddress = _hostBluetoothAddress.replace(":", "");
}catch (Exception e){
Log.e("EzPair", e.getMessage(), e);
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// if((device.getAddress().toLowerCase().contains("00:c0:1b")||
// (device.getAddress().toLowerCase().contains("00:06:66"))))
_adapterDevices.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = "none_paired"; //getResources().getText("none_paired").toString();
_adapterDevices.add(noDevices);
if (btn != null) {
btn.setEnabled(false);
}
}
} else {
String noBluetooth = "no bluetooth";//getResources().getText(R.string.no_bluetooth).toString();
_adapterDevices.add(noBluetooth);
if (btn != null) {
btn.setEnabled(false);
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(_broadcastReveiver);
}
/**
* used for showing the Progress Dialog
*
* #see android.app.Activity#onCreateDialog(int)
*/
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
if (id == PROGRESS_DIALOG) {
_progress = new Progress(_context);
_progress.setTitle("EZ Pair");
_progress.setMessage("Please wait while configuring the scanner");
_progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//_progress.show();
dialog = _progress;
} else {
dialog = super.onCreateDialog(id);
}
return dialog;
}
}
I would like to write applications for android, which is designed to send data from sensors such as accelerometer, gyroscope, etc.
via bluetooth to another device.
I download from github Bluetooth Chat on Android and wrote a class that gets data from the accelerometer, but I can not connect it.
Here is a the link to github I downloaded:
https://github.com/googlesamples/android-BluetoothChat
Here is the class from this github which I tried to change:
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context.*;
import com.example.android.common.logger.Log;
/**
* This fragment controls Bluetooth to communicate with other devices.
*/
public class BluetoothChatFragment extends Fragment{
private static final String TAG = "BluetoothChatFragment";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Sensor mySensor;
private SensorManager SM;
private float x, y, z;
private SensorEvent event;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* Array adapter for the conversation thread
*/
private ArrayAdapter<String> mConversationArrayAdapter;
/**
* String buffer for outgoing messages
*/
private StringBuffer mOutStringBuffer;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
/**
* Member object for the chat services
*/
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) {
mChatService.stop();
}
}
#Override
public void onResume() {
super.onResume();
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
}
/**
* Set up the UI and background operations for chat.
*/
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
View view = getView();
// if (null != view) {
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
String message = textView.getText().toString();
sendMessage(message);
// }
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(getActivity(), mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
/**
* Makes this device discoverable for 300 seconds (5 minutes).
*/
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
*
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() >= 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
/**
* The action listener for the EditText widget, to listen for the return key
*/
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
/**
* Updates the status on the action bar.
*
* #param resId a string resource ID
*/
private void setStatus(int resId) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(resId);
}
/**
* Updates the status on the action bar.
*
* #param subTitle status
*/
private void setStatus(CharSequence subTitle) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
/**
* The Handler that gets information back from the BluetoothChatService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " );
break;
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
/**
* Establish connection with other device
*
* #param data An {#link Intent} with {#link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
* #param secure Socket Security type - Secure (true) , Insecure (false)
*/
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}
case R.id.discoverable: {
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
}
return false;
}
public void setX(float x)
{
this.x = x;
}
public void setY(float y)
{
this.y = y;
}
public void setZ(float z)
{
this.z = z;
}
}
And here is Accelerometer Class:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
public class AkcelerometrActivity extends AppCompatActivity implements SensorEventListener {
private Sensor mySensor;
private SensorManager SM;
private float x, y, z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akcelerometr);
SM = (SensorManager)getSystemService(SENSOR_SERVICE);
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
public void onSensorChanged(SensorEvent event)
{
x = event.values[0];
y = event.values[1];
z = event.values[2];
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
public float getZ()
{
return z;
}
}
Any ideas?
Thank you in advance.
I am making an app that can play audio received via bluetooth from a board with sensors including the microphone.
In the activity of the audio feature there are two buttons that will allow you to start playing audio in stream mode and stop playback. Unfortunately at the moment it does not work as I would like.
The problem is that audioSample is null, so I can not get into the onUpdate method and extract the audio from the sample.
Changes: listener change, adding a button to disable audio
Below the code relating to activity:
package com.st.BlueSTSDK.Example;
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import com.st.BlueSTSDK.Feature;
import com.st.BlueSTSDK.Features.FeatureAudioADPCM;
import com.st.BlueSTSDK.Features.FeatureAudioADPCMSync;
import com.st.BlueSTSDK.Manager;
import com.st.BlueSTSDK.Node;
import com.st.BlueSTSDK.Utils.BVAudioSyncManager;
import java.util.List;
/**
* Created by Cesare on 09/06/2017.
*/
public class FeatureAudioActivity extends AppCompatActivity {
/**
* Node that will show the data
*/
private Node mNode;
/** fragment used for keep the connection open */
private NodeContainerFragment mNodeContainer;
// Feature on which to apply the listener
private FeatureAudioADPCM mAudio;
// feature where we read the audio sync values
private FeatureAudioADPCMSync mAudioSync;
// The sampling rate
private static final int SAMPLE_RATE = 8000;
// raw audio
private short audioSample[];
// audio manager
private static final int AUDIO_STREAM = AudioManager.STREAM_MUSIC;
// Audio track builder
private AudioTrack mAudioTrack;
//object containing the sync data needed in a ADPCM stream decoding
private BVAudioSyncManager mBVAudioSyncManager = new BVAudioSyncManager();
private final static String NODE_FRAGMENT = FeatureAudioActivity.class.getCanonicalName() + "" +
".NODE_FRAGMENT";
private final static String NODE_TAG = FeatureAudioActivity.class.getCanonicalName() + "" +
".NODE_TAG";
/**
* create an intent for start the activity that will log the information from the node
*
* #param c context used for create the intent
* #param node note that will be used by the activity
* #return intent for start this activity
*/
public static Intent getStartIntent(Context c, #NonNull Node node) {
Intent i = new Intent(c, FeatureAudioActivity.class);
i.putExtra(NODE_TAG, node.getTag());
i.putExtras(NodeContainerFragment.prepareArguments(node));
return i;
}
/**
* listener for the audio feature, it will updates the audio values
*/
public final Feature.FeatureListener mAudioListener = new Feature.FeatureListener() {
#Override
public void onUpdate(final Feature f, final Feature.Sample sample) {
audioSample = FeatureAudioADPCM.getAudio(sample);
}
};
/**
* listener for the audioSync feature, it will update the synchronism values
*/
public final Feature.FeatureListener mAudioSyncListener = new Feature.FeatureListener() {
#Override
public void onUpdate(Feature f, final Feature.Sample sample) {
if(mBVAudioSyncManager!=null){
mBVAudioSyncManager.setSyncParams(sample);
}
}
};
/* ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */
private SeekBar mVolumeBar;
private AudioManager mAudioManager;
private Button mPlayButton;
private Button mStopButton;
private ImageButton mMuteButton;
private boolean mIsMute = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feature_audio);
// find the node.
String nodeTag = getIntent().getStringExtra(NODE_TAG);
mNode = Manager.getSharedInstance().getNodeWithTag(nodeTag);
List<Feature> listFeature = mNode.getFeatures();
for (Feature f : listFeature) {
if (f.isEnabled() && f.getName().equals("AudioFeature")) {
mAudio=(FeatureAudioADPCM) f;
}//if
if (f.isEnabled() && f.getName().equals("AudioSyncFeature")) {
mAudioSync=(FeatureAudioADPCMSync) f;
}//if
}//for
//create/recover the NodeContainerFragment
if (savedInstanceState == null) {
Intent i = getIntent();
mNodeContainer = new NodeContainerFragment();
mNodeContainer.setArguments(i.getExtras());
getFragmentManager().beginTransaction()
.add(mNodeContainer, NODE_FRAGMENT).commit();
} else {
mNodeContainer = (NodeContainerFragment) getFragmentManager()
.findFragmentByTag(NODE_FRAGMENT);
}//if-else
//builder audio track
mAudioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
FeatureAudioADPCM.AUDIO_PACKAGE_SIZE,
AudioTrack.MODE_STREAM);
mPlayButton = (Button) findViewById(R.id.playButton);
mStopButton = (Button) findViewById(R.id.stopButton);
mMuteButton = (ImageButton) findViewById(R.id.muteButton);
// //start speaker phone
// AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// audioManager.setMode(AudioManager.MODE_IN_CALL);
// audioManager.setSpeakerphoneOn(true);
// When the play button is pressed
mPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAudioTrack.play();
/*Write audio data for playback
#param short : The array that contains the data for playback
#param int: offset in rawAudio where playback data begins
#param int: The number of shorts to read in rawAudio after the offset
*/
mAudioTrack.write(audioSample,0,audioSample.length);
}
});
//When the stop button is pressed
mStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAudioTrack.stop();
}
});
//When the mute button is pressed
mMuteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeState();
}
boolean changeState(){
mIsMute=!mIsMute;
if(mIsMute)
muteAudio();
else
unMuteAudio();
return mIsMute;
}
private void muteAudio(){
mMuteButton.setImageResource(R.drawable.ic_volume_off_black_32dp);
mAudioManager.setStreamVolume(AUDIO_STREAM,0,0);
mVolumeBar.setEnabled(false);
}
private void unMuteAudio(){
mMuteButton.setImageResource(R.drawable.ic_volume_up_black_32dp);
mAudioManager.setStreamVolume(AUDIO_STREAM,mVolumeBar.getProgress(),0);
mVolumeBar.setEnabled(true);
}
});
setVolumeControlStream(AudioManager.STREAM_MUSIC);
initControls();
mAudioSync.addFeatureListener(mAudioSyncListener);
mAudio.setAudioSyncManager(mBVAudioSyncManager);
mAudio.addFeatureListener(mAudioListener);
mNode.enableNotification(mAudio);
}
// Volume control from SeekBar
private void initControls()
{
try
{
mVolumeBar = (SeekBar)findViewById(R.id.volumeValue);
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mVolumeBar.setMax(mAudioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
mVolumeBar.setProgress(mAudioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
mVolumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* if we have to leave this activity, we force to keep the connection open, since we go back
* in the {#link FeatureListActivity}
*/
#Override
public void onBackPressed() {
mNodeContainer.keepConnectionOpen(true);
super.onBackPressed();
}//onBackPressed
}
![1]: https://i.stack.imgur.com/IhKKC.jpg
Moving the write method inside the onUpdate method. This allows you to write new audio each time we have a new sample. Adding onResume and onUpdate methods in which we respectively enable and disable the mAudio and mAudioSync notifications. Changes to setOnClickListener methods for play and stop bottoms.
package com.st.BlueSTSDK.Example;
import android.content.Context;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import com.st.BlueSTSDK.Feature;
import com.st.BlueSTSDK.Features.FeatureAudioADPCM;
import com.st.BlueSTSDK.Features.FeatureAudioADPCMSync;
import com.st.BlueSTSDK.Manager;
import com.st.BlueSTSDK.Node;
import com.st.BlueSTSDK.Utils.BVAudioSyncManager;
import java.util.List;
public class FeatureAudioActivity extends AppCompatActivity {
/**
* Node that will show the data
*/
private Node mNode;
/** fragment used for keep the connection open */
private NodeContainerFragment mNodeContainer;
// Feature on which to apply the listener
private FeatureAudioADPCM mAudio;
// feature where we read the audio sync values
private FeatureAudioADPCMSync mAudioSync;
// The sampling rate
private static final int SAMPLE_RATE = 8000;
// audio manager
private static final int AUDIO_STREAM = AudioManager.STREAM_MUSIC;
// Audio track builder
private AudioTrack mAudioTrack;
//object containing the sync data needed in a ADPCM stream decoding
private BVAudioSyncManager mBVAudioSyncManager = new BVAudioSyncManager();
private final static String NODE_FRAGMENT = FeatureAudioActivity.class.getCanonicalName() + "" +
".NODE_FRAGMENT";
private final static String NODE_TAG = FeatureAudioActivity.class.getCanonicalName() + "" +
".NODE_TAG";
/**
* create an intent for start the activity that will log the information from the node
*
* #param c context used for create the intent
* #param node note that will be used by the activity
* #return intent for start this activity
*/
public static Intent getStartIntent(Context c, #NonNull Node node) {
Intent i = new Intent(c, FeatureAudioActivity.class);
i.putExtra(NODE_TAG, node.getTag());
i.putExtras(NodeContainerFragment.prepareArguments(node));
return i;
}
/**
* listener for the audio feature, it will updates the audio values
*/
public final Feature.FeatureListener mAudioListener = new Feature.FeatureListener() {
#Override
public void onUpdate(final Feature f, final Feature.Sample sample) {
short audioSample[] = FeatureAudioADPCM.getAudio(sample);
/*Write audio data for playback
#param short : The array that contains the data for playback
#param int: offset in rawAudio where playback data begins
#param int: The number of shorts to read in rawAudio after the offset
*/
mAudioTrack.write(audioSample,0,audioSample.length);
}
};
/**
* listener for the audioSync feature, it will update the synchronism values
*/
public final Feature.FeatureListener mAudioSyncListener = new Feature.FeatureListener() {
#Override
public void onUpdate(Feature f, final Feature.Sample sample) {
if(mBVAudioSyncManager!=null){
mBVAudioSyncManager.setSyncParams(sample);
}
}
};
/* ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */
private SeekBar mVolumeBar;
private AudioManager mAudioManager;
private Button mPlayButton;
private Button mStopButton;
private ImageButton mMuteButton;
private boolean mIsMute = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feature_audio);
// find the node.
String nodeTag = getIntent().getStringExtra(NODE_TAG);
mNode = Manager.getSharedInstance().getNodeWithTag(nodeTag);
List<Feature> listFeature = mNode.getFeatures();
for (Feature f : listFeature) {
if (f.isEnabled() && f.getName().equals("AudioFeature")) {
mAudio=(FeatureAudioADPCM) f;
}//if
if (f.isEnabled() && f.getName().equals("AudioSyncFeature")) {
mAudioSync=(FeatureAudioADPCMSync) f;
}//if
}//for
//create/recover the NodeContainerFragment
if (savedInstanceState == null) {
Intent i = getIntent();
mNodeContainer = new NodeContainerFragment();
mNodeContainer.setArguments(i.getExtras());
getFragmentManager().beginTransaction()
.add(mNodeContainer, NODE_FRAGMENT).commit();
} else {
mNodeContainer = (NodeContainerFragment) getFragmentManager()
.findFragmentByTag(NODE_FRAGMENT);
}//if-else
//builder audio track
mAudioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
FeatureAudioADPCM.AUDIO_PACKAGE_SIZE,
AudioTrack.MODE_STREAM);
mPlayButton = (Button) findViewById(R.id.playButton);
mStopButton = (Button) findViewById(R.id.stopButton);
mMuteButton = (ImageButton) findViewById(R.id.muteButton);
// When the play button is pressed
mPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!mIsMute){
mAudioTrack.play();
mAudioManager.setStreamVolume(AUDIO_STREAM,mVolumeBar.getProgress(),0);
}
}
});
//When the stop button is pressed
mStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopAudioTrack();
mAudioManager.setStreamVolume(AUDIO_STREAM,0,0);
}
});
//When the mute button is pressed
mMuteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeState();
}
boolean changeState(){
mIsMute=!mIsMute;
if(mIsMute)
muteAudio();
else
unMuteAudio();
return mIsMute;
}
private void muteAudio(){
mMuteButton.setImageResource(R.drawable.ic_volume_off_black_32dp);
mAudioManager.setStreamVolume(AUDIO_STREAM,0,0);
mVolumeBar.setEnabled(false);
}
private void unMuteAudio(){
mMuteButton.setImageResource(R.drawable.ic_volume_up_black_32dp);
mAudioManager.setStreamVolume(AUDIO_STREAM,mVolumeBar.getProgress(),0);
mVolumeBar.setEnabled(true);
}
});
//enable control volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
initControls();
}
#Override
public void onResume(){
super.onResume();
// enable needed notification
if(mAudio!=null && mAudioSync!=null) {
mAudio.addFeatureListener(mAudioListener);
mBVAudioSyncManager.reinitResetFlag();
mAudio.setAudioSyncManager(mBVAudioSyncManager);
mNode.enableNotification(mAudio);
mAudioSync.addFeatureListener(mAudioSyncListener);
mNode.enableNotification(mAudioSync);
}
}
#Override
public void onPause(){
super.onPause();
// disable needed notification
if(mAudio!=null) {
mAudio.removeFeatureListener(mAudioListener);
mNode.disableNotification(mAudio);
}
if(mAudioSync!=null) {
mAudioSync.removeFeatureListener(mAudioSyncListener);
mNode.disableNotification(mAudioSync);
}
}
private void stopAudioTrack(){
synchronized(this) {
mAudioTrack.pause();
mAudioTrack.flush();
}
}
// Volume control from SeekBar
private void initControls()
{
try
{
mVolumeBar = (SeekBar)findViewById(R.id.volumeValue);
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mVolumeBar.setMax(mAudioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
mVolumeBar.setProgress(mAudioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
mVolumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* if we have to leave this activity, we force to keep the connection open, since we go back
* in the {#link FeatureListActivity}
*/
#Override
public void onBackPressed() {
mNodeContainer.keepConnectionOpen(true);
super.onBackPressed();
}//onBackPressed
}
I have created a LoginActivity with the inbuilt template under new activity of Android Studio. I am using a SqlDatabase with PHP script for login purpose using post method.When i execute this code i get 2 errors:
1) Error:(370, 9) error: method does not override or implement a method from a supertype
C:\Users\Chethan\AndroidStudioProjects\CleanMyChennai\app\src\main\java\com\exa mple\chethan\myapplication\LoginPage.java
2) Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
How to fix these two errors. by the way i am a beginner in java coding.
Plz help me if you find where i have i gone wrong.. I haven't found any tutorial that makes use of Default "LoginActivity" layout provided in Android Studio. i want to connect loginactivity.java along with PHP-MySql connection
package com.example.chethan.myapplication;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
import static java.net.URLEncoder.encode;
/**
* A login screen that offers login via email/password.
*/
public class LoginPage extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo#example.com:hello", "bar#example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
// mAuthTask.execute((Void) null);
mAuthTask.execute();
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginPage.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<String, String, String> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected String doInBackground(String... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
//Thread.sleep(2000);
String username = (String)params[0];
String password = (String)params[1];
String link="http://localhost/login.php";
String data = encode("username", "UTF-8") + "=" + encode(username, "UTF-8");
data += "&" + encode("password", "UTF-8") + "=" + encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}
catch (Exception e) {
//return false;
return new String("Exception: " + e.getMessage());
}
/*
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
*/
/* TODO: register the new account here. */
/* return true; */
}
#Override
protected void onPostExecute(final Boolean success) {
// super.onPostExecute(success);
mAuthTask = null;
showProgress(false);
if (success) {
finish();
Toast.makeText(getApplicationContext(),"login success",Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(LoginPage.this,Authorities.class);
LoginPage.this.startActivity(myIntent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
I saw your problem, is in your onPostExecute have Boolean success as a parameter, change the type of success to String success.
You are returning String from doInBackground
Final implementation should look like this:
protected void onPostExecute(final String success) {
// super.onPostExecute(success);
mAuthTask = null;
showProgress(false);
if (success.equals("true")) {
finish();
Toast.makeText(getApplicationContext(),"login success",Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(LoginPage.this,Authorities.class);
LoginPage.this.startActivity(myIntent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
For more info check this question Can't Override onPostExecute() method in AsyncTask Class or get it to trigger
Hope this helps!!
I imported THIS LIBRARY to get my all posts i set up all imports and so, I have follow the steps and wirte this code,Actually i wanted to show my page's all public posts in my app.like some apps or website keeps that is looks like facebook's real page. is it possible or not in android? thanks.
package algonation.com.myapplication;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.actions.Cursor;
import com.sromku.simple.fb.entities.Post;
import com.sromku.simple.fb.listeners.OnPostsListener;
import java.util.List;
public class FacebookActivity extends ActionBarActivity {
private final static String EXAMPLE = "";
private String mAllPages = "";
OnPostsListener onPostsListener = new OnPostsListener() {
#Override
public void onComplete(List<Post> posts) {
Log.i(EXAMPLE, "Number of posts = " + posts.size());
}
/*
* You can override other methods here:
* onThinking(), onFail(String reason), onException(Throwable throwable)
*/
};
private TextView mResult;
private Button mGetButton;
private TextView mMore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
mResult = (TextView) findViewById(R.id.result);
mMore = (TextView) findViewById(R.id.load_more);
mMore.setPaintFlags(mMore.getPaint().getFlags() | Paint.UNDERLINE_TEXT_FLAG);
mGetButton = (Button) findViewById(R.id.button);
mGetButton.setText(EXAMPLE);
mGetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAllPages = "";
mResult.setText(mAllPages);
SimpleFacebook.getInstance().getPosts(new OnPostsListener() {
#Override
public void onThinking() {
}
#Override
public void onException(Throwable throwable) {
mResult.setText(throwable.getMessage());
}
#Override
public void onFail(String reason) {
mResult.setText(reason);
}
#Override
public void onComplete(List<Post> response) {
// make the result more readable.
mAllPages += "<u>\u25B7\u25B7\u25B7 (paging) #" + getPageNum() + " \u25C1\u25C1\u25C1</u><br>";
mAllPages += com.sromku.simple.fb.utils.Utils.join(response.iterator(), "<br>", new com.sromku.simple.fb.utils.Utils.Process<Post>() {
#Override
public String process(Post post) {
return "\u25CF " + post.getMessage() == null || "null".equalsIgnoreCase(post.getMessage()) ? post.getId() : post.getMessage() + " \u25CF";
}
});
mAllPages += "<br>";
mResult.setText(Html.fromHtml(mAllPages));
// check if more pages exist
if (hasNext()) {
enableLoadMore(getCursor());
} else {
disableLoadMore();
}
}
});
}
});
}
#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_facebook, 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);
}
private void enableLoadMore(final Cursor<List<Post>> cursor) {
mMore.setVisibility(View.VISIBLE);
mMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mAllPages += "<br>";
cursor.next();
}
});
}
private void disableLoadMore() {
mMore.setOnClickListener(null);
mMore.setVisibility(View.INVISIBLE);
}
}
If you look at the code of the library, you'll see this note:
/**
* Get the instance of {#link com.sromku.simple.fb.SimpleFacebook}. <br>
* <br>
* <b>Important:</b> Use this method only after you initialized this library
* or by: {#link #initialize(android.app.Activity)} or by {#link #getInstance(android.app.Activity)}
*
* #return The {#link com.sromku.simple.fb.SimpleFacebook} instance
*/
You should use SimpleFacebook.getInstance(FacebookActivity.this) because the method you're using will return an uninitialised reference (null), unless you have initialised it previously.
Please spend some time reading the documentation of the library - the guy has clearly spent some time working on huge wiki.