How can I split MainActivity functionality into an another class for clarity?

android multiple activities in one screen
multiple buttons in one activity android
android multiple activities in one app
how to move from one activity to another in android on button click
how to move from one activity to another in android without using intent
how to navigate from one page to another in android studio
android go back to previous activity on button click
white screen is displayed while switching between activities

I have an android program and I want to be able to split the functionality in MainActivity into multiple files to keep my code organized, but I'm getting a null object reference error.

To demonstrate the error, I created a simple program that has only a textView and a button to change the textView. The error occurs when the button is clicked. How can I fix this issue so I can have a helper class?

MainActivity.java

package com.example.testapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private MainActivityHelper mainActivityHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainActivityHelper = new MainActivityHelper();
    }

    public void buttonPressed(View view) {
        mainActivityHelper.changeText();
    }
}

MainActivityHelper.java

package com.example.testapp;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivityHelper extends AppCompatActivity {
    public MainActivityHelper() {

    }

    public void changeText() {
        TextView textView = findViewById(R.id.helloString);

        if(textView.getText().toString() == "Hello World!") {
            textView.setText("Goodbye world!");
        }
        else {
            textView.setText("Hello World!");
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Error message:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.testapp, PID: 17322
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
        at android.view.View.performClick(View.java:6294) 
        at android.view.View$PerformClick.run(View.java:24770) 
        at android.os.Handler.handleCallback(Handler.java:790) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
        at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
        at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:56)
        at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
        at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:198)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
        at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
        at com.example.testapp.MainActivityHelper.changeText(MainActivityHelper.java:14)
        at com.example.testapp.MainActivity.buttonPressed(MainActivity.java:19)
        at java.lang.reflect.Method.invoke(Native Method) 
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
        at android.view.View.performClick(View.java:6294) 
        at android.view.View$PerformClick.run(View.java:24770) 
        at android.os.Handler.handleCallback(Handler.java:790) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

You have a null pointer because you haven't set the content view for Main activity helper. Use and Activity inside another one is not the correct way to reach your objective.

If You want to have an helper class you don't have to extends an Activity or to declare a field that Is an Activity. The best way Is to use a viewmodel that Is a common backend class used into mvvm pattern. Viewmodels allows the separation of the Logic from the Activity code.

If you want continue your case Just declare a normal Java class and pass a reference of Activity to the constructor of this class. Something likes this in onCreate of Main Activity:

MainActivityHelper = new MainActivityHelper(this);

After that you can call methods of your activity inside the helper (e.g. likes findviewbyid).

Hope this give you some hints/help.

Cheers.

Multiple Activities, The main activity, as defined in the AndroidManifest XML file, is started when the application is started Note that unlike other activities, implicit intents that reside in other More functionality can be added as needed to this activity, and multiple Button; public class PlayGame extends Activity { public void onCreate(Bundle� Then enter the Activity Class name and a name for the XML layout. Overall I have Created a new project with package name com.learn2crack.activities, Activity name MainActivity, and layout name activity_main. Finally select finish, Gradle will build your project. Now you have activity_main.xml in your layouts resource directory. Let’s add a

You cannot just break an activity that way. I would recommend to use fragments inside activity, that way you could isolate every fragment with specific pieces of code and just make a simple call back to the activity (at this point, the activity is a simple container to glue all the fragments, serves as a mediator).

Please take a look at this Android Fragments.

This one could be outdated but it's a good entrypoint vogella.

Device Orientation, To control the orientation on Android, open MainActivity.cs and set the orientation using the attribute decorating the MainActivity class: Notice that the apps take advantage of the available space by adding more functionality in landscape. For clarity, the following sections demonstrate how to implement� Right, open the MainActivity java file now and we’ll create the onButtonClick method: Here’s the code for onButtonClick: public void onButtonClick(View v){ Intent myIntent = new Intent(getBaseContext(), SecondActivity. class ); startActivity(myIntent); }

you are getting NPE, because you are using findViewById without attaching the content view.

you can create a separate class and put this method and all your other methods inside it:

Class that contains all of your constants
public final class Constants {

    public static final String HELLO_WORLD = "Hello World!";
    public static final String GOODBYE_WORLD = "Goodbye world!";

}
Class that contains all of your methods
public class Methods {

    public static void changeText(TextView textView) {
        if(textView.getText().toString() == Constants.HELLO_WORLD) {
            textView.setText(Constants.GOODBYE_WORLD);
        }
        else {
            textView.setText(Constants.HELLO_WORLD);
        }
    }


    public static void otherMethods() {
        // other methods
    }


}

And use it inside your MainActivity like this

setContentView(R.layout.activity_main);

TextView textView = findViewById(R.id.helloString);
Methods.changeText(textView)

Changing Your Android App's Theme Dynamically, Find out how to build a customizable Android app, where the user can change the For the sake of clarity, we'll focus on themes in this tutorial, but in reality the To check that the theme switching functionality is working, we'll create a public class MainActivity extends Activity implements OnClickListener Here are 8 fantastic brain warm-up exercises that can be done in the morning to encourage mental clarity, leaving you with a mind as clear as a blue sky. 1. Find a Noun for Each Letter of the Alphabet

You can't split the activity into two classes that extend the AppCompatActivity class, but you can have a helper class or "Utils" class which holds a set of static functions, each one serving a specific purpose. This way you can make the activity code more readable by minimizing it and moving portions of your code to the helper class.

Also, you can use ViewModel with LiveData to separate your data "Fetching" logic and UI logic. You can learn more about this here: https://developer.android.com/jetpack/docs/guide

Android Tab Layout with Swipeable Views, Also you can swipe between tab view as it is the functionality of In order to display tabs we don't have to use any other UI element like TabHost. In your MainActivity.java class add following code. I divide the information with Navegation Drawer and I divide that information in categories with the Tabs. Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. As of API 11 drag and drop of view onto other views or view groups is supported.The framework includes following three important components to support drag & drop functionality − Drag event class.

[PDF] Graduates' career planning and its effect on graduate outcomes, the point of applying to university by main activity at Planning for Success Survey . Figure 5.1: Levels of graduate participation in different forms of work experience . Table 7.1 Clarity of career plan upon completing undergraduate degree by profile of Without them of course, the research would not have been possible. Explicitly use the class name MenuScreen.this. Call a function that is declared at the right context level. This is what is used in Listing 2.8: startGame(). Each of these methods can usually be interchanged. Utilize the one that works best for the clarity of the situation.

Grant Allen Use this definitive Android reference to take your apps , followed by another semicolon, followed by the path to the Android SDK The final step to make ADT functional in Eclipse is to point it to the Android SDK. android:text="Literal text" //what we did for clarity or setData(Uri.parse("geo:0,0 ?z=4&q=business+near+city")); code from Listing 3-1 into your MainActivity class. Notice I split up the list comprehension into multiple lines for clarity. The first line is our temporary variable name. Since we’re not modifying the value, nothing special happens here.

[PDF] Shoptimus Prime Final Report, For clarity, only classes which apply to the end-‐user are shown. done manually by pressing the Set Location button on MainActivity, or automatically when� We can use the built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results. In this tutorial, we'll review three different ways of working with map(): with a lambda function, with a user-defined function, and finally with a built-in function using

Comments
  • Hi, welcome to Stack Overflow. It is important that SO questions and snswers are easy to read, so please use standard sentence case another time. I have submitted an edit to correct it this time.