0

I added a second activity to my perfectly working application and after that it crashes already when running. I though I did all necessary things to make it works, like cleaning project, adding reference into manifest file etc., but it still doesn't work. New activity should start after choosing imageButtonInfo. Any ideas what could be wrong?

MainActivity.java:

    package com.example.beatzlooper;

import java.io.IOException;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.os.Build;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;

public class MainActivity extends ActionBarActivity implements OnClickListener{

    /* Declarations */
    MediaPlayer mp = new MediaPlayer();
    Beat beatOne = new Beat("Unknown", "1 asdasfsdfsdfsdfsfdad", R.raw.elements6); // (author, title, id)
    Beat beatTwo = new Beat("Unknown", "2 adasdavvvzzzzfff", R.raw.beat);
    TextView labelView = (TextView) findViewById(R.id.labelView);
    Intent intent = new Intent(MainActivity.this, InfoActivity.class);

    /* ----------------------------------------------------------- */

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

//        if (savedInstanceState == null) {
//            getSupportFragmentManager().beginTransaction()
//                    .add(R.id.container, new PlaceholderFragment())
//                    .commit();
//        }

    /* Buttons */
    ImageButton btnStop = (ImageButton) findViewById(R.id.imageButtonStop);
    btnStop.setOnClickListener(this);
    ImageButton btnInfo = (ImageButton) findViewById(R.id.imageButtonInfo);
    btnInfo.setOnClickListener(this);    
    ImageButton btnExit = (ImageButton) findViewById(R.id.imageButtonExit);
    btnExit.setOnClickListener(this);
    Button btnOne = (Button) findViewById(R.id.button1);
    btnOne.setOnClickListener(this);
    Button btnTwo = (Button) findViewById(R.id.button2);
    btnTwo.setOnClickListener(this);
    /* ----------------------------------------------------------- */
    }

    public void onClick(View v) {

        switch(v.getId()) {

            case R.id.button1:
                mp.stop();
                mp.release();
                mp = null;
                mp = MediaPlayer.create(this, beatOne.id());
                mp.setLooping(true);
                labelView.setText(1 + ". " + beatTwo.author() + " - " + beatOne.title());
                labelView.setTextColor(Color.parseColor("#FFFFFF"));
                mp.start();
                break;
            case R.id.button2:
                mp.stop();
                mp.release();
                mp = null;
                mp = MediaPlayer.create(this, beatTwo.id());
                mp.setLooping(true);
                labelView.setText(2 + ". " + beatTwo.author() + " - " + beatTwo.title());
                labelView.setTextColor(Color.parseColor("#FFFFFF"));
                mp.start();
                break;
            case R.id.imageButtonStop:
                mp.stop();
                mp.release();
                mp = null;
                break;
            case R.id.imageButtonInfo:
                mp.stop();
                mp.release();
                mp = null;
                MainActivity.this.startActivity(intent);
                break;
            case R.id.imageButtonExit:
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
            default:
                return;
            }
    }           

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }
}

InfoActivity.java:

package com.example.beatzlooper;

import com.example.beatzlooper.R;
import com.example.beatzlooper.R.id;
import com.example.beatzlooper.R.layout;
import com.example.beatzlooper.R.menu;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class InfoActivity extends MainActivity {

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

//      if (savedInstanceState == null) {
//          getSupportFragmentManager().beginTransaction()
//                  .add(R.id.container, new PlaceholderFragment()).commit();
//      }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.info, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_info, container,
                    false);
            return rootView;
        }
    }
}

AndroidManifest.xml:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".InfoActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name_info" >
        </activity>
    </application>

</manifest>

activity_main.xml:

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bandanabackground"
    android:columnCount="2"
    android:orientation="horizontal" >


    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="35dp"
        android:text="2" />

    <ImageButton
        android:id="@+id/imageButtonInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="30dp"
        android:background="@drawable/buttonstyle"
        android:padding="10dp"
        android:src="@drawable/info_invert" />

    <ImageButton
        android:id="@+id/imageButtonExit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignTop="@+id/imageButtonInfo"
        android:background="@drawable/buttonstyle"
        android:padding="10dp"
        android:src="@drawable/exit_invert" />

    <ImageButton
        android:id="@+id/imageButtonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_alignTop="@+id/imageButtonInfo"
        android:background="@drawable/buttonstyle"
        android:padding="10dp"
        android:src="@drawable/stop_invert" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/labelView"
        android:layout_marginLeft="37dp"
        android:layout_marginTop="42dp"
        android:text="1" />

    <TextView
        android:id="@+id/labelView"
        android:layout_width="16dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/imageButtonExit"
        android:layout_marginTop="39dp"
        android:gravity="center" />

