Android App - View function - android

bit of a noob question, I think I'm going about this the wrong way.
This is my first app and I'm trying to set it up into multiple files and classes, my current problem:
For neatness and unforseen use in the future, I had placed my layouts into functions:
public void homepage (){
setContentView(R.layout.layout_homepage);
}
I use the menu for most of my direct navigation and, previously, calling these functions in the
onOptionsItemSelected () worked perfectly.
However, when I moved my page functions to a seperate class:
public class newpage extends MyApp {
//Home
public void homepage (){
setContentView(R.layout.layout_homepage);
}
....
and called them in the function:
public boolean onOptionsItemSelected(MenuItem item) {
//Create new page class
newpage pagecla = new newpage();
...
pagecla.homepage();
....
It crashes the app, and when debugging the only sense I can make of it is a NullPointerException.
I'm guessing I have to give it some kind of value for View, but I'm really not sure what.

Don't do this. Each activity should have a call to the setContentView() function to intialise the function. Shouldn't need to externally reference it.

You should invoke setContentView from your activity, not your Application. If you want to do this from your Application anyway (don't know why), you should provide a reference to your activity. But it's an awful design, plus you shan't name your class pagecla, you'd better read about java naming conventions.
It seems that you lack OOP knowledge also. Your function is in fact a method, which needs an object to be invoked on. It's your Activity before your refactoring and your pagecla after it.

Related

code reusability in android

I have 3 activities with the same toolbar. I would like to avoid copying code on each activity. I know I can use <include> tags in every layout in order to reuse the same layout for the toolbar. Now I would like to share the event handlers for each button of the toolbar in all the activities. I am thinking of making a toolbarActivity which extends Activity class and the 3 activities extends toolbarActivity, so in onCreate method, when I call base.OnCreate, all the event handlers would be defined. But, SetContentLayout was not called yet, so base.OnCreate will not find the buttons. Remember the 3 activities have different layouts. Do you know the best way to reuse code in order to avoid copying all the event handlers in OnCreate method for every activity and allowing me to override some functionality?
Android is used on mobile devices so at development time their is no way to know the size and dimensions of the users device. On large devices many UI elements can fit. On smaller devices few UI elements can fit. Your question relates to this dilemma and therefore has many possible answers. Logically for code to work it must exist inside the source, ie you could cut and paste, a bad solution because you end up with many versions of this "same" toolbar or you could refer/reference one "external" toolbar. Fragments come to mind as does having a separate source file. UI source files can be thought of as pairs. Java for dynamic elements and xml for static. So in summary just reference an external fragment that has implemented your toolbar.
If you keep the naming conventions for the buttons and other things in each layout that are tied to the references in your activities then you should have no problem.
For example if you have a '#+id/login_button' in one layout then just use the same convention for the same type of button in the next one and youll be fine.
You could define a base activity which all your other activities extend, and make it implement a click listener (or whatever interface you are using to listen for button presses). You can check the Id of the clicked view and thus provide a callback to perform whatever logic you want.
public class BaseActivity extends Activity implements OnClickListener {
public void onCreate() {
myBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (R.id.my_btn == v.getId()) {
onFoo();
}
}
protected void onFoo() {
// TODO handle foo
}
}
You can then override the method in your subclasses if you need to provide different behaviour.
public class DifferentActivity extends BaseActivity {
#Override protected void onFoo() {
super.onFoo()
// TODO handle foo differently
}
}

How to set the values in Textview of MainActivity from simple class

I have two classes One is MainActivity.java and other is simple Java class ConnectMe.java. I have Single Button and Single EditText on MainActivity. I am using a button to Login So it is named also as btnLogin. On its clickListener, I am taking the Ip from the EditText(in string format) and calling the Login function from the ConnectMe.java class which takes string as a parameter.
Now in ConnectMe class I check if the application is connected to the server it should show the Connected Message in EditText and Also it should show the Toast on MainActivity. And I have no Idea How to do this as I am new to android.
here is my sample code
public class MainActivity extends Activity {
Button btngLogin;
EditText etIp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ConnectMe connectMe = new ConnectMe();
connectme.LogMeIn(etIp.getText().toString);
}
});
}
here is my java class for connection
public class ConnectMe {
MainActivity mainActivity = new MainActivity();
void LogMeIn(String ip){
MyConnectedmethod.Connectednew (new Runnable() {
public void run() {
mainActivity.setText("connected");
}
}
I know the code is not proper, But I just want to give you an idea. I am getting the null point exception on the line in which I am setting text of EditText.
With some research, I have find out that I can not touch the views from the Thread and Runnable directly . and I was told to use runOnUiThread. like mainActivity.runOnUiThread but it is also not helping giving error of nullpointexception.
So Please help me as I am new to android programming
A lot going on here.
There's basically no instance in which you should instantiate an activity.
The Activity doesn't have a .setText() method. So that's the null pointer.
There's a much easier way to do a simple worker task than creating your own thread and managing it yourself. Use AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
EDIT:
You can run as many AsncTasks as you like. Without more context, it's hard to say exactly what your best approach is. But, it sounds like you probably want to run some kind of service. (http://developer.android.com/reference/android/app/Service.html). There's a couple different flavors available, depending on what you want to do. If it needs to run all the time, rather your app is running or not, then use a start service. If it needs to run only so long as the UI is going, then a bound service is the option. If it needs to do something every so often than some combination of intent service/broadcast receiver/alarm manager is the route.
You may not even need a service. If you're just loading several things use the loader manager. For downloading content a SyncAdapter may be the way to go. The point is that after 24APIs most common tasks already have a ready made solution. So, in most cases, you don't need to fiddle with threads yourself.
The NullPointerException happens because you`re missing to declare what object Button btngLogin refers to.
btngLogin = findViewById(R.id.yourbuttonnameinxml);
Do the same with your EditText.
i think you better read this first, starting another activity with intents and sharing a message between two activities (classes): http://developer.android.com/training/basics/firstapp/starting-activity.html

Android: How to call a a Class within the Current Class

I'm working on an application that has multiple Activities, and I'm tired of running back and forth between the Manifest and XML layout and stuff. Is there a way to have
Intent intent = new Intent(MainActivity.this, MainActivity.Settings.class);
Or something? Because I've tried it, it doesn't throw me an error, but it just force closes the application. I'm able to bundle all my classes from different .java into one, for ex.
public class MainActivity extends Activity
{
...
#Override
protected void onCreate(Bundle MainActivityState)
{
...
}
public class Settings extends ...
{
...
}
public class Register extends ...
{
...
}
public class Login extends ...
{
...
}
public class BeautifulLady extends personality ...
}
Simple. Just don't even try.
An activity loosely represents a single screen - something the user interacts with. Android is built around this concept and trying to circumvent it will lead to tears.
Stick with it. Having your classes in separate files, and having layout XML separate for each activity, will become your friend and will actually speed things up once you are familiar.
Start with the Activity life cycle document and read it several times until the penny drops. Then expand out from there.
http://developer.android.com/reference/android/app/Activity.html
Object oriented programming, with classes that take care of themselves, is a joy and regardless of which platform you choose to develop on is the way to go for the foreseeable future (old hands, no debates on OOP vs functional please ;)).
If you are going to do mobile development, then the separation of activities, classes and UI is the same concept, just done differently.
See also MVC programming and its' cousins.
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Good luck.
Perhaps you can define your Activity as 'Single Top', then launch your activity from herself like MainActivity.this.startActivity(new Intent(MainActivity.this, MainActivity.class). It'll then go into onNewIntent() and you will redisplay what you want to redisplay. This way you will have only one screen.

Android/Java: Change view from another class?

There are two classes. MainActivity, in which i set the view, and ClassX from which i want to update a view in MainActivity. ClassX is an AsyncTask called from MainActivity, if that's relevant.
What i want to do is to change the text of a view called mainTextLog. I've declared a global TextView variable, and in the onCreate() method i set it to the view using findViewById().
private TextView logger;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
logger = (TextView) findViewById(R.id.mainTextLog);
}
By now i should be able to change the text from onCreate(), and i can. But since i want to change it from another class (ClassX) i need to create a method for it:
public void setLogText(String text) {
logger.setText(text);
}
But it doesn't work. I've tried making logger and the setLogText() method static, but it still doesn't work. The app just crashes.
It's probably pretty easy, but i'm out of ideas.
If you are using an AsyncTask you need to set the value in either onProgressUpdate or in onPostExecute.
You really should read the documentation for AsyncTasks
You CANNOT update the UI from the doInBackground method as it is not run in the UI thread and will give you an exception.
Also, you should post the exception you are getting when the application crashes so we have a better idea what the problem is. But I'd guess you are trying to update the text from the wrong thread.
I've done this plenty in the app im working on, its sort of an MDI type app on the android tablet.
To do what you're asking....
in MainActivity have
public static void setText(String txt){
((TextView)findViewById(R.id.mainTextLog)).setText(txt);
}
then in the child (or calling class) call it like...
MainActivity.setText("myTextToShow");
That's it... im using android api level 12... If i remember correcty it worked in api level 7 as well though.
Hope this helps...
One possibility is that: when you call setLogText in another Class X. The MainActivity may not be existing anymore, which makes the logger a null reference?

Is there a way to make a function that's available to all Activities?

I have a set of commands that I want my app to run when it's restarted, regardless of what activity it's on. I know I need to put an onRestart() into every one.
Since it's the same set of commands regardless of what activity it's on, is there a way I could have them all refer to a single function for that? It seems like that would be better then having to copy paste the commands into each onRestart() handler. It will be a lot less work if I need to change the set of commands too.
You have a couple of options, depending on the code.
You can put it in a helper class as a static function: public static void doWork() { .. } This should work, unless whatever you are doing depends on being in the activity. You can generally just pass it what it needs though, like the Context.
Or, you could extend Activity with your own class, MyActivity and place the work in that onResume. Then extend MyActivity for each of your real activities. They will now automatically do that work when you call super.onResume(). This works well as long as you really want to do the same thing in every activity, and don't use a lot of specialized activities like ListActivity.
Edit:
public class MyHelper {
public static void doWork() {
// do your work here
}
}
public class MyActivity extends Activity {
public void onResume() {
super.onResume();
MyHelper.doWork();
}
}
A search for "static method" will provide more details.
Derive all your activities from a single class (something like ActivityBase) that, in turn derives from system-provided Activity. Then implement onRestart() in ActivityBase.
Is it your application that is restarting from scratch? Or just your activities that are restarting/resuming?
The Application class has an onCreate() method, and you can extend Application in your app to override its behavior. Just remember to change the name of the application in AndroidManifest.xml so it picks up your custom Application class when starting. This code would run before any activities start up. But it won't run every time an activity is stopped and restarted. If that's what you need, this won't do it.
You could also implement a singleton class that contains an initialize() method, or restart() method. You simply call it from onRestart() in each activity you want it in. It sounds like this special code ought to be localized away from your activities so I don't think I'd recommend extending Activity to put the code there.

Categories

Resources