Having difficulties with making my processing PrintWriter and BufferedReader work - processing

So, i was able to make my code run, however i am having trouble with the highscore code. I am unable to use the bufferedreader and printwriter functions because for some reason that i am not understanding, they are not running. I want the program to compare the score to the highscore, and if the score is larger than the highscore, the highscore will be updated on a txt file. the reason the txt file is necessary is due to the fact that once the program closes, i need a method as to check for the previous highscore. I am really new to using processing and writing and reading txt files using programs, and none of the other sites and forums ive looked at have helped because they do not write the highscore variable onto a txt file. Please help, im ready to break my computer.
EM1.score = the score accumulated over the course of the program.
class High_Score {
int highscore = 0;
PrintWriter output; //imports the writer
BufferedReader reader; //imports the reader
int state = 0; //sets the varoable for the keyboard
void scoring() {
int score = EM1.score;
if (score > highscore) {
highscore = score;
}
textSize(30);
text("Your score is "+ score, 150, height/4);
text("The current highscore is "+highscore+".", 75, height/2);
text("Try to beat it.", 200, 450);
textSize(12);
text("Press esc to exit this page.", 225, 550);
}
void reader() {
importHS();
updateHS();
}
void updateHS() {
int score = EM1.score;
output = createWriter("highscore.txt"); //creates the file that will be
if (highscore < score) {
highscore = score;
output.print(highscore);
output.close();
}
}
void importHS() {
reader = createReader("highscore.txt"); //reads the current highscore
if (reader == null) {
highscore = 0;
return;
}
String line;
try {
line = reader.readLine();
}
catch (IOException e) {
e.printStackTrace();
line = null;
}
if (line != null) {
highscore = int(line);
println(highscore);
}
try {
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
void type() { //allows the screen to close is esc is pressed on the keyboard
state = key;
if (key == ESC) {
exit();
}
}
}

You're almost there. There are only a couple of things I see slightly off:
you're not calling flush() on the writer to writes the remaining data to the file
checking if (highscore < score) in updateHS() is preventing the write: you don't really need this anyway since scoring() already checks if the current score is a highscore and updates accordingly.
Here's most of your code tweaked to write/read from disk:
EM1Class EM1 = new EM1Class();
High_Score hs = new High_Score();
void setup(){
size(800,600);
EM1.score = 500;
hs.reader();
}
void draw(){
background(0);
hs.scoring();
hs.updateHS();
}
void keyPressed(){
if(keyCode == UP) EM1.score += 10;
if(keyCode == DOWN) EM1.score -= 10;
}
class EM1Class{
int score;
}
class High_Score {
int highscore = 0;
PrintWriter output; //imports the writer
BufferedReader reader; //imports the reader
int state = 0; //sets the varoable for the keyboard
void scoring() {
int score = EM1.score;
if (score > highscore) {
highscore = score;
}
textSize(30);
text("Your score is "+ score, 150, height/4);
text("The current highscore is "+highscore+".", 75, height/2);
text("Try to beat it.", 200, 450);
textSize(12);
text("Press esc to exit this page.", 225, 550);
}
void reader() {
importHS();
updateHS();
}
void updateHS() {
int score = EM1.score;
output = createWriter("highscore.txt"); //creates the file that will be
output.print(highscore);
output.flush();
output.close();
}
void importHS() {
reader = createReader("highscore.txt"); //reads the current highscore
if (reader == null) {
highscore = 0;
return;
}
String line;
try {
line = reader.readLine();
}
catch (IOException e) {
e.printStackTrace();
line = null;
}
if (line != null) {
highscore = int(line);
println(highscore);
}
try {
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
void type() { //allows the screen to close is esc is pressed on the keyboard
state = key;
if (key == ESC) {
exit();
}
}
}
There'a placeholder EM1Class there just so a sketch could compile.
I'm not sure the High_Score class should know about EM1 directly.
You might want to refactor the code a bit and make sure it's not as tightly coupled as it currently is since you're using classes anyway.
Also check out a Java style guide: it will help to write code that is consistent and neatly organised. It will surely pay off building the discipline to do so on the long run, but also immediately as you're code will be easier to scan/quickly read and deduce it's flow.
Another option is to use the Processing built-in XML and JSON functions which will make be easier to parse (and also have handy load/save functions).
int score = 0;
int highScore;
void setup(){
loadHighScore();
}
void draw(){
background(0);
text("score:"+score+"\nhighScore:"+highScore+"\n\nuse UP/DOWN\narrows",10,15);
}
void keyPressed(){
if(keyCode == UP) score += 10;
if(keyCode == DOWN) score -= 10;
if(score > highScore) highScore = score;
}
void loadHighScore(){
try{
JSONObject jsonScore = loadJSONObject("highScore.json");
highScore = jsonScore.getInt("highScore");
}catch(Exception e){
println("error loading/parsing highScore.json");
e.printStackTrace();
}
}
void saveHighScore(){
JSONObject jsonScore = new JSONObject();
jsonScore.setInt("highScore",highScore);
saveJSONObject(jsonScore,"highScore.json");
}
//save on close
void exit(){
saveHighScore();
super.exit();
}

Related

Getting issue while retrieve location with different location request mode

For retrieve location i have used GoogleAPIClient with FusedLocationProvider API.
These functions are in onCreate() method.
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
gpsChecker();
Full Code
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void gpsChecker() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
AddVisitActivity.this, 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
For run time permissions i did this.
protected void startLocationUpdates() {
if (ActivityCompat.shouldShowRequestPermissionRationale
(AddVisitActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
Snackbar.make(findViewById(android.R.id.content),
"Please Grant Permissions",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(AddVisitActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AddVisitActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, AddVisitActivity.this);
Log.d(TAG, "Location update started ...: ");
}
}
}).show();
} else {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ...: ");
}
}
}
For checking if the GPS enabled or not in setting screen using gpsChecker() with request code 1000 and in onActivityResult() i have done this.
if (requestCode == 1000) {
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
finish();
break;
}
}
While i execute this code in some devices its working and in some device the location request automatically set to Device Only or Battery Saving though i have set mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Note : Mi Note 4, Vivo V9 Pro, Mi Note 5 Pro and some other device getting the issue
So what should i need to change in my code so will it work proper with the High Accuracy?
Finally solved by changing
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
to
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
and change
private static final long INTERVAL = 1000 * 60 * 60;
private static final long FASTEST_INTERVAL = 1000 * 5;
interval time to 30 minutes and fastest interval to 5 seconds means once get location in 5 seconds after then new location will be get in 30 minutes.
Try this solutin with GPS Provider and make sure that your GPS service is ON.
static final int LOCATION_INTERVAL = 1000;
static final float LOCATION_DISTANCE = 10f;
//put this in onCreate();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider, LOCATION_INTERVAL, LOCATION_DISTANCE, this);
if (location != null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
//put this LocationListener after onCreate();
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(String.format("%f, %f", location.getLatitude(), location.getLongitude()), "");
Log.e("Location available", "Location available");
locationManager.removeUpdates(mLocationListener);
} else {
Log.e("Location is null", "Location is null");
}
current_latitude = location.getLatitude();
current_longitude = location.getLongitude();
/* LatLng latLng = new LatLng(current_latitude, current_longitude);
points.add(latLng);
redrawLine();*/
Log.e("current_latitude", String.valueOf(current_latitude));
Log.e("current_longitude", String.valueOf(current_longitude));
if (location.hasSpeed()) {
//progressBarCircularIndeterminate.setVisibility(View.GONE);
String speed = String.format(Locale.ENGLISH, "%.0f", location.getSpeed() * 3.6) + "km/h";
SpannableString s = new SpannableString(speed);
s.setSpan(new RelativeSizeSpan(0.25f), s.length() - 4, s.length(), 0);
txt_current_speed.setText(s);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};

MediaFormat options, the KEY_ROTATION is not work

The current image is encoded and stored in the output buffer as it is.
However, Samsung (Galaxy S6(Nouga), 7(Nouga), 8(Nouga)) KEY_ROTATION option works well,
This option does not work on the Google reference phone (Pixel 2 XL -> Oreo, Nexus 5 -> Lollipop).
In other words, while the KEY_ROTATION option works well on the Samsung device, the value output to the output buffer is rotated,
This option does not work on Google reference phones.
The surface created by encoderSurface () serves as an input buffer
Check the output buffer through onOutputBufferAvailable of MediaCodec.Callback.
Anyone who knows the reason needs help.
Here is the code I wrote.
private final MediaCodec.Callback _mediaCodecCallback = new MediaCodec.Callback() {
#Override
public void finalize(){
}
#Override
public void onInputBufferAvailable(#NonNull MediaCodec mediaCodec, int i) {
}
#Override
public void onOutputBufferAvailable(#NonNull MediaCodec mediaCodec, int i, #NonNull MediaCodec.BufferInfo bufferInfo) {
ByteBuffer buffer = mediaCodec.getOutputBuffer(i);
byte[] outData = new byte[bufferInfo.size];
buffer.get(outData);
mediaCodec.releaseOutputBuffer(i, false);
switch (bufferInfo.flags) {
case MediaCodec.BUFFER_FLAG_CODEC_CONFIG:
if(DEBUG_LOG) {
Log.v(TAG, "CONFIG FRAME");
}
_configFrame = new byte[bufferInfo.size];
System.arraycopy(outData, 0, _configFrame, 0, outData.length);
break;
case MediaCodec.BUFFER_FLAG_KEY_FRAME:
// I Frame;
if(DEBUG_LOG) {
Log.v(TAG, "I FRAME" +
", SIZE = " + bufferInfo.size + ", " + currentDateandTime);
}
try {
_outputFrame.reset();
_outputFrame.write(_configFrame);
_outputFrame.write(outData);
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
// P Frame;
if(DEBUG_LOG) {
Log.v(TAG, "P FRAME" +
", SIZE = " + bufferInfo.size);
}
break;
}
}
//
public boolean initialize(int width,int height) {
try {
_mediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
} catch (IOException e) {
e.printStackTrace();
return false;
}
MediaCodecInfo codec = selectCodec(MIME_TYPE);
if (codec == null) {
return false;
}
MediaCodecInfo.CodecCapabilities cap = codec.getCapabilitiesForType(MIME_TYPE);
MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRateInfo.getInstance().getBitRate()); // 300000
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
mediaFormat.setInteger(MediaFormat.KEY_ROTATION, 90);
// in under API 21, not use MediaFormat.KEY_ROTATION, but use "rotation-degrees"
// This does not work on a Google reference phone.
_mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
_surface = _mediaCodec.createInputSurface();
_mediaCodec.setCallback(_mediaCodecCallback);
_mediaCodec.start();
Log.d(TAG,"Encoder Start SUCCESS");
return true;
}
public Surface encoderSurface() {
//Return the value of this function and use it as the input surface.
return _surface;
}
please Help me ..

Update Vaadin Progressbar with push asynchronously

I have a question when calculating the hash of files eg: md5, sha1, sha256 setting the progress in the progressBar through the asynchronous process
Thanks to Alejandro Duarte who shows a very practical example
https://github.com/newUserRepo/testbar/blob/issueBar/vaadin-upload/src/main/java/com/example/vaadinupload/ProcessingService.java#L44
the only way I can get it to work is that in method line 75, I put 4 milliseconds to process the task and the bar is updated, but it is too slow.
Yes, I do not sleep the Thread the application does not do the push correctly, and the changes are not reflected correctly to the client.
Another way that actually worked was with the Runnable interface and execute the heavy task in the run() method
#Override
public void run() {
calcularHash();
}
public void calcularHash() {
System.out.println("Path tmp archivo: " +
tmpPath.toFile().getAbsolutePath());
for(int f=0; f<hashType.size(); f++) {
try (InputStream bis = new
BufferedInputStream(Files.newInputStream(tmpPath))) {
t.initTime();
byte[] buffer = new byte[1024];
MessageDigest messageDigest =
MessageDigest.getInstance(hashType.get(f));
int dataRead = 0;
long largo = tmpPath.toFile().length();
Long acum = 0L;
while ((dataRead = bis.read(buffer)) != -1) {
messageDigest.update(buffer, 0, dataRead);
acum += dataRead;
Float per = ((float) acum / largo);
bar.setValue(per);
System.out.println(per * 100);
//textFieldPercent.setValue(Types.formatPercentaje(per *
100));
}
final byte[] bytesDigest = messageDigest.digest();
final StringBuilder sb = new StringBuilder();
for (int c = 0; c < bytesDigest.length; c++) {
sb.append(Integer.toString((bytesDigest[c] & 0xFF) + 0x100,
16).substring(1));
}
final String hashObtenido = sb.toString();
t.finishTime();
final String totalTime = t.getFinalTimeSec() + "seg " +
t.getFinalTimeMs() + "ms";
final String large = Types.getLargeFileFormat(largo);
System.out.println(hashObtenido);
ui.access(() -> {
checksumTransactions.initData(messageDigest.getAlgorithm(),
sb.toString(),large, totalTime);
});
//Files.delete(tmpPath); //fixme borrar desde el grid o UI
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
In the present picture I use a simple public void run () and the Progressbar is updated well
but we know that the application may have memory leaks and is not a good practice, the ideal would be to know how to execute that Background thread
I still do not know the best way to achieve this :$

JTextArea Do not scrollRectToVisible after Re-set Text

I encounter a strange issue.
The scenario is that I need to replace a keyword in JTextArea with another word.
I have two buttons, one is to find the keyword, and the other is to replace the keyword.
For both buttons, I add the mouse listener and implement function mouseClicked. At current stage I can highlight the found keyword and scroll to the keyword position. But when dealing with replace button, after re-setting text, the JTextArea always scrolls down to the bottom, but I want to keep the position where the replacement happens, what should I do? Below is my code snippet, but it doesn't work.
replaceBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
String keyword = jKeyword.getText();
if (keyword.length() == 0)
return;
String text = jTextArea.getText();
pos = text.indexOf(keyword, 0);
if (pos == -1) {
pos = 0;
JOptionPane.showMessageDialog(null, "can not find " + keyword);
return;
}
jTextArea.setText(text.replaceFirst(keyword, jReplaceKW.getText()));
//jTextArea.revalidate();
//scroll to first keyword occurrence
try {
Rectangle rectangle = jTextArea.modelToView(pos);
jTextArea.scrollRectToVisible(rectangle);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
I found a workaround: set text in function mousePressed then scroll in function mouseReleased.
I suspect the text has to be represented in the GUI before the component can figure out the scroll dimension? Not sure.
replaceBtn.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
String keyword = jKeyword.getText();
if (keyword.length() == 0)
return;
String text = jTextArea.getText();
pos = text.indexOf(keyword, 0);
if (pos == -1) {
pos = 0;
JOptionPane.showMessageDialog(null, "can not find " + keyword);
return;
}
jTextArea.setText(text.replaceFirst(keyword, jReplaceKW.getText()));
}
#Override
public void mouseReleased(MouseEvent e) {
//scroll to first keyword occurrence
try {
Rectangle rectangle = jTextArea.modelToView(pos);
jTextArea.scrollRectToVisible(rectangle);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});

Adding animation to a button in BlackBerry

I want to use animation on a Button that I created in my BlackBerry App. The animation works fine the first time when I click the button. On first click, the button starts animation (blinking). On second click the blinking stops. However, when I click the button again (third time), the blinking should start again. However, I get an error:
App Error 104 Uncaught: IllegalStateException
The code for creating the Button and adding animation is as follows:
final Bitmap image000 = Bitmap.getBitmapResource("panic.png");
final Bitmap image001 = Bitmap.getBitmapResource("panicon.png");
final Timer animationTimer = new Timer();
final BitmapField animationField = new BitmapField(image000,BitmapField.FOCUSABLE){
protected boolean navigationClick(int status, int time)
{
if(flag){
animationTask.cancel();
flag=false;
}else{
animationTimer.scheduleAtFixedRate(animationTask, 0, 100);
flag=true;
}
return true;
}
};
animationTask = new TimerTask() {
public void run() {
if(counter == 0){
animationField.setBitmap(image000);
}
if(counter == 1){
animationField.setBitmap(image001);
counter = -1;
}
counter++;
}
};
add(animationField);
EDIT: I debugged my code and the error occurs in the loop that starts the thread. Cancelling the thread seems fine. I am lost what is the issue. Please guide.
try this -
TimerTask animationTask;
BitmapField animationField;
final Bitmap image000 = Bitmap.getBitmapResource("panic.png");
final Bitmap image001 = Bitmap.getBitmapResource("panicon.png");
final Timer animationTimer = new Timer();
animationField = new BitmapField(image000,BitmapField.FOCUSABLE){
protected boolean navigationClick(int status, int time)
{
if(flag){
animationTask.cancel();
flag=false;
}else{
animationTask = new TimerTask() {
public void run() {
if(counter == 0){
animationField.setBitmap(image000);
}
if(counter == 1){
animationField.setBitmap(image001);
counter = -1;
}
counter++;
}
};
animationTask.run();
animationTimer.scheduleAtFixedRate(animationTask, 0, 100);
flag=true;
}
return true;
}
};
animationTask = new TimerTask() {
public void run() {
if(counter == 0){
animationField.setBitmap(image000);
}
if(counter == 1){
animationField.setBitmap(image001);
counter = -1;
}
counter++;
}
};
add(animationField);

Resources