I am trying to call a method I have written. It compiles except for one line...
public class http extends Activity {
httpMethod(); //will not compile
I think perhaps you need to learn more about Android Application Fundamentals and in particular the Activity class and the Activity
lifecycle.
Your first problem is related to attempting to set a test string on your TextView
.
DO NOT attempt to do this in any method which is called by the constructor. Perhaps more importantly, forget about ever defining a constructor (or constructors) for any class you create which extends Activity
.
In order to be able to manipulate the UI elements of an Activity
, the content view must be inflated. This is done either implicitly using setContentView(...)
or explicitly using LayoutInflater
. It is most usual to do this in onCreate(...)
and until this is done, attempting to use findViewById(...)
will return null
. This is why attempting to do anything with the UI from an Activity
constructor will fail unless you explicitly inflate your layout within the constructor (or another method called by it). I'm not sure it's even possible to inflate the layout at this point and it's certainly not something I'd recommend even if it is possible. As I said, forget about constructors for Activities
.
To do what you want to do (for test purposes) you would need to do something like...
public class HttpActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
httpMethod();
}
public void httpMethod() {
...
}
}
Your second problem, as Maxim's comment on your question, even though my example will work for older versions of Android, more recent versions will throw an exception if you attempt to perform network operations on the main thread (aka UI thread) as they are potentially time-consuming and can cause the thread to be blocked. As Maxim suggests you should do this with an AsyncTask
or on some other Thread
than the main (UI) thread.