Oscilloscope app using mpandroidchart - mpandroidchart

I'm trying to create an app that can display linegraphs at a sample rate of 15 kHz frequency and have run into two main problems:
I cant seem to set the sample rate to anywhere below 1 ms(I'm using thread.sleep(1) to set the time duration between each value.
Also the graph shows too little onscreen at any given time. I've set xAxis.setSpaceBetweenLabels to 1 and still am only getting about 6 entries on screen at any given time. Is it at all possible to get a higher sample rate(at the order of nanoseconds) and get the chart to display much higher number of entries on screen?
Currently the app displays random values as the entries. This is the code snippet:
#Override
protected void onResume() {
super.onResume();
//real time addition
new Thread(new Runnable() {
#Override
public void run() {
//adding 100 entries
for ( int i = 0;i<3000; i++) {
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
//pausing between each addition
//pausing between each addition
try{
Thread.sleep(600);
} catch (InterruptedException e) {
// to manage error....
}
}
}
}).start();
}
EDIT: Figured out how to show more entries onscreen (setVisibleXRange) but still have the problem of increasing samplerate.

In order to increase sampling rate just use TimeUnit.NANOSECONDS.sleep instead of Thread.sleep.
Also don't forget to import TimeUnit library(alt enter doesnt work) ;)
Thanks for all the help.

Related

How can I load - inflate items to a Recycler view without locking the UI or showing a load icon?

I just want to be able to display a list of contacts (without even communicating to a server) just the way it is displayed on the "Contacts" native app on the phone.
I have like 1500 contacts and when I try to load the recycler view, all items at once, it lags a lot 2 - 3 seconds.
I've achieved loading more items but with a loading bar and thats not what I want.
I've already tried Threads, Executors, postOnUIThread(), handler.post() and even AsyncTask -> Override -> doOnBackground. Nothing works.
private class CustomTask extends AsyncTask<Void, Void, Void> {
int inserted;
#Override
protected Void doInBackground(Void... param) {
//Do some work
try {
lcf.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
((BaseActivity) lcf.getActivity()).showProgressDialog();
}
});
int currentSize = contactsLoaded.size();
for (inserted = 0; inserted < lcf.getController().getContacts().size() && contactsLoaded.size() < lcf.getController().getContacts().size(); inserted++) {
contactsLoaded.add(lcf.getController().getContacts().get(currentSize + inserted));
notifyItemRangeInserted(contactsLoaded.size() - 1, inserted);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void param) {
//Print Toast or open dialog
//notifyItemRangeInserted(contactsLoaded.size() - 1, 0);
if(!lcf.getController().isSelectedAffiliated()){
lcf.disclaimerLayout.setVisibility(View.VISIBLE);
}else{
lcf.disclaimerLayout.setVisibility(View.GONE);
}
lcf.isLoading=false;
((BaseActivity) lcf.getActivity()).hideProgressDialog();
}
}
That code lives within my adapter, "lcf" is a reference to the fragment. If I use the already loaded list saved on the controller (that I get from the fragment reference) and then just call notifyDataSetChanged() it LAGS like hell. So with this CustomTask I tried to load every item and notify it one by one to a Background task hoping it would make the items pop up quickly and sequentially without interfereing with the UI thread to not freeze the screen. It doesn't work. I am out of options now. I've tried everything.

Dynamic time display crash on orientation

I have a layout that will display a TextView which is used to display a ticking time.I followed the codes from this link
How to Display current time that changes dynamically for every second in android
but I get an error of
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I had the same problem here but I fixed it
Intent extras null on configuration change
Here are the Java codes
void clockTicking(){
final CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
timeDisplay = (TextView)findViewById(R.id.txtTime);
Calendar c = Calendar.getInstance();
timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)+" PM");
}
public void onFinish() {
}
};
newtimer.start();
In your code timeDisplay object is null.
Make sure your textview id is correct. Double check this line timeDisplay = (TextView)findViewById(R.id.txtTime);
I think your id txtTime is incorrect.
Hope it will helpful.
Okay so I finally fixed it,the only reason why it crashed was because during orientation the layout I used has no TextView which Mitesh Vanaliya stated was correct.So I fixed it by turning it off upon orientation using this code thanks to Ayyappan from
How to Display current time that changes dynamically for every second in android
Turning off the clock
void clockUnTicking(){
CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
timeDisplay = (TextView)findViewById(R.id.txtTime);
Calendar c = Calendar.getInstance();
timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
}
public void onFinish() {
}
};
newtimer.cancel();
}
to turn it on just replace newtimer.cancel(); with newtimer.start()

Java - pressing a direction key and having it move smoothly

