This question already has answers here:
Java Error: Cannot make a static reference to the non-static method
(7 answers)
Closed 8 years ago.
I have this in my java code, when I try to compile my code I get an error. This happens when I try to get the value of the text in my textview into a var. I cannot understand this error because It works fine in the other method.
Why happens this and how can I fix it?
public class MainActivity extends Activity {
public EditText editText;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(MainActivity.this, "onCreate", Toast.LENGTH_LONG).show();
//setupMessageButton();
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView)findViewById(R.id.tvIsConnected);
}
public void btnDisplayMessage(View view){
//HERE WORKS FINE
String missatge = editText.getText().toString();
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
//HERE CRASHES
String missatge = "red"//editText.getText().toString(); GIVES ERROR
String usuario = "foo";
............
WHY?
EDIT: Thanks for downvote my question, Yes, I searched for another similar questions and I've already tried with static method...then don't crash but the content of the var is null and don't work at all.
You can not access a variable non static from a static method...
Solutions:
Make editText static
Its not Logical that one static method access a variable non static, so you should change the logic there!
Greetings :)...
Related
This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 5 years ago.
I need to start the countdown timer in this activity. It should be started from the button. Below I bring the code snippets.
I think I did everything right, but it doesn't work - why is this?
public class Step5 extends AppCompatActivity {
Button mgo;
public TextView timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.step5);
timer = (TextView) findViewById(R.id.timer);
mgo = (Button) findViewById(R.id.go);
mgo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(900000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText((int)millisUntilFinished/1000);
}
#Override
public void onFinish() {
timer.setText("Done");
}
}.start();
}
});
}}
Button in xml
<Button
android:id="#+id/go"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#FF3D00"
android:textColor="#ffffff"
android:text="#string/Start"
android:layout_alignParentBottom="true"/>
The problem is in the timer.setText((int)millisUntilFinished/1000); part.
timer.SetText() needs a string as an argument.
So try the following
timer.setText(String.valueOf((int)millisUntilFinished/1000));
It will work 100 %.
The problem lies on the below code snippet:
timer.setText((int)millisUntilFinished/1000);
setText() method accepts only String as argument type while you are passing an int type of argument. So you could try to use the valueOf() static method of String class in order to convert your int value type into a String Object. Below is the suggested solution:
timer.setText(String.valueOf((int)millisUntilFinished/1000));
Nevertheless it should be noticed that if you compile you submitted code you will get the below compilation error:
error: incompatible types: int cannot be converted to String
This means that your code will be compiled with error and you will get noticed by the compiler for sure.
Additionally if you would use a Java IDE like Netbeans then you would get noticed for this error by a notification like below:
incompatible types: int cannot be converted to String
So concluding lets say that errors like these can be avoided by reading IDE's warnings and as a second step the compiler's messages.
public class MainActivity extends AppCompatActivity {
public int theMethod(){
return 3;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.theOutput);
textView.setText(theMethod());
}
}
I have tried this. To write out the return value of theMethod to the screen with setText.
The result is the app just stopping when I try to start.
How could I do that? Thanks.
edit:
Thank you guys. Now it works. Luv ya all!
textView.setText(String.valueOf(theMethod()));
If you have look in the documentation of TextView, you can see that setText(int) actually expects a resource id: (https://developer.android.com/reference/android/widget/TextView.html#setText(int))
So you have to turn your int to a CharSequence, you could simply do
textView.setText(theMethod()+"");
Try like this.
textview.setText(""+theMethod());
And post your logcat.
Your problem is that there are two setText() methods on TextView.
The first one is setText(int param) which you are using, and expects a string resource ID, like R.string.some_text.
What you intended to use was setText(String param) which displays the String in the TextView. To fix this, make your method return a String instead, like this:
public String theMethod(){
return String.valueOf(3);
}
Your Problem is when ever you try to pass int value to the TextView's setText() method it tries to find a string resource associated with the integer you passed, thats why you are program is crashing.
try to set it as below
textview.setText(String.valueOf(theMethod()));
and then you will not get ResourceNotFoundException
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Problem: (All info below) I've set up the app to get text from EditText component and add it into a LinkedList once the button is pressed.
Tests: Testing for getText.toString() was successful (so u_in had a usable string) and I also tried to implement a simple array within my MainActivity and perform the same function which worked perfectly. Although I keep getting a NullPointerException with the database class and LinkedList.
I've also tried adding a null check in the OnClick anonymous method, but still got the same error.
Testing using physical device and running Android Studio 2.1
Main class:
public class MainActivity extends AppCompatActivity {
public Data_base db;
public String u_in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check_button();
}
public void check_button() {
Button add_button = (Button) findViewById(R.id.button);
final EditText etext = (EditText) findViewById(R.id.editText);
add_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
u_in = etext.getText().toString();
db.add(u_in,0);
}
});
}
Input class(Initializes information):
public class Input {
public String input;
public int age;
public Input (String input, int age) {
this.input = input;
this.age = age;
}
}
Database class (where I have my linkedlist and methods to manipulate it):
public class Data_base {
public LinkedList<Input> user_in = new LinkedList<>();
public void add(String in, int age) {
user_in.add(new Input(in, age));
}
public LinkedList<Input> getList() {
return user_in;
}
}
Error:
05-02 22:51:59.202 2813-2813/com.example.user.test_app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.test_app, PID: 2813
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.user.test_app.Data_base.add(java.lang.String, int)' on a null object reference
at com.example.user.test_app.MainActivity$1.onClick(MainActivity.java:33)
at android.view.View.performClick(View.java:5155)
at android.view.View$PerformClick.run(View.java:20747)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
In your MainActivity you're using db.add without instantiating db first.
Edit Addressing Comment:
Not sure exactly what you're doing with the age variable, but generally there are some ways to programatically get the same variable from an entire collection:
1) Get the value while iterating over the original collection:
//Somewhere in your business logic:
for(Input i : db) {
String text = i.getInput(); //Your class should have getters and setters
//Do something with the text variable
}
2) Make a List<String> using a static method in your Input class:
public static List<Input> stringsFromInputs(List<Input> inputs) {
List<String> ret = new ArrayList<String>();
for(Input i : inputs)
ret.add(i.getInput()); //Again, your class should have getters/setters
return ret;
}
3) If you're not going to use such a static method often, then perform this logic where needed in the code itself (which you seem to want to avoid).
Hope this helps some.
In onCreate before calling check_button() add:
db = new Data_base();
Create Data_base object first in MainActivity the try to do operation with add method
I need to display in a AlertDialog the following message and show it. using this code I already have done it on this way :
AlertDialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.pic_time +
" qntpic" +//This is one variable i must call from a .java called PreviewCamera
R.string.pic +
"time" +//This is one variable i must call from a .java called PreviewCamera
R.string.time);
builder.setPositiveButton(android.R.string.ok, null );
dialog = builder.create();
dialog.show()
but i don't know how to proceed to call this variables, i try already some methods but no results.
This variables are int, and private on PreviewCamera.
Using the information that you guys give it to me, this appear.
This is the solution if maybe someone find the same problem as me
AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getResources().getString(R.string.pic_time) +
Integer.parseInt(bdl.getqntpic()) +
getResources().getString(R.string.pic)+
Integer.parseInt(bdl.getTime()) +
getResources().getString(R.string.time));
builder.setPositiveButton(android.R.string.ok, null ); dialog = builder.create(); dialog.show(); }
Is that right? it kind of works.
Thanks!
R.string.pic_time return the id of the resource.
If you want the value of the resource, you have to use getResources().getString(R.string.pic_time) for a String or getResources().getInteger(R.integer.time) for an Integer.
The Integer can be converted to String by use : String.valueOf(yourInt)
You are confusing .xml variables and .java variables.
.XML variables are get with getResources().getString(R.string.pic_time) or getResources().getInt(R.int.pic_time). They are defined inside a .xml file (named only with lowercase letters and underscore) under a folder "res/values". They are set at compiletime and cannot(/shouldn't?) be changed at runtime (afaik).
.java variables are variables set by your java code, inside classes. They are get with references. When you call System.out.println(pic_time);, you get the value of your variable "pic_time" thanks to its reference in memory.
Example : the class MainActivity will get the variable "pic_time" from the class A_Class :
MainActivity.java
public class Accueil extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
A_Class mySecondClass = new A_Class();
int myInt = mySecondClass.getPicTime();
System.out.println(myInt);
}
}
A_Class.java
public class A_Class
{
private int pic_time;
public A_Class()
{
pic_time = 50;
}
public int getPicTime()
{
return pic_time;
}
}
This question already has answers here:
How are Anonymous inner classes used in Java?
(18 answers)
Closed 9 years ago.
second day in android self teachin and saw this code bleow.
from what I understood, it seems to me that the code is getting the button value
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
and then I am not sure what happened. Being from php background this syntax looks very unfamiliar that a method is being called as a methods parameter in here
GetServerData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// WebServer Request URL
String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
I also am not sure what View arg0 is.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rest_ful_webservice);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// WebServer Request URL
String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
1) This is type casting, the method
findViewById returns something, the method
which called it casts the result to Button.
2) This an anonymous class, this is a class
implementing an interface, the class is defined
right there at the place of its usage.
3) The OnClickListener interface
apparently has one method called
onClick and it has one View argument.
This is what arg0 is. But it does not
seem to be used in the implementing class.
The name arg0 is not really important.
You can name it also x or y or anything else.