I'm learning java and i have found a great tutorial on youtube, when trying to addapt it for my needs, i came to this problem:
I need to turn a string into a double, do some math, and fill a TextView with the result.
Also, it would be nice, if i could get that data from the firebase database (which my code does in another activity).
Now, i've abandoned the ideea of getting the data from the dtb because the app crashes everytime i open the activity, after i added the try, catch, finally, it doenst crash, but the activity is blank and no error is being displayed.
Tried eliminating row by row, to see where the problem is, but the app still crashes, even if one row is being left in.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText sup = findViewById(R.id.etSup);
EditText emi = findViewById(R.id.etEmi);
EditText ver = findViewById(R.id.etVer);
EditText abs = findViewById(R.id.etAbs);
TextView ResultTextView = findViewById(R.id.tvResult);
TextView Car = findViewById(R.id.tvCar);
Double dsup = Double.parseDouble(sup.getText().toString());
Double demi = Double.parseDouble(emi.getText().toString());
Double dver = Double.parseDouble(ver.getText().toString());
Double dabs = Double.parseDouble(abs.getText().toString());
Double CE = dsup * demi;
ResultTextView.setText("Total emissions are " + CE);
Double PS = dver * dabs;
Double Total = CE - PS;
Car.setText("Emission balance is " + Total);
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
No error messages have been seen
Try putting the entirety of the onClick() method in a try/catch block. By the time a parseDouble() method throws an exception, you are no longer in the onCreate() method because all you are doing in onCreate() is registering a listener. The onClick() method runs later on
I'm not sure what exception you might be getting from your parseDouble calls (could be many things, nullpointer perhaps?) but this change will allow you to find out.
In case I'm not explaining myself very well:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
// do things
} catch (Throwable e) {
e.printStackTrace();
throw e;
}
}
}
Edit: Changed catching 'Exception' to 'Throwable' just to be sure we don't miss anything (as a side note, you really shouldn't catch a Throwable except for debugging, which is why I've thrown it on again)
Related
I've tried to set the text on SwitchCompat, but it doesn't work. It only work for the first time. But when you tried to change the text (eg. when button is clicked), it doesn't work.
For example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SwitchCompat switchCompat = (SwitchCompat)findViewById(R.id.switch_test);
switchCompat.setTextOn("Yes");
switchCompat.setTextOff("No");
switchCompat.setShowText(true);
Button buttonTest = (Button)findViewById(R.id.button_test);
buttonTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switchCompat.setTextOn("YOO");
switchCompat.setTextOff("NAH");
//switchCompat.requestLayout(); //tried to this but has no effect
//switchCompat.invalidate(); //tried to this but has no effect
}
});
}
You will see that the text stays as Yes and No. I've tried to call requestLayout() and invalidate() with no success. Any idea?
The problem is, that SwitchCompat is not designed with that case in mind. It has private fields mOnLayout and mOffLayout, which are computed once and not recomputed later when text is being changed.
So, you have to explicitly null them out in order text change to initiate those layouts to be recreated.
buttonTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Field mOnLayout = SwitchCompat.class.getDeclaredField("mOnLayout");
Field mOffLayout = SwitchCompat.class.getDeclaredField("mOffLayout");
mOnLayout.setAccessible(true);
mOffLayout.setAccessible(true);
mOnLayout.set(switchCompat, null);
mOffLayout.set(switchCompat, null);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
switchCompat.setTextOn("YOO");
switchCompat.setTextOff("NAH");
}
});
Result:
I have this code in one of the java file of my application.
public class Board_Play1 extends Activity {
int d,a=0,b=0,turn=2;
Random random = new Random();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.board_play1);
while(a!=100 && b!=100)
{
if(turn%2==0)
{
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
d=random.nextInt(6)+1;
EditText diceno = (EditText) findViewById(R.id.editText1);
diceno.setText(String.valueOf(d));
}
});
}turn++;
}
}
}
I come to this java file from another java file. All the problem I get is when this file doesn't have any while loop as in code it runs fine. But with including the while loop on navigating to this layout turns screen black and no further process can be done. If we press back button we have a pop out message saying Your application isn't responding. Do You want to close? Yes No.
Why is that happening. All things I included in while loop are perfect. What is causing for this problem?
I think you have an infinite loop. the condition in your while loop is always true because a and b values are never incremented.
And the reason why you're seeing black screen is that this infinite loop is blocking the Main UI Thread.
Seems that this is an infinite loop to me.
int a=0, b=0;
These values never change in your code and you are using them in your while loop's conditional.
Try something like:
while(a!=100 && b!=100)
{
if(turn%2==0)
{
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
d=random.nextInt(6)+1;
EditText diceno = (EditText) findViewById(R.id.editText1);
diceno.setText(String.valueOf(d));
}
});
}
turn++;
// a = somevalue based on what you're trying to do.
// b = somevalue based on what you're trying to do.
}
Edit: I put this pB = (ProgressBar) findViewById(R.id.progressBar); in the onPreExecute(). It works, everything works. But is this a good solution? I know that in my main thread the progress bar was !null. But before this findViewById, my asynctask just couldn't find the progress bar I wanted, even though I thought I was passing it in .execute().
This is my first experience with asynctask. I have a progress bar that I want to count up, but I keep getting a NullPointerException.
The log read "Progress Update: 1" but then the VM shuts down. So I know an integer is getting passed, but I can't figure out why it can't find the progress bar(pB). I've tried to setProgress(0) in the main thread, in the onPreExecute(), but the machine hated it.
It runs the rest of the for loop in doInBackground(), and logs the "Percent Progress: " and "Sleeping " but won't log any more "Progress Update: ".
The NullPointerException is at line 31, which is pB.setProgress(progress[0]);
#Override
protected void onProgressUpdate(Integer...progress){
Log.d(LOG_TAG, "Progress Update: "+progress[0].toString());
super.onProgressUpdate(progress);
if(progress[0]!=null){
pB.setProgress(progress[0]);
}
}
#Override
protected Boolean doInBackground(Integer...numSeconds){
Log.d(LOG_TAG, "doInBackground: "+numSeconds[0]);
try {
int totalSecs = numSeconds[0].intValue();
Log.d(LOG_TAG, "Total SECS: "+totalSecs);
for(int i = 1; i <= totalSecs; i++){
Log.d(LOG_TAG, "Sleeping "+i);
Thread.sleep(1000);
float percentage = ((float)i/(float)totalSecs)*100;
Log.d(LOG_TAG, "Percentage Progress: "+ percentage);
Float progress = Float.valueOf(percentage);
publishProgress(new Float(progress).intValue());
}
} catch (InterruptedException e){
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result){
Log.d(LOG_TAG, "Post Execute "+ result);
super.onPostExecute(result);
pB.setProgress(0);
}
Here's some from my main thread:
To initialize the progress bar:
timer = (ProgressBar) findViewById(R.id.progressBar);
timer.setProgress(0);
To execute the asynctask:
OnClickListener startBubbles = new OnClickListener(){
#Override
public void onClick(View arg0) {
new ProgBar(timer).execute(100);
setAll();
}
};
The constructor:
public ProgBar(ProgressBar pB){
Log.d(LOG_TAG, "Constructor");
}
Null Pointer Exception occurs when you are accessing value , which is not yet been initaialized.
So for ex. char a[10];
System.out.println(a[3]);
So there must be variable within your code which you are accessing without initialising it. I thing numSecond but I am not sure.
Sorry thats all I know
I'm trying to use jsoup to display temperature of Boston from a website as a toast message in an android app. My Java program looks like this:
public static void showWeather() throws IOException
{
Document doc = Jsoup.connect("http://www.wunderground.com/US/ma/boston.html?MR=1").get();
Elements languages = doc.select("#tempActual span.b ");
for(Element langElement: languages)
{
//System.out.println(" The temperature in Boston: "+langElement.text()+ " F");
}
}
The Java program works Okay and prints the temperature of Boston to the screen. I want to use this method to try to display the temperature as a toast in a simple android app, but when I try to run to method (without the print statement of course) in the onCreate method in my android activity, the program closes automatically. Here's my onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addKeyListener();
try {
showWeather();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anybody please tell how to run this java program in my android activity? I don't know how to treat the try/catch clause properly. I tried put toast in the catch clause but to no avail. Please help.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Reference:
http://developer.android.com/reference/android/os/AsyncTask.html
Usage
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
I'm trying to make an app that accepts an input and automatically changes it to an int. However, when it tries to obtain an int, the app automatically stops. Below is the full code...
public class MainActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculateTip);
calculate.setOnClickListener(this);
}//end onCreate
public void onClick(View v) {
EditText money = (EditText)findViewById(R.id.bill);
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}//end onClick
}//end MainActivity
I suspect that the application is stopping because the value you are trying to parse is not really an integer. You should throw that code into a try catch.
ie:
public void onClick(View v) {
EditText money;
try
{
money = (EditText)findViewById(R.id.bill);
// This check makes sure that the EditText is returning the correct object.
if(money != null)
{
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}
}
catch(NumberFormatException e)
{
// If we get in here that means the inserted value was not an Integer. So do something.
//ie:
money.setText("Please enter a value amount" );
}
}//end onClick
Regardless, you should have this code in a try catch to maintain data integrity.
Hopefully this helps!
Cheers.
Are you sure that the Object is an instance of EditText and that it isn't null?