When I press a direction key to move the object in that direction, it moves once, pauses momentarily, then moves again. Kind of like how if I want to type "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", I would hold "a" key down, but after the first "a" there is a pause then the rest of the "a"'s are typed. How do I remove that pause in KeyListener? Thank you.
This is the key repetition feature that the OS provides, so there is no way around the pauses.
The way most games gets around this is to keep an array of the current state of all required keys and check periodically on them (for example in the game loop) and act on that (e.g move).
public class KTest extends JFrame implements KeyListener {
private boolean[] keyState = new boolean[256];
public static void main(String[] args) {
new KeyTest();
int xVelocity = 0;
int x = 0;
while(1) {
xVelocity = 0;
if(keyState[KeyEvent.VK_LEFT]) {
xVelocity = -5;
}
x += xVelocity;
}
}
KTest() {
this.addKeyListener(this);
}
void keyPressed(KeyEvent e) {
key_state[e.getKeyCode()] = true;
}
void keyReleased(KeyEvent e) {
key_state[e.getKeyCode()] = false;
}
}
Base class taken from: http://content.gpwiki.org/index.php/Java:Tutorials:Key_States

MP3 Playing with NAudio - Problems with Stop()

I've just started using NAudio (1.4) solely for MP3 playback. I've been working off the documentation and the source code for the samples. Currently I have this in a class:
IWavePlayer waveOutDevice;
WaveStream mainOutputStream;
WaveChannel32 volumeStream;
public AudioPlaybackService() : base() {
waveOutDevice = new WasapiOut(AudioClientShareMode.Shared, 100);
}
public bool LoadTrack(string trackPath, float volume)
{
if (!File.Exists(trackPath))
return false;
try
{
mainOutputStream = new Mp3FileReader(trackPath);
volumeStream = new WaveChannel32(mainOutputStream);
volumeStream.Volume = volume;
waveOutDevice.Init(mainOutputStream);
}
catch (Exception e)
{
Logger.Error("Failed to load track for playback {0} :: {1}", trackPath, e.ToString());
return false;
}
return true;
}
public bool PlayTrack()
{
if (waveOutDevice == null || waveOutDevice.PlaybackState == PlaybackState.Playing)
return false;
waveOutDevice.Play();
return true;
}
public bool StopTrack()
{
if (waveOutDevice == null || waveOutDevice.PlaybackState == PlaybackState.Stopped)
return false;
waveOutDevice.Stop();
mainOutputStream.CurrentTime = TimeSpan.Zero;
return true;
}
This loads and plays my test track fine, my issue is with the Stop() function. Firstly should I need to reset the CurrentTime property after calling Stop()? Currently it acts more like a pause button i.e. it resumes the track in the same place it was "stopped". If I do need to reset the CurrentTime I now have a problem where if I click stop, the track stops, but if I click play again afterwards I get a little leftover noise before the track starts again.
Looking at the source code of one of the samples all it does is call Stop().
In our use of naudio, we never stop the audio. Any stop-like functionality causes a silent waveform (zeroes) to be fed to the wave out. This was mainly due to instability in naudio when stopping and starting too frequently, but it also prevents the "leftover buffer" problem.

GWT code-splitting pattern for ClientBundle image resources

In my GWT large project, I have a ClientBundle for my image resources. I defined about 40 GIF files inside it. (size of each file is about 5KB)
Then I create a class with a static method to set the proper image to the obj that get as parameters:
public static void setImageFromId (String id,final Image img) {
//for 1.gif
if (id.equals("1")) {
GWT.runAsync(new RunAsyncCallback() {
#Override
public void onFailure(Throwable reason) {}
#Override
public void onSuccess() {
img.setResource(MyImages.INSTANCE.img1()); //MyImages is the ClientBundle
}
});
}
}
//for 2.gif
if (id.equals("2")) {
GWT.runAsync(new RunAsyncCallback() {
#Override
public void onFailure(Throwable reason) {}
#Override
public void onSuccess() {
img.setResource(MyImages.INSTANCE.img2()); //MyImages is the ClientBundle
}
});
}
//etc. for other images 3, 4, 5, ...
//...
}
I want to know is it good pattern for code-splitting? because if I don't do it all the 40 files will be cached to client browser in first call, but it is not necessary.
RGDS
So you're trying to avoid downloading each image when your page loads. That's good, if you don't know ahead of time whether every image will be needed.
But, what your code is doing is using code-splitting to only download the code to display your images when the image is needed, which as you can see, is only one line of code per image.
Try this code:
if (id.equals("1")) {
img.setSrc(MyImages.INSTANCE.img1().getUrl());
} else if (id.equals("2")) {
//.. and so on.
}
Your images will only be downloaded and displayed when the relevant image is needed. You can use Firebug or Chrome's Developer Tools to see when your images are being downloaded, they should only be requested when needed.
If you have any more questions or find that all your images are being downloaded on page load, let me know and I'll edit my answer again to help you out.