Updating handleEvent(e) to AWTEvent - java

The first snippet is my first try before I learned it was deprecated and attempted to switch to AWT in the second snippet
public boolean handleEvent (Event e) {
if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
try {
o.writeUTF((String) e.arg);
o.flush();
} catch (IOException ex) {
ex.printStackTrace();
listener.interrupt();
}
input.setText("");
return true;
} else if((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
if (listener != null)
listener.interrupt();
setVisible(false);
return true;
}
return super.handleEvent(e);
}
The next part I tried below changed it to AWT which is what I'm aiming for but this is when the "cannot be resolved or is not a field" errors came up.I tried processEvent(); but that gave me "cannot be resolved or is not a field" errors on each instance of "target" and "arg", also a "Cannot return a void result" on return super.processEvent(e);. Does anyone know a way I can update this?
public boolean handleEvent (AWTEvent e) {
if ((e.target == input) && (AWTEvent.RESERVED_ID_MAX == Event.ACTION_EVENT)) {
try {
o.writeUTF((String) e.arg);
o.flush();
} catch (IOException ex) {
ex.printStackTrace();
listener.interrupt();
}
input.setText("");
return true;
} else if((e.target == this) && (AWTEvent.RESERVED_ID_MAX == Event.WINDOW_DESTROY)) {
if (listener != null)
listener.interrupt();
setVisible(false);
return true;
}
return super.processEvent(e);
}

Related

(TXT File) Java GUI Login

I want to login from a text file called "members.txt" which using 2nd (username) and third (password) line with "/" delimiter. But when I run it, it seems they recognize all of text file's account in sequence. Please help. Here's my code.
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String s;
String bypassid = "guest";
String bypasspw = "guest";
String[] array;
boolean isLogin= false; // 포기
BufferedReader br = new BufferedReader(new FileReader("members.txt"));;
while((s=br.readLine())!=null) {
array=s.split("/");
if(txtID.getText().equals(array[1])&&txtPass.getText().equals(array[2])){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
break;
} else if(array.length != 0 && bypassid.equals(txtID.getText())&&bypasspw.equals(txtPass.getText())){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
break;
} else {
JOptionPane.showMessageDialog(null, "계정 정보를 다시 확인해주세요.");
}
}
br.close();
} catch (IOException e10) {
// TODO Auto-generated catch block
e10.printStackTrace();
}
}
});
Actually you are reading every line and if user/password doesn't match, you print error message in else {} block. You can just set boolean variable isLogin once and see if isLogin is false, print error message once outside loop. Below is the code snippet for that. Replace your actionPerformed method with code below
public void actionPerformed(ActionEvent e) {
try {
String s;
String bypassid = "guest";
String bypasspw = "guest";
String[] array;
boolean isLogin= false; // 포기
BufferedReader br = new BufferedReader(new FileReader("members.txt"));
while((s=br.readLine())!=null) {
array=s.split("/");
if(txtID.getText().equals(array[1])&&txtPass.getText().equals(array[2])){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
isLogin = true;
break;
} else if(array.length != 0 && bypassid.equals(txtID.getText())&&bypasspw.equals(txtPass.getText())){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
isLogin = true;
break;
}
}
if(!isLogin) {
JOptionPane.showMessageDialog(null, "계정 정보를 다시 확인해주세요.");
}
br.close();
} catch (IOException e10) {
// TODO Auto-generated catch block
e10.printStackTrace();
}
}
Just be careful about what #David Kroukamp mentioned in comment

Can't resume AudioTrack after pause

