Substring in Java Eclipse Project - java

I'm pretty new to this. I'm working on an app in eclipse to read card reader input. Currently, the card reader as usual reads out the card details all in a single row of entry (its a tract 2 reader). It will be changed to a track1 card reader, then I can use the cardHolderName text. Here's a sample card output
;1234567890111213=12345678901113141516?
I would like to;
remove the first ";" everytime a card is read
Add the first 16 digits (after the ";") to a textfield
Remove the "="
display the first 4 digits after the "=" sign in another textfield
So the two textfields should display:
Textfield1:1234567890111213
Textfield2: 12/34
I tried using the substring() method in the setText lines, but it didn't provide any results. Can anyone help identify where I'm making a mistake ?
The .java code i am working on is below; Much appreciated!
package com.square;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Payments extends Activity {
private UpdateBytesHandler updateBytesHandler;
private UpdateBitsHandler updateBitsHandler;
private TextView decodedStringView;
private TextView strippedBinaryView;
private TextView holderName;
private TextView expiryDate;
private TextView cardNumber;
private Button startBtn;
private Button stopBtn;
private MagRead read;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button)findViewById(R.id.startbtn);
stopBtn = (Button)findViewById(R.id.stopbtn);
stopBtn.setEnabled(false);
decodedStringView = (TextView)findViewById(R.id.bytes);
strippedBinaryView = (TextView)findViewById(R.id.bits);
holderName = (TextView)findViewById(R.id.holderNameReal);
cardNumber = (TextView)findViewById(R.id.cardNumberReal);
expiryDate = (TextView)findViewById(R.id.expiry);
read = new MagRead();
read.addListener(new MagReadListener() {
#Override
public void updateBytes(String bytes) {
Message msg = new Message();
msg.obj = bytes;
updateBytesHandler.sendMessage(msg);
}
#Override
public void updateBits(String bits) {
Message msg = new Message();
msg.obj = bits;
updateBitsHandler.sendMessage(msg);
}
});
MicListener ml = new MicListener();
startBtn.setOnClickListener(ml);
stopBtn.setOnClickListener(ml);
updateBytesHandler = new UpdateBytesHandler();
updateBitsHandler = new UpdateBitsHandler();
}
#Override
protected void onDestroy() {
super.onDestroy();
read.release();
}
/**
* Listener called with the mic status button is clicked, and when the zero level or noise thresholds are changed
*/
private class MicListener implements OnClickListener{
/**
* Called when the mic button is clicked
* #param
*/
#Override
public void onClick(View v) {
if(v == stopBtn){//stop listening
stopBtn.setEnabled(false);
startBtn.setEnabled(true);
read.stop();
}else if(v == startBtn) {//start listening
stopBtn.setEnabled(true);
startBtn.setEnabled(false);
read.start();
}
}
}
private class UpdateBytesHandler extends Handler {
#Override
public void handleMessage(Message msg) {
String bytes = (String)msg.obj;
decodedStringView.setText(bytes);
}
}
private class UpdateBitsHandler extends Handler {
#Override
public void handleMessage(Message msg) {
String bits = (String)msg.obj;
strippedBinaryView.setText(bits);
}
}
private class UpdateHolderName extends Handler {
#Override
public void handleMessage(Message msg) {
String holderN = (String)msg.obj;
holderName.setText(holderN);
}
}
private class UpdateCardNumber extends Handler {
#Override
public void handleMessage(Message msg) {
String cardN = (String)msg.obj;
cardNumber.setText(cardN);
}
}
private class UpdateExpiry extends Handler {
#Override
public void handleMessage(Message msg) {
String exp = (String)msg.obj;
expiryDate.setText(exp);
}
}
}`

Consider this to your string
String data = ";1234567890111213=12345678901113141516?"
String first= data.substring(1, 17);
String second= data.substring(18, data.length()-1);
For more understanding, follow this tutorial

Check the java String method substring(i,j)
String code = ";1234567890111213=12345678901113141516?";
String first = code.substring(1,17);
String second = code.substring(18,19) + "/" + code.substring(20,21);
IMPORTANT substring() returns a new String !
Returns a new string that is a substring of this string.
So you must store the result in a variable.

Related

Get elements of ArrayList from retrieved ArrayList via intent via Parcelable in 2nd activity

I'm trying to build a simple android that should simulate learning vocabulary with cards. to get to the final app, I'm going to add functionality and complexity step by step, by learning new things, and adding new things.
I'm about to tell you where I'm stuck, but first, here's what my App should do, so far (I'm still far, far way from where I'd like it to go, but you don't have to mind about that.):
At this point the app should do the folowing thing:
1) in the MainActivity:
a) Create an Array of 3 instances of an implementation of the
Parcelable interface (class VocCard implements Parcelable), VocCard[]
voc1, in this case. Since the class VocCard implements Parcelable, a
Parcel is obtained for the construction of the 3 instances.
b) Create an ArrayList of the type VocCard called vocCardList and add
all 3 elements of voc1 to vocCardList.
c) Create an instance of a start button which creates an intent for
starting a 2nd activity called PracticeActivity when clicked.
d) Add the ArrayList vocCardList with Parcelable to the
intent.
2) in PracticeActivity
a) Get the intent created by MainActivity.
b) Retrieve ArrayList vocCardList from intent
c) Get any element of vocCardsList and assign a variable of the type
VocCard to it.
d) Retrieve a value of the assigned Voccard instance by invoking its
methods.
e) Display that value by setting a TextView to the value's String
value.
f) Create a Button nextButton which creates an intent for starting
the 2nd activity PracticeActivity again, as some kind of recursion.
g) Add the ArrayList vocCardList with parcelable to intent.
h) repeat 2) a)-g) until App is closed by closing-icon.
I'm currently stuck at 2) c), insofar that the App only works as described above for the index 0. Only VocCard card0 = vocCardList1.get(0); works, vocCardList1.get(1), or vocCardList1.get(2); don't, despite 1 and 2 being within the ArrayList boundries.
Oddly enough, the Runtime Exeption Message for using index 1 and index 2 is not the same:
with vocCardList1.get(1): java.lang.ClassCastException: java.lang.String cannot be cast to com.undiclosed.smartcards.VocCard
with vocCardList1.get(2): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.undisclosed.smartcards.VocCard.returnVocForeign()' on a null object reference
Question:
Why can't I acces the elements of the ArrayList the way I expected? When I searched the web I was probably looking for the wrong stuff.
MainActivity.java:
package com.undisclosed123.smartcards;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<VocCard> vocCardList;
private String[] voc_f = {"bread","apple","water"};
private String[] voc_n = {"pain","pomme","eau"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create VocCards and add to List
vocCardList = new ArrayList<VocCard>();
VocCard[] voc1 = new VocCard[3];
Parcel in = Parcel.obtain();
for(int i = 0; i < 3; i++){
voc1[i] = new VocCard(in);
voc1[i].setVocForeign(voc_f[i]);
voc1[i].setVocNative(voc_n[i]);
vocCardList.add(voc1[i]);
}
// Create Intent and assign the parcelable List for sending to second activity on btn click
Button startBtn = (Button) findViewById(R.id.button);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("unchecked")
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, PracticeActivity.class);
intent.putParcelableArrayListExtra("voc1",(ArrayList)vocCardList);
getApplicationContext().startActivity(intent);
}
});
}
}
And below, PracticeActivity.java:
(Sorry for the large sections which are commented out, I figured it could help communicating my further intentions for that class)
package com.undisclosed123.smartcards;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class PracticeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practice);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
final ArrayList<VocCard> vocCardList1 = intent.getParcelableArrayListExtra("voc1"); //
//Get the Data from the VocCards
//VocCard card4count = vocCardList1.get(2);
// card4count.increaseCount();
//int count = card4count.getCount();
/* if(count >= vocCardList1.size()){
// TODO
//Create new intent for EndPracticeActivity
//makeshift statement
count--;
}*/
VocCard card0 = vocCardList1.get(2);
// VocCard card1 = vocCardList1.get(1);
String test1 = card0.returnVocForeign();
// card0.increaseCount();
// String test1 = "test1";
//Make a TextView display the transfered String
TextView textView = findViewById(R.id.textView);
textView.setText(test1);
//Create another intent that recalls same activity recursively
Button nextBtn = (Button) findViewById(R.id.button2);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("unchecked")
public void onClick(View v) {
Intent intent = new Intent(PracticeActivity.this, PracticeActivity.class);
intent.putParcelableArrayListExtra("voc1",(ArrayList)vocCardList1);
getApplicationContext().startActivity(intent);
}
}); /**/
}
}
And at last, VocCard.java:
package com.undisclosed123.smartcards;
import android.os.Parcel;
import android.os.Parcelable;
public class VocCard implements Parcelable {
private String voc_foreign;
private String voc_native;
private boolean learned;
private int error_level;
private static int counter;
public String returnVocForeign(){
return voc_foreign;
}
public void setVocForeign(String voc_f){
voc_foreign = voc_f;
}
public String returnVocNative(){
return voc_native;
}
public void setVocNative(String voc_n){
voc_native = voc_n;
}
public boolean checkLearned(){
return learned;
}
public int getErrorLevel(){
return error_level;
}
public void makeLearned(){
learned = true;
}
public void increaseErrorLevel(){
error_level++;
}
public int getCount(){
return counter;
}
public void increaseCount(){
counter++;
}
public VocCard(Parcel in) {
voc_foreign = in.readString();
voc_native = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(voc_foreign);
dest.writeString(voc_native);
dest.writeInt((Boolean) learned ? 1 : 0);
dest.writeInt(error_level);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<VocCard> CREATOR = new Creator<VocCard>() {
#Override
public VocCard createFromParcel(Parcel in) {
return new VocCard(in);
}
#Override
public VocCard[] newArray(int size) {
return new VocCard[size];
}
};
}
The problem is with writing data to Parcel and reading data from it.
public class VocCard implements Parcelable {
...
...
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(voc_foreign);
dest.writeString(voc_native);
dest.writeInt(learned ? 1 : 0);
dest.writeInt(error_level);
}
/**
* This constructor is invoked by the method
* createFromParcel(Parcel source) of the object CREATOR.
*
* The order and number of writing and reading data to and from
* Parcel should be same
**/
private VocCard(Parcel in) {
voc_foreign = in.readString();
voc_native = in.readString();
learned = in.readInt() == 1;
error_level = in.readInt();
}
/**
* A constructor that initializes the VocCard object.
**/
VocCard(String voc_foreign, String voc_native) {
this.voc_foreign = voc_foreign;
this.voc_native = voc_native;
}
...
...
}
Few changes in MainActivity inside onCreate
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
...
...
//Create VocCards and add to List
mVocCardList = new ArrayList<>(3);
for (int i = 0; i < 3; i++) {
mVocCardList.add(new VocCard(voc_f[i], voc_n[i]));
}
Button startBtn = (Button) findViewById(R.id.button);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, PracticeActivity.class);
intent.putParcelableArrayListExtra("voc1", (ArrayList<? extends Parcelable>) mVocCardList);
startActivity(intent);
}
});
}
Now get the VocCard list in PracticeActivity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
...
...
final ArrayList<VocCard> vocCardList = getIntent().getParcelableArrayListExtra("voc1");
final VocCard card = vocCardList.get(2);
String test = card.getVocForeign();
...
...
}

Play audio on smartphone, received via bluetooth, from a SensorTile (STEVAL-STLKT01V1)

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
}

ADK toolkit Android+Arduino store variable issue

I'm writing a program which is supposed to run "forever". The program is Android application for tablet which exchanges data with Arduino. I have already implemented the code for Arduino and Android, and it exchanges data very well. However, after 2 cycles of work, my instance of AdkManager becomes NULL. As I've read before, Android will null variables from time to time because it has limited resources. However here's the problem - the AdkManager has confirmed bug that once it has been closed, it can't be reopened. Thus I can't re-initiate the AdkManager instance and I need to store it somehow. So far I've been using Application extension. The code is below:
MyApplication:
package org.udoo.androidadkdemobidirect;
import android.app.Application;
import android.content.Context;
import android.hardware.usb.UsbManager;
import me.palazzetti.adktoolkit.AdkManager;
/**
* Created by admin on 8/18/16.
*/
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
public static class sAdkManager{
private static sAdkManager ourInstance = null;
public static sAdkManager getInstance() {
if (ourInstance==null)
ourInstance = new sAdkManager();
return ourInstance;
}
private static AdkManager mAdkManager = null;
public void write(String s){
mAdkManager.writeSerial(s);
}
public String read(){
return mAdkManager.readSerial();
}
public void open(){
mAdkManager.open();
}
public void close(){
mAdkManager.close();
}
public boolean checkNull(){
return mAdkManager==null;
}
public static void init(Context context){
if(mAdkManager==null) {
mAdkManager = new AdkManager((UsbManager) context.getSystemService(Context.USB_SERVICE));
context.registerReceiver(mAdkManager.getUsbReceiver(), mAdkManager.getDetachedFilter());
}
}
private sAdkManager() {
}
}
}
MainActivity:
package org.udoo.androidadkdemobidirect;
import me.palazzetti.adktoolkit.AdkManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
//import org.udoo.androidadkdemobidirect.sAdkManager;
public class MainActivity extends Activity{
// private static final String TAG = "UDOO_AndroidADKFULL";
private static String mAdkManager=null;
private ToggleButton buttonLED;
private TextView distance;
private AdkReadTask mAdkReadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
//// register a BroadcastReceiver to catch UsbManager.ACTION_USB_ACCESSORY_DETACHED action
// registerReceiver(mAdkManager.getUsbReceiver(), mAdkManager.getDetachedFilter());
buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLed);
distance = (TextView) findViewById(R.id.textViewIntro);
// mAdkManager.open();
TextView tv = (TextView) findViewById(R.id.ppm);
if (mAdkManager==null){
tv.setText("ADK is null. init()");
mAdkManager = new String ("sometext");
}
else{
tv.setText("ADK is not null.");
}
if (MyApplication.sAdkManager.getInstance().checkNull()) {
distance.setText("Null before init");
MyApplication.sAdkManager.init(this);
}
if (MyApplication.sAdkManager.getInstance().checkNull()) {
distance.setText("Null after init");
}
MyApplication.sAdkManager.getInstance().open();
mAdkReadTask = new AdkReadTask();
mAdkReadTask.execute();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
MyApplication.sAdkManager.getInstance().close();
// unregisterReceiver(mAdkManager.getUsbReceiver());
super.onDestroy();
}
// ToggleButton method - send message to SAM3X
public void blinkLED(View v){
if (buttonLED.isChecked()) {
TextView tvdbg = (TextView) findViewById(R.id.ppm);
tvdbg.setText("send 1");
// writeSerial() allows you to write a single char or a String object.
//mAdkManager.writeSerial("1");
MyApplication.sAdkManager.getInstance().write("1");
// mAdkManager.writeSerial("8");
} else {
//mAdkManager.writeSerial("0");
MyApplication.sAdkManager.getInstance().write("0");
}
}
/*
* We put the readSerial() method in an AsyncTask to run the
* continuous read task out of the UI main thread
*/
private class AdkReadTask extends AsyncTask<Void, String, Void> {
private boolean running = true;
public void pause(){
running = false;
}
protected Void doInBackground(Void... params) {
// Log.i("ADK demo bi", "start adkreadtask");
while(running) {
// if (mAdkManager.serialAvailable())
// publishProgress(mAdkManager.readSerial()) ;
publishProgress(MyApplication.sAdkManager.getInstance().read());
}
return null;
}
protected void onProgressUpdate(String... progress) {
distance.setText("You put "+((int)progress[0].charAt(0)-48) + " iqos butts\tRFID OK");
next();
// Log.i(TAG, "received: " + (int)progress[0].charAt(0));
}
}
private void next() {
final Intent intent = new Intent(this, BRActivity.class );
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
mAdkReadTask.pause();
mAdkReadTask = null;
startActivity(intent);
}
},
3000);
}
}
There are just 2 Activities for now - MainActivity and BRActivity. BRActivity is just a view with "return" button which comes back to MainActivity.
Also what I find interesting - I output the readSerial in TextView to see what I got in reader thread. However on cycle#2 i don't get any output to TextView, but Activity still changes to the next one.
[EDIT]
Apparently the problem was solved when the thread was nulling. However, I still don't get the text update, but I magically get to another screen. Please advice.

Cannot initiate the type View.onclicklistner

I am getting this error on line 174
code was working fine but after last update I am getting this error that Cannot initiate the type View.onclicklistner
this is client code for chat functionality using websockets
how to fix this???
package de.lauridmeyer.com.tests;
import org.jwebsocket.api.WebSocketClientEvent;
import org.jwebsocket.api.WebSocketClientTokenListener;
import org.jwebsocket.api.WebSocketPacket;
import org.jwebsocket.client.plugins.rpc.Rpc;
import org.jwebsocket.client.plugins.rpc.RpcListener;
import org.jwebsocket.client.plugins.rpc.Rrpc;
import org.jwebsocket.client.token.BaseTokenClient;
import org.jwebsocket.kit.WebSocketException;
import org.jwebsocket.token.Token;
import org.jwebsocket.token.TokenFactory;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SimpleJWAndroidClientActivity extends Activity implements WebSocketClientTokenListener{
//GUI Elements
private static TextView log;
private static TextView Chatlog;
private static EditText ipadress;
private static EditText Message;
private static Button send;
private static Button conBtn;
private String entered_msg=null;
TextView customDialog_TextView;
Button customDialog_Yes, customDialog_No;
static final int CUSTOM_DIALOG_ID = 0;
public static String decision=null;
//stores if the SLider is changed by the user or the server
private static Boolean isDragging=false;
//stores the connection status
private static Boolean connected=false;
//used for the connection
private static BaseTokenClient btc = new BaseTokenClient();//create a new instance of the base token client
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
log = (TextView)findViewById(R.id.log);//Textview to Display Messages
ipadress=(EditText)findViewById(R.id.ipadress);//inputfield for the ipadress
Chatlog=(TextView)findViewById(R.id.chat);
conBtn= (Button)findViewById(R.id.conBtn);//(dis)connection button
Message=(EditText)findViewById(R.id.Message);
send= (Button)findViewById(R.id.Send);
//add the listener for the slider and the (dis)connection Button
conBtn.setOnClickListener(buttonConnectOnClickListener);
//add the listener for the websocket connection
btc.addListener(this);//add this class as a listener
btc.addListener(new RpcListener());//add an rpc listener
Rpc.setDefaultBaseTokenClient(btc);//set it to the default btc
Rrpc.setDefaultBaseTokenClient(btc);//same here
//set the connection status to "not connected" on startup
changeConnectionStatus(false);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
entered_msg = Message.getText().toString();
Token firstToken = TokenFactory.createToken("com.lauridmeyer.tests.LauridsPlugIn","Welcomemessage");
firstToken.setString("message",entered_msg);//add the message to the token
try {
btc.sendToken(firstToken);//try to send the token to the server
} catch (WebSocketException ex) {
outputText("error:"+ex.getMessage());//log errors
}
}
});
}
private OnClickListener buttonConnectOnClickListener = new OnClickListener() {
public void onClick(View v){
if(!connected){//if not connected
try{
String ipAdress=ipadress.getText().toString();//get the ip-adress from the inputfield
outputText("connecting to "+ipAdress+" ...");//debug
btc.open(ipAdress);//try to open the connection to your server
}catch(Exception e){
outputText("Error while connecting...");//log errors
}
}else{//if connected
try{
btc.close();//try to close
}catch(Exception e){
outputText(e.toString());//log errors
}
}
}
};
// private static SeekBar.OnSeekBarChangeListener seekbarchangedListener = new SeekBar.OnSeekBarChangeListener(){
// //Method is fired everytime the seekbar is changed
// #Override
// public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// if(isDragging && connected){//if the ssekbar is changed by the user and not by the server
// //create a new Token with the namspace, and type
// Token tempToken = TokenFactory.createToken("com.lauridmeyer.tests.LauridsPlugIn","sliderChanged");
// tempToken.setInteger("value",progress);//add an integer to the token
// try {
// btc.sendToken(tempToken);//try to send the token to the server
// } catch (WebSocketException ex) {
// outputText("error:"+ex.getMessage());//log errors
// }
// }
// }
//
// #Override
// public void onStartTrackingTouch(SeekBar seekBar) {
// isDragging=true;//turn the sending mechanism on
// }
//
// #Override
// public void onStopTrackingTouch(SeekBar seekBar) {
// isDragging=false;//turn the sending mechanism off
// }
// };
/* Method is called when the connection status has changed
* connected <-> disconnected */
public static void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
//seekBar.setEnabled(isConnected);//enable/disable seekbar
if(isConnected){//if connection established
outputText("successfully connected to server");//log
conBtn.setText("DISCONNECT");//change Buttontext
}else{
outputText("disconnected from Server!");//log
conBtn.setText("CONNECT");//change Buttontext
}
}
/* Method prints text to the log textfield*/
public static void outputText(String msg) {
log.append(msg+"\n");
}
/* Message handler is used to process incoming tokens from the server*/
private Handler messageHandler = new Handler() {
#Override
public void handleMessage(Message aMessage) {
if(aMessage.what==0){//if it's a token
Token aToken =(Token) aMessage.obj;//get the received token
//if the namespace matches my plugin
if(aToken.getNS().equals("com.lauridmeyer.tests.LauridsPlugIn")){
//and it's a command that the slider has changed
//String wM = aToken.getString("Welcomemessage");
if(aToken.getString("reqType").equals("sliderHasChanged")){
int value=aToken.getInteger("value");//get the slider value
isDragging=false;//make sure that the slider changes are not recognized as user inputs
//seekBar.setProgress(value);//move the slider to the recieved position
}
if(aToken.getString("reqType").equals("Welcomemessage")){
String message=aToken.getString("Welcomemessage");//get the slider value (here)
Chatlog.setOnClickListener(new View.OnClickListener());
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
}
}
}
};
#Override
public void processOpened(WebSocketClientEvent aEvent) {
changeConnectionStatus(true);//when connected change the status
}
#Override
public void processClosed(WebSocketClientEvent aEvent) {
changeConnectionStatus(false);//when disconnected change the status
}
#Override
public void processToken(WebSocketClientEvent aEvent, Token aToken) {
//for some reason you can't process the token directly
//you have to use the messagehandler
Message lMsg = new Message();//create a new mess
lMsg.what = 0;
lMsg.obj = aToken;
messageHandler.sendMessage(lMsg);
}
//following Methods are not used in this example, but have to be there :)
#Override
public void processPacket(WebSocketClientEvent aEvent, WebSocketPacket aPacket) {
}
#Override
public void processOpening(WebSocketClientEvent aEvent) {
}
#Override
public void processReconnecting(WebSocketClientEvent aEvent) {
}
}
The line:
Chatlog.setOnClickListener(new View.OnClickListener());
It doesn't look like you're overriding a onClick() method.

How parcelable works and why data should be in sequence?

I am using Parcelable. Here, i have done some test code.
TestParcelable.java
--------------------
package com.example.parcelableexample;
import android.os.Parcel;
import android.os.Parcelable;
public class TestParcelable implements Parcelable {
private String bName;
private String aName;
private int pTime;
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public int getpTime() {
return pTime;
}
public void setpTime(int pTime) {
this.pTime = pTime;
}
public static final Parcelable.Creator<TestParcelable> CREATOR = new Creator<TestParcelable>() {
#Override
public TestParcelable createFromParcel(Parcel source) {
TestParcelable test = new TestParcelable();
test.bName = source.readString();
test.aName = source.readString();
test.pTime = source.readInt();
return test;
}
#Override
public TestParcelable[] newArray(int size) {
return new TestParcelable[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(bName);
dest.writeInt(pTime);
dest.writeString(aName);
}
}
MainActivity.java
-------------------
package com.example.parcelableexample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button btnPar;
public final static String PAR_KEY = "com.example.parcelableexample.par";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnPar = (Button) findViewById(R.id.button2);
btnPar.setOnClickListener(this);
}
public void parcelableMethod() {
TestParcelable testParcelable = new TestParcelable();
testParcelable.setbName("TOC");
testParcelable.setaName("Ullman");
testParcelable.setpTime(0000);
Intent intent = new Intent(this, ObjectP.class);
Bundle bundle = new Bundle();
bundle.putParcelable(PAR_KEY, testParcelable);
intent.putExtras(bundle);
startActivity(intent);
}
#Override
public void onClick(View v) {
if(v == btnSer) {
parcelableMethod();
}
}
When i am changing the sequence of write in this method writeToParcel(), than it is taking some null value instead of actual value. Some please explain why we should maintain the sequence of read and write data in parcelable?
I am not perfectly sure but according to my understanding both methods i.e. writeToParcel and createFromParcel are working like a pair, means you have to have same sequence in both of the methods.
Its working something like,
writeToParcel is generating a string in which its writing your first value i.e. bName(string value) than some seperator than pTime (int value) than again seperator and than aName (string value) while createFromParcel is converting from that string to object it is not getting the sequence as its expecting. Thats why it getting null value.
If you have to change sequence than you have to change on both ends.
note: above explanation is just for understanding , i am not truly aware of internal mechanism of these methods.

Categories

Resources