</RelativeLayout>

activity_info.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

</RelativeLayout>

LogCat:

    05-24 17:53:24.309: D/AndroidRuntime(18837): Shutting down VM
05-24 17:53:24.309: W/dalvikvm(18837): threadid=1: thread exiting with uncaught exception (group=0x2b542210)
05-24 17:53:24.309: E/AndroidRuntime(18837): FATAL EXCEPTION: main
05-24 17:53:24.309: E/AndroidRuntime(18837): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.beatzlooper/com.example.beatzlooper.MainActivity}: java.lang.NullPointerException
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.os.Looper.loop(Looper.java:137)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.ActivityThread.main(ActivityThread.java:4441)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at java.lang.reflect.Method.invokeNative(Native Method)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at java.lang.reflect.Method.invoke(Method.java:511)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at dalvik.system.NativeStart.main(Native Method)
05-24 17:53:24.309: E/AndroidRuntime(18837): Caused by: java.lang.NullPointerException
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.Activity.findViewById(Activity.java:1794)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at com.example.beatzlooper.MainActivity.<init>(MainActivity.java:30)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at java.lang.Class.newInstanceImpl(Native Method)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at java.lang.Class.newInstance(Class.java:1319)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
05-24 17:53:24.309: E/AndroidRuntime(18837):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
05-24 17:53:24.309: E/AndroidRuntime(18837):    ... 11 more
dawlib
  • 237
  • 2
  • 13

3 Answers3

1

First, the second Activity is declared as follows:

public class InfoActivity extends MainActivity { }

It extends the MainActivity and imports all the stuff from this Activity extension. You Should create the second Activity with its own extensions:

public class InfoActivity extends ActionBarActivity { }  

And do not attach it with another Activity.

Then, you have an initialization error, see:

at com.example.beatzlooper.MainActivity.<init>(MainActivity.java:30)  

Here are the lines which occur the issue:

TextView labelView = (TextView) findViewById(R.id.labelView);
Intent intent = new Intent(MainActivity.this, InfoActivity.class);

You should create the var and then initialize it. Also like I said in my comments, you should initialize a var for your Intent but call it inside onClick(). As follows:

// create variables
Intent intent;
TextView labelView;

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

    labelView = (TextView) findViewById(R.id.labelView);
}

// initialize intent in onClick
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.imageButtonInfo:
            intent = new Intent(MainActivity.this, InfoActivity.class);
            MainActivity.this.startActivity(intent);
            break;
    }
}
Blo
  • 11,903
  • 5
  • 45
  • 99
  • I think onCreate and subclassing has nothing to do with the trace. can refer to exception in constuctor (what we do not have in this case), and exception during variable initialization (and we have only an Intent variable here). I guess the trace and the code are not in sync. – kupsef May 24 '14 at 15:58
  • " can refer to exception in constuctor", that's not the case for `super.onCreate()`? (because MainActivity should be abstract to deal with child activities) – Blo May 24 '14 at 16:02
  • onCreate is a simple function, not a constructor. Inheritance between Activites should be fine, that is why onCreate is generated with protected by default. – kupsef May 24 '14 at 16:06
  • 1
    Indeed, you're right this is an issue as you said. I'll update my answer. Thanks @kupsef. – Blo May 24 '14 at 16:07
0

Try to make your variable(s) or object(s) local as much as possible if you are using it only once. Cut this line of code from top - Intent intent = new Intent(MainActivity.this, InfoActivity.class); and paste it before start(intent); . May be this will work.

And one question why are you extending InfoActivity with MainActivity by this your InfoActivity becomes child class of parent class i.e. Main activity . I have seen this thing first time from your code, never done it by myself . May be this is the cause of crash. Try to extend your InfoActivity with Activity or ActionBarActivity class.

DanishKhan
  • 11
  • 6
  • That extension was what I saw in one of the SO threads. I fixed it to ActionBarActivity again. You're right - this Intent object has to be in local function. Also I moved "TextView labelView = (TextView) indViewById(R.id.labelView);" into onClick() function. Works perfectly now. – dawlib May 24 '14 at 16:51
0
Intent intent = new Intent(MainActivity.this, InfoActivity.class);

You cannot access the static this variable during the initialization of the object. You should create that intent in the onCreate() method.

at com.example.beatzlooper.MainActivity.<init>(MainActivity.java:30)

This line suggest that the problem is in the initialization of the object. You should analize the trace always, most of the time it tells you the cause of the problem.

UPDATE:

You deleted the critical part from your code:)

TextView labelView = (TextView) findViewById(R.id.labelView);

Of course, you should not access public methods of the object before the initialization. Move that to onCreate() also.

kupsef
  • 3,357
  • 1
  • 21
  • 31