I am currently using AudioTrack in stream mode to play some prerecorded tracks. Play and stop mechanics work properly.However, when i hit pause and try to resume afterwards the buffer only reads -1, indicating that the EOF was reached.
I tried to mark and reset the Inputstream, like it's suggested in some posts but it didn't help.
public void pauseTrack() {
currentAudioTrack.pause();
isPaused = true;
}
public void resumeTrack() {
isPaused = false;
}
#Override public void run() {
try {
while (offset < audioFile.length()) {
if (isPaused)
continue;
currentAudioTrack.play();
int numberOfBytesRead = fileInputStream.read(audioData);
if (numberOfBytesRead != -1) {
currentAudioTrack.write(audioData, 0, numberOfBytesRead);
offset+=numberOfBytesRead;
}
else {
return;
}
}
Log.v("status", "finished reading");
} catch (IOException io) {
Log.v("Exception", "IOException found: " + io.getLocalizedMessage());
} catch (IllegalStateException ie) {
Log.v("Exception","IllegalStateException:" + ie.getLocalizedMessage());
}
}
What am i doing wrong?
Just to give some closure to the post, i ended up changing to the AudioTrack static mode. The change wasn't because of the pause situation, however it end up solving it. Since the buffer writing is done all in one take, it doesn't present the challenges of the stream mode.
Try this
public void pauseTrack()
{
currentAudioTrack.pause();
isPaused = true;
}
public void resumeTrack()
{
isPaused = false;
}
#Override public void run()
{
try {
while (offset < audioFile.length())
{
if(isPaused != true)
{
currentAudioTrack.play();
int numberOfBytesRead = fileInputStream.read(audioData);
if (numberOfBytesRead != -1) {
currentAudioTrack.write(audioData, 0, numberOfBytesRead);
offset+=numberOfBytesRead;
}
else {
return;
}
}
}
Log.v("status", "finished reading");
} catch (IOException io) {
Log.v("Exception", "IOException found: " + io.getLocalizedMessage());
} catch (IllegalStateException ie) {
Log.v("Exception","IllegalStateException:" + ie.getLocalizedMessage());
}
}
I used the skip() method, as below, to skip the offset which is recorded when pause is triggered. Works fine sofar.
public void play() {
try {
dis.skip(offset); //skip "offset * bufferSize" in the **dis** data input stream
while (((i = dis.read(music_chunk, 0 , 0)) > -1) && !isPaused) {
i = dis.read(music_chunk, 0, bufferSize);
track.write(music_chunk, 0, i); // track is the AudioTrack
position += bufferSize;
}
track.stop();
}
public void pause() {
track.pause();
offset = position ;
isPaused = true;
}
Please adjust the above code to your needs before running.
Thanks

Android doInBackground error

I am a beginner in android development and I get an error that I can not solve a few days ago with the doInBackground() method.
My error is at the end of my code, at
e2 = e11;
createInsecureRfcommSocketToServiceRecord = null;
this.sender = e2.getMessage();
createInsecureRfcommSocketToServiceRecord.close();
The error is
Unhandled exception:java.io.IO.EXCEPTION
If you have solutions , thank you in advance!
My code :
protected Object doInBackground(Object[] objArr) {
BluetoothSocket createInsecureRfcommSocketToServiceRecord;
IOException e;
Throwable th;
IButton a;
Boolean valueOf;
boolean z = true;
this.jobType = (JobType) objArr[0];
this.sender = (MainActivity) objArr[1];
this.device = (BluetoothDevice) objArr[2];
try {
createInsecureRfcommSocketToServiceRecord =
device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e2) {
Log.e("Bluetooth", e2.getMessage());
Log.e("Bluetooth", "trying fallback");
try {
createInsecureRfcommSocketToServiceRecord = (BluetoothSocket)
this.device.getClass().getMethod("createInsecureRfcommSocket", new Class[]{Integer.TYPE}).invoke(this.device, new Object[]{Integer.valueOf(1)});
} catch (Exception e3) {
Log.e("Bluetooth", e3.getMessage());
}
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e4) {
e2 = e4;
try {
this.error = e2.getMessage();
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e5) {
}
return null;
} catch (Throwable th2) {
th = th2;
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e6) {
}
throw th;
}
}
}
if (this.jobType == JobType.read) {
a = readDevice(createInsecureRfcommSocketToServiceRecord);
try {
createInsecureRfcommSocketToServiceRecord.close();
return a;
} catch (IOException e7) {
return a;
}
} else
if (this.jobType == JobType.stopMission) {
a = (IButton) objArr[3];
if (!(stopMission(createInsecureRfcommSocketToServiceRecord) &&
writeDevice(createInsecureRfcommSocketToServiceRecord, a))) {
z = false;
}
valueOf = Boolean.valueOf(z);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e8) {
return valueOf;
}
} else
if (this.jobType == JobType.startMission) {
boolean z2 = writeDevice(createInsecureRfcommSocketToServiceRecord, (IButton) objArr[3]) &&
startMission(createInsecureRfcommSocketToServiceRecord);
valueOf = Boolean.valueOf(z2);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e9) {
return valueOf;
}
} else {
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e10) {
}
return null;
}
} catch (IOException e11) {
e2 = e11;
createInsecureRfcommSocketToServiceRecord = null;
this.sender = e2.getMessage();
createInsecureRfcommSocketToServiceRecord.close();
return null;
} catch (Throwable th3) {
th = th3;
createInsecureRfcommSocketToServiceRecord = null;
createInsecureRfcommSocketToServiceRecord.close();
throw th;
}
return null;
}
close() also throws an IOException exception you need to handle. Additionally you should use a finally block for cleaning up and be careful not to provoke NullPointerExeptions by setting the variable to null before closing it.
You could improve your code like
try {
....
} catch (Exception e) {
....
} finally {
try {
createInsecureRfcommSocketToServiceRecord.close();
createInsecureRfcommSocketToServiceRecord = null;
} catch (IOException e) {
}
}
I'm modify my code with this but i'm a java.lang.NullPointerException...
The fonction doInBackground() is very difficult...
Thank's for your help !
My code modify
protected Object doInBackground(Object[] objArr) {
BluetoothSocket createInsecureRfcommSocketToServiceRecord = null;
IOException e;
Throwable th;
IButton a;
Boolean valueOf;
boolean z = true;
this.jobType = (JobType) objArr[0];
this.sender = (MainActivity) objArr[1];
this.device = (BluetoothDevice) objArr[2];
try {
createInsecureRfcommSocketToServiceRecord =
device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e2) {
Log.e("Bluetooth", e2.getMessage());
Log.e("Bluetooth", "trying fallback");
try {
createInsecureRfcommSocketToServiceRecord = (BluetoothSocket)
this.device.getClass().getMethod("createInsecureRfcommSocket", new Class[]{Integer.TYPE}).invoke(this.device, new Object[]{Integer.valueOf(1)});
} catch (Exception e3) {
Log.e("Bluetooth", e3.getMessage());
}
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e4) {
e2 = e4;
try {
this.error = e2.getMessage();
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e5) {
}
return null;
} catch (Throwable th2) {
th = th2;
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e6) {
}
throw th;
}
}
}
if (this.jobType == JobType.read) {
a = readDevice(createInsecureRfcommSocketToServiceRecord);
try {
createInsecureRfcommSocketToServiceRecord.close();
return a;
} catch (IOException e7) {
return a;
}
} else if (this.jobType == JobType.stopMission) {
a = (IButton) objArr[3];
if (!(stopMission(createInsecureRfcommSocketToServiceRecord) &&
writeDevice(createInsecureRfcommSocketToServiceRecord, a))) {
z = false;
}
valueOf = Boolean.valueOf(z);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e8) {
return valueOf;
}
} else if (this.jobType == JobType.startMission) {
boolean z2 = writeDevice(createInsecureRfcommSocketToServiceRecord, (IButton) objArr[3]) &&
startMission(createInsecureRfcommSocketToServiceRecord);
valueOf = Boolean.valueOf(z2);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e9) {
return valueOf;
}
} else {
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e10) {
}
return null;
}
} catch (IOException e11) {
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e1) {
e1.printStackTrace();
}
createInsecureRfcommSocketToServiceRecord = null;
return null;
} catch (Throwable th3) {
th = th3;
} finally {
try {
createInsecureRfcommSocketToServiceRecord.close();
createInsecureRfcommSocketToServiceRecord = null;
} catch (IOException e2) {
}
}
return null;
}

