I am a beginner Android developer and I have a runtime error in my code: when I want to run it in a emulator or a device it show "force close" massage. My log is here:
http://upir.ir/934/1_5e07a.jpg
My Java code:
public class Third extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
public void dialog(){
final Dialog dialog = new Dialog(Third.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("واحد عدد وارد شده را انتخاب کنید");
dialog.show();
RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.rg);
final RadioButton rb1 = (RadioButton) dialog.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton) dialog.findViewById(R.id.rb2);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if(rb1.isChecked()) {
dialog.dismiss();
Button t = (Button)findViewById(R.id.btn5);
t.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EditText ft1 = (EditText)findViewById(R.id.f3);
TextView foot = (TextView)findViewById(R.id.foot);
TextView mile = (TextView)findViewById(R.id.mile);
TextView inch = (TextView)findViewById(R.id.inch);
TextView yard = (TextView)findViewById(R.id.yard);
TextView mm = (TextView)findViewById(R.id.millymeter);
TextView dm = (TextView)findViewById(R.id.decimeter);
TextView mim = (TextView)findViewById(R.id.micrometer);
TextView nm = (TextView)findViewById(R.id.nanometer);
TextView hand = (TextView)findViewById(R.id.hand);
TextView iron = (TextView)findViewById(R.id.iron);
TextView point = (TextView)findViewById(R.id.point);
if(ft1.getText().toString().length() == 0 ){return;}
int first = Integer.parseInt(ft1.getText().toString());
double equal = first *0.0328;
DecimalFormat formatf = new DecimalFormat("#.####");
String x = formatf.format(equal)+" فوت";
foot.setText(x);
first = Integer.parseInt(ft1.getText().toString());
equal = first * 0.000005;
DecimalFormat formatm = new DecimalFormat("#.####");
x = formatm .format(equal)+"مایل";
mile.setText(x);
equal = first * 0.393;
DecimalFormat formati = new DecimalFormat("#.####");
x = formati.format(equal)+"اینچ";
inch.setText(x);
equal = first * 0.0109;
DecimalFormat formaty = new DecimalFormat("#.#####");
x = formaty.format(equal)+"یارد";
yard.setText(x);
equal = first / 10;
DecimalFormat formatmi = new DecimalFormat("#.##");
x = formatmi.format(equal)+"دسی متر";
dm.setText(x);
int equalmm = first * 10;
x = equalmm+"میلی متر";
mm.setText(x);
int equalm = first * 10000;
x = equalm+"میکرو متر";
mim.setText(x);
int equaln = first * 10000000;
x = equaln + "نانو متر";
nm.setText(x);
equal = first * 0.098;
DecimalFormat formath = new DecimalFormat("#####.#####");
x = formath.format(equal)+"هَند";
hand.setText(x);
equal = first * 19;
x = equal+"آیرون";
iron.setText(x);
equal = first * 28;
x = equal+"پوینت";
point.setText(x);
}
});
}
You need to inflate your activity with a layout resource first before you can use the findViewById() method to retrieve views. If there's no layout, then there are no views which could possibly be found.
You are missing an important part. You need to add a view to your Activity in order to find the elements of that view like the Button you are trying to instantiate.
In your OnCreate method add this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.the_xml_file); //Here add the xml file with the view you want to show
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
After your super.onCreate(savedInstanceState); are you setting the content view?
e.g.
setContentView(R.layout.nameofxmlfilehere);
Related
This question already has answers here:
OnClickListener in Android Studio
(5 answers)
Closed 6 years ago.
I am new to android studio and tried a tutorial where the presenter demonstrated his program but when I type out the code I am persistently getting an error like Cannot resolve Symbol setOnClickListener where the setOnClickListener is highlighted in red.
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
#Override
public View findViewById(#IdRes int id) {
return super.findViewById(R.id.Percentage_Input);
}
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener(){
public void onClick((View) view); {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent/100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec*Qty;
Resultant.setText(Float.toString(total));
}
})
I think your code is not in the right place. I see you are overriding findViewById (I wonder why) and rest of your code is also at the same level. You need to put all this code within a lifecycle method.
Maybe in onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener() {
public void onClick((View) view); {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent / 100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec * Qty;
Resultant.setText(Float.toString(total));
}
});
}
Also you are missing a semicolon ; at the end of setting OnClickListener.
Move ; and put at the end, this:
TextView Resultant = (TextView) findViewById(R.id.Resultant);
EditText Percentage_Input = (EditText) findViewById(R.id.Percentage_Input);
EditText Number_Input = (EditText) findViewById(R.id.Percentage_Input);
#Override
public View findViewById(#IdRes int id) {
return super.findViewById(R.id.Percentage_Input);
}
Button calc_btn = (Button) findViewById(R.id.calc_btn);
calc_btn.setOnClickListener(new View.OnClickListener(){
public void onClick((View) view) {
float percent = Float.parseFloat(Percentage_Input.getText().toString());
float dec = percent/100;
float Qty = Float.parseFloat(Number_Input.getText().toString());
float total = dec*Qty;
Resultant.setText(Float.toString(total));
}
});
Remove you method findViewById, this is some weird stuff, returning always the same view.
Put the rest of your code inside onCreate and add the missing ; at the end.
So , I was not making my self clear. I'm having a little trouble trying to get a button index from a matrix.
I have this matrix bt[4][4], and each button has a value like this :
btn11 = bt[0][0].
Now what I want to do is, whenever I click on a Button, I get it´s "cordinates".
Ex: Bt11 would give [0] and [0] .
Now the problems that I'm having:
I've set listeners to each button, but I can't implement a "onClick" method.
Whenever I try to implement here "public class easy extends Activity" I get an error message.
Second problem, I don't know to get the cordinates from bt[x][y].
To sum it up. I want to set a onClick method so every time you click on a button you get it's [x][y] cordinates.
Here's my code:
public class easy extends Activity { //Can't implement OnClick Listener
Button bt[][] = new Button[4][4];
Button up;
Button down;
Button left;
Button right;
int listaTroca[] = new int[10]; // lista pra receber os valores de retorno da logica
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
//Linha 1
bt[0][0] = (Button) findViewById(R.id.bt11);
bt[0][0].setOnClickListener((View.OnClickListener) this);
bt[0][1] = (Button) findViewById(R.id.bt12);
bt[0][1].setOnClickListener((View.OnClickListener) this);
bt[0][2] = (Button) findViewById(R.id.bt13);
bt[0][2].setOnClickListener((View.OnClickListener) this);
bt[0][3] = (Button) findViewById(R.id.bt14);
bt[0][3].setOnClickListener((View.OnClickListener) this);
//--------------------- Linha 2
bt[1][0] = (Button) findViewById(R.id.bt21);
bt[1][0].setOnClickListener((View.OnClickListener) this);
bt[1][1] = (Button) findViewById(R.id.bt22);
bt[1][1].setOnClickListener((View.OnClickListener) this);
bt[1][2] = (Button) findViewById(R.id.bt23);
bt[1][2].setOnClickListener((View.OnClickListener) this);
bt[1][3] = (Button) findViewById(R.id.bt24);
bt[1][3].setOnClickListener((View.OnClickListener) this);
//------------------------Linha 3
bt[2][0] = (Button) findViewById(R.id.bt31);
bt[2][0].setOnClickListener((View.OnClickListener) this);
bt[2][1] = (Button) findViewById(R.id.bt32);
bt[2][1].setOnClickListener((View.OnClickListener) this);
bt[2][2] = (Button) findViewById(R.id.bt33);
bt[2][2].setOnClickListener((View.OnClickListener) this);
bt[2][3] = (Button) findViewById(R.id.bt34);
bt[2][3].setOnClickListener((View.OnClickListener) this);
//---------------------Linha 4
bt[3][0] = (Button) findViewById(R.id.bt41);
bt[3][0].setOnClickListener((View.OnClickListener) this);
bt[3][1] = (Button) findViewById(R.id.bt42);
bt[3][1].setOnClickListener((View.OnClickListener) this);
bt[3][2] = (Button) findViewById(R.id.bt43);
bt[3][2].setOnClickListener((View.OnClickListener) this);
bt[3][3] = (Button) findViewById(R.id.bt44);
bt[3][3].setOnClickListener((View.OnClickListener) this);
//----------------------FIM DECLARAÇÃO + OUVIDOS
listaTroca = Logic.Logic_main(1,1,1);
}
}
I'm not completely sure what your question is here, but from what i understand you want a View.OnClickListener() on each button, and when the button is being clicked you want to do something right?
EDITED: I've edited the answer as the question was clarified in the comments below.
What you want to do, is simply iterate your bt[][] to find the right button, like so:
public class Easy extends Activity {
Button[][] bt = new Button[4][4];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
//Linha 1
bt[0][0] = (Button) findViewById(R.id.bt11);
bt[0][0].setOnClickListener(mOnClickListener);
bt[0][1] = (Button) findViewById(R.id.bt12);
bt[0][1].setOnClickListener(mOnClickListener);
// ADD YOUR OTHER findViewByID
}
View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ButtonCoordinate bc = getButtonCoordinate(v);
if (bc != null) {
// You now have your button, and the coordinates
Log.d("Easy", "Button.position[ x:" + bc.x + ", y:" + bc.y + " ]");
}
}
};
private ButtonCoordinate getButtonCoordinate(View v) {
for (int x = 0 ; x < bt.length ; x++ ) {
for (int y = 0 ; y < bt[x].length ; y++) {
Button b = bt[x][y];
if (v == b) {
return new ButtonCoordinate(x, y, b);
}
}
}
return null;
}
public static class ButtonCoordinate {
public final int x;
public final int y;
public final Button button;
public ButtonCoordinate(int x, int y, Button button) {
this.x = x;
this.y = y;
this.button = button;
}
}
}
you just need to call getButtonCoordinate(View) which will return a ButtonCoordinate containing the Button and it's x and y coordinates in the bt[][]
My app is crashing at the end of the array in bluestacks. I have no idea why.
When I click the next button at the end of the array, the app crashes. I also tested it on my phone, same result. The rest of the app functions as intended.
From what I know "i %= image_elements.length;" is supposed to be the function that loops the array.
I am pretty sure this is where the crash is coming from.
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
Full code below
public class Practice extends MainMenuActivity {
int i = 0;
final int[] image_elements = {
R.drawable.spr_elements_0,
R.drawable.spr_elements_1,
[...]
R.drawable.spr_elements_86,
R.drawable.spr_elements_87,
};
final int[] image_names = {
R.drawable.spr_name_0,
R.drawable.spr_name_1,
[...]
R.drawable.spr_name_86,
R.drawable.spr_name_87,
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
}
});
}
public void backButton(View view) {
Intent z = new Intent(this, MainMenuActivity.class);
startActivity(z);
}
}
You'll need to rearrange your code from this:
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
to this:
i++;
i %= image_elements.length;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
What happens otherwise is that the index is incremented beyond the boundaries of the array, and that is corrected afterwards with the modulus operator. You'll need to the the correction before you use the index.
i %= image_elements.length in this particular case, is essentially the same as
if( i == image_elements.length ) {
i = 0;
}
Arrays indices go from 0 to length-1.
You could get rid of the arrays entirely by looking up the resources by name, such as this:
final static int MAX_ELEMENTS = 88; // this includes 0..87
private int index = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
final Resources res = this.getResources();
final String pkgName = this.getPackageName();
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final int imgId = res.getIdentifier( "spr_elements_" + index, "drawable", pkgName );
final int nameId = res.getIdentifier( "spr_name_" + index, "drawable", pkgName );
element.setImageResource( imgId );
name.setImageResource( nameId );
index = (index+1) % MAX_ELEMENTS;
}
});
}
Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
But i get always the same order, even i close and run again the app. How to do that?
If you want shuffle list:
Collections.shuffle(names)
If you want random int between 0 or 1 (nextInt(int) javadoc):
Random random = new Random();
int randomInt = random.nextInt(2);
Math.random() returns a number between 0 and 1. So when you cast it to int it will always be 0.
Try this:
p1 = (int)(Math.random()*2);
It happens because
p1 = (int)Math.random();
always gives you zero.
This code creates a seekbar and makes the seekbar create as many EditText fields as the slider is at / remove ones that would be too much. This code is in OnActivityCreated
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
EditText editText = new EditText(getActivity());
editText.setId(i);
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
SeekBar bar = (SeekBar) getActivity().findViewById(R.id.npv_seekbar);
final TextView selection = (TextView) getActivity()
.findViewById(R.id.npv_selected);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress,
boolean fromUser) {
selection.setText("You have selected " + progress + " periods.");
if (progress == 0) {
String normalstring = getActivity().getResources()
.getString(R.string.npv1);
selection.setText(normalstring);
}
if (i > progress) {
while (i > progress) {
i--;
EditText editText = (EditText) getActivity()
.findViewById(i);
linearLayout.removeView(editText);
}
} else {
while (i < progress) {
EditText editText = new EditText(getActivity());
editText.setId(i);
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(editText);
editText.setHint("Cash Flow " + i);
i++;
}
}
}
public void onStopTrackingTouch(SeekBar arg0) {
}
public void onStartTrackingTouch(SeekBar arg0) {
}
});
This code is in the general class area:
int i = 0;
EditText r = (EditText) getActivity().findViewById(R.id.npv_rate);
Button calc = (Button) getActivity().findViewById(R.id.npv_calc);
EditText[] DynamicField = new EditText[16];
Now I want users to input numbers into those edittext fields and then I want to do some math on them: Entry / (Math.pow(1+r, i) with i beeing the id of the field. The first entry should therefore be calculated as this: entry/(1+r)^0. This is what I tried but it doesn't work. It just crashes on startup.
calc.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Double r1 = Double.parseDouble(r.getText().toString());
EditText editText = (EditText) getActivity().findViewById(i);
TextView answer = (TextView) getActivity().findViewById(R.id.npv_answer);
double[] CashFlows;
CashFlows = new double[i];
double result = 0;
CashFlows[i] = (Double.parseDouble(editText.getText()
.toString())) / (Math.pow(1 + r1, i));
for (double d : CashFlows) {
result += d;
}
answer.setText("answer is " + result);
}
});
What did I do wrong? by the way only the last code segment isnt working. if i comment that out it all works fine i tested it :) just dosent do anything obviuosly :)
ok a little background on the errorlog that you can see here: http://pastebin.com/G8iX6Pkm
EDIT: the entire class file can be seen here: http://pastebin.com/dxA91dst, the entire project can be found here: https://github.com/killerpixler/Android-Financial-Calculator.git
the class file is a fragment that gets loaded in a DetailsActivity when somebody clicks on a listitem from the Main activity. Like i said the error has to be in the button listener because it was working before i added it.
That NullPointerException comes from the fact that you initialize your Views using the getActivity() method where you declare them as fields in the F_NPV class. The method getActivity() method will return a valid Activity reference after the callback onAttach() is called, so the way you initialize the views will not work as, at that moment(when the fields of the Fragment class are initialized) the method getActivity will return null, no valid reference. The correct way to do that initialization is doing it in the onActivityCreated callback:
EditText r;
Button calc;
//...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
r = (EditText) getActivity().findViewById(R.id.npv_rate);
calc = (Button) getActivity().findViewById(R.id.npv_calc);
//...
Also, if I may, some suggestions regarding your code:
You're doing some double's parsing from Strings and it may be a good idea to check the input so you don't throw a NumberFormatException. For example, if the user creates some EditTexts and then clicks the calculate Button(I know, it sounds silly, but there are chances the user will do it(I did it for example)), you'll throw a NumberFormatException as you try to parse an empty String. Instead make a little check:
public void onClick(View arg0) {
Double r1 = Double.parseDouble((r.getText().toString())
.equals("") ? "0" : r.getText().toString());
EditText editText = (EditText) getActivity().findViewById(i);
TextView answer = (TextView) getActivity().findViewById(R.id.npv_answer);
double[] CashFlows;
CashFlows = new double[i];
double result = 0;
String tmp = editText.getText().toString();
CashFlows[i] = (Double.parseDouble(tmp.equals("") ? "0" : tmp))
/ (Math.pow(1 + r1, i));
//...
Also, even if you have correct values in the EditText the above code will throw a NullPointerException, as the editText variable will be null. The reason for this is in the while loops that you used to create the fields. For example, if the user moves the SeekBar to 3 than the while loop will run 3 times, each time incrementing the i value. So i will be 0, 1, 2, so far correct but because you increment i each time the final i will be 4. Now in the onClick method you'll look for an EditText with the id i, but as there is no EditText in the layout with the id 4, the view will be null.
Also, try to give your classes better names, you may know very well what they mean but you could be making things worse for someone that reads your code(like F_PNV, F_PV etc).
Code for the onActivityCreated method. This should solve what you're trying to do(if I understand what you want):
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
r = (EditText) getActivity().findViewById(R.id.npv_rate);
calc = (Button) getActivity().findViewById(R.id.npv_calc);
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
SeekBar bar = (SeekBar) getActivity().findViewById(R.id.npv_seekbar);
final TextView selection = (TextView) getActivity().findViewById(
R.id.npv_selected);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress,
boolean fromUser) {
selection
.setText("You have selected " + progress + " periods.");
if (progress == 0) {
String normalstring = getActivity().getResources()
.getString(R.string.npv1);
selection.setText(normalstring);
linearLayout.removeAllViews(); // the progress is 0 so
// remove all the views that
// are currently present
} else {
int currentChilds = linearLayout.getChildCount();
if (currentChilds < progress) {
while (currentChilds != progress) {
EditText editText = new EditText(getActivity());
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(editText);
currentChilds++;
}
} else if (currentChilds > progress) {
while (currentChilds != progress) {
linearLayout.removeViewAt(linearLayout
.getChildCount() - 1);
currentChilds--;
}
}
}
}
public void onStopTrackingTouch(SeekBar arg0) {
}
public void onStartTrackingTouch(SeekBar arg0) {
}
});
calc.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Double r1 = Double.parseDouble((r.getText().toString())
.equals("") ? "0" : r.getText().toString());
TextView answer = (TextView) getActivity().findViewById(
R.id.npv_answer);
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
int size = linearLayout.getChildCount();
double[] CashFlows = new double[size];
double result = 0;
for (int i = 0; i < size; i++) {
EditText editText = (EditText) linearLayout.getChildAt(i);
String tmp = editText.getText().toString();
CashFlows[i] = (Double.parseDouble(tmp.equals("") ? "0"
: tmp)) / (Math.pow(1 + r1, i));
}
for (double d : CashFlows) {
result += d;
}
answer.setText("answer is " + result);
}
});
}