GCMInternet service.java mBuilder setColor error in java

this line-> mBuilder.setColor(iconColor);
showing error as method setColor(int) is undefined for the type NotificationCompat.Builder mBuilder
here is my code
private void setNotificationIconColor(String color, NotificationCompat.Builder mBuilder, String localIconColor)
{
int iconColor = 0;
if (color != null) {`enter code here`
try {
iconColor = Color.parseColor(color);
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "couldn't parse color from android options");
}
}
else if (localIconColor != null) {
try {
iconColor = Color.parseColor(localIconColor);
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "couldn't parse color from android options");
}
}
if (iconColor != 0) {
mBuilder.setColor(iconColor);
}
}
If you are using it for push notification as Phonegap/Cordova project just do below steps update code before Emulate:
private void setNotificationIconColor(String color, NotificationCompat.Builder mBuilder, String localIconColor)
{
int iconColor = 0;
if (color != null) {`enter code here`
try {
iconColor = Color.parseColor(color);
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "couldn't parse color from android options");
}
}
else if (localIconColor != null) {
try {
iconColor = Color.parseColor(localIconColor);
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "couldn't parse color from android options");
}
}
if (iconColor != 0) {
//mBuilder.setColor(iconColor);
}
}

Buttons not working at first and last index?

I am working on an application in which have two navigation button namely 'previous and next' which on tap load stories respectively. When i tap these buttons gently they work fine button when i tap next button to the last index continuously without any break then the previous button does not work or similarly when i start tapping previous button to the very first index i am unable to move forward.
Remember this only happens at the extreme cases, onClick is not called, don't know why.
My code is as follows, please help me out. Thanks in advance.
this the code of onClick, which works fine in all cases except the extreme cases, when buttons are not tapped gently.
public void onClick(View v) {
if (visible == true) {
Log.e("visible", "true");
return;
}
visible = true;
try {
Log.e("Now", "On Click");
pDialog = new ProgressDialog(StoriesListController.this);
pDialog.setIndeterminate(true);
pDialog.setIcon(R.drawable.icon_small);
pDialog.setCancelable(true);
if (isFavoriteList == true) {
pDialog.setMessage("Loading favorites...");
} else {
pDialog.setMessage("Loading data...");
}
pDialog.setTitle("Please wait");
pDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
if (cancelableHeavyWorker != null) {
cancelableHeavyWorker.setHandler(null);
}
finish();
}
});
pDialog.show();
if (v == next) {
if (ind < items.size() - 1) {
ind++;
loadAndShowNextActivity();
}
} else if (v == previous) {
if (ind > 0) {
ind--;
loadAndShowNextActivity();
}
}
// realeaseMemoryIfneededofStory(ind);
} catch (Exception e) {
Log.e("Error", "--.OnClink Message" + e.toString());
e.printStackTrace();
}
}
Moreover, the boolean variable "visible" is being set to false in the callback function.
The Code of Call Back Function is as follows:
private void fetchTopStoryDetailCallback(Object resultVector) {
System.out.println("fetchTopStoryDetailCallback");
try {
Vector<?> v = (Vector<?>) resultVector;
boolean completedOrFailed = ((Boolean) v.elementAt(0)).booleanValue();
if (completedOrFailed == true) {
boolean slideshow = ((Boolean) v.elementAt(1)).booleanValue();
Object result = v.elementAt(2);
String res[] = (String[]) result;
if (slideshow) {
if (Utils.topStorySlidesArrayList != null && Utils.topStorySlidesArrayList.size() > 0) {
Intent articleActivityIntent = new Intent(this, SlideShowActivity.class);
articleActivityIntent.putExtra("storyData", (String[]) result);
articleActivityIntent.putExtra("back", back);
articleActivityIntent.putStringArrayListExtra("sid", slideids);
// articleActivityIntent.putExtra("contentType", )
articleActivityIntent.putExtra("addkey", ADDS_KEY);
showActivityInContoller(articleActivityIntent);
hidePrgressgingDailog();
} else {
hidePrgressgingDailog();
this.closeActivity = true;
showMessage("Error", "This story encounter an error while opening. Check your Internet Connection and try later");
}
} else {
if (res[3] != null && (!(res[3].equalsIgnoreCase("null")) && (!res[3].equals("")))) {
Intent slideshowActivtyIntent = new Intent(this, ArticleActivity.class);
slideshowActivtyIntent.putExtra("storyData", (String[]) result);
slideshowActivtyIntent.putExtra("back", back);
slideshowActivtyIntent.putExtra("addkey", ADDS_KEY);
showActivityInContoller(slideshowActivtyIntent);
hidePrgressgingDailog();
} else {
hidePrgressgingDailog();
this.closeActivity = true;
showMessage("Error", "This story encounter an error while opening. Check your Internet Connection and try later");
}
}
} else {
showMessage("Error", "This story encounter an error while opening. Check your Internet Connection and try later");
hidePrgressgingDailog();
}
} catch (Exception e) {
Log.e("StoriesController", "Message = " + e.toString());
e.printStackTrace();
}
finally {visible = false; }
}
this is how visiblity of the buttons is set...!!!!
private void adjustButtonsVisibility() {
try {
if (items.size() == 1) {
next.setEnabled(false);
next.setImageResource(R.drawable.navigator_next_disable);
previous.setEnabled(false);
previous.setImageResource(R.drawable.navigator_previous_disable);
//hidePrgressgingDailog();
return;
}
if (ind == 0) {
previous.setEnabled(false);
next.setEnabled(true);
previous.setImageResource(R.drawable.navigator_previous_disable);
next.setImageResource(R.drawable.story_next_arrow);
hidePrgressgingDailog();
} else if (ind > 0 && ind < items.size() - 1) {
previous.setEnabled(true);
next.setEnabled(true);
previous.setImageResource(R.drawable.story_previous_arrow);
next.setImageResource(R.drawable.story_next_arrow);
}
if (ind == items.size() - 1) {
previous.setEnabled(true);
next.setEnabled(false);
previous.setImageResource(R.drawable.story_previous_arrow);
next.setImageResource(R.drawable.navigator_next_disable);
hidePrgressgingDailog();
}
} catch (Exception e) {
Log.e("Error", "--,adjustButtonsVisibility Message = " + e);
e.printStackTrace();
}
}
Do this
if (ind == 0) {
previous.setEnabled(false);
previous.setImageResource(R.drawable.navigator_previous_disable);
next.setImageResource(R.drawable.story_next_arrow);
hidePrgressgingDailog();
}
else if (ind > 0 && ind < items.size() - 1) {
previous.setEnabled(true);
next.setEnabled(true);
previous.setImageResource(R.drawable.story_previous_arrow);
next.setImageResource(R.drawable.story_next_arrow);
}
else if (ind == items.size() - 1) {
previous.setEnabled(true);
next.setEnabled(false);
previous.setImageResource(R.drawable.story_previous_arrow);
next.setImageResource(R.drawable.navigator_next_disable);
hidePrgressgingDailog();
}

Categories

Resources