Pardeep Singh
Pardeep Singh

Reputation: 422

Error in Android app while initialling array with drawable ID?

Consider:

package com.example.practicealpha;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener {
    Button next,previous;
    ImageView image;
    Integer[] id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id[0] = R.drawable.aa;
        id[1] = R.drawable.bb;
        id[2] = R.drawable.cc;
        id[3] = R.drawable.dd;

        next=(Button)findViewById(R.id.buttonNext);
        previous=(Button)findViewById(R.id.buttonPrevious);
        image=(ImageView)findViewById(R.id.imageView1);
        // image.setImageDrawable(id[0]);
        // image.setImageResource(id[i]);
        /*
            next.setOnClickListener(new Button.OnClickListener(){
                public void onClick(View v)
                {
                    if (i<=3)
                    {
                        i++;
                        image.setImageResource(id[i]);
                        if(i==4)
                            next.setEnabled(false);
                    }
                }
            });
            previous.setOnClickListener(new Button.OnClickListener(){
                public void onClick(View v)
                {
                    if(i>=1)
                    {
                        i--;
                        image.setImageResource(id[i]);
                        if(i==0)
                            next.setEnabled(false);
                    }
                }
            });
       */
    }

    @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 void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

id[0] = R.drawable.aa;

This line is causing my app to stop forcefully. How can I fix this problem?

I am trying to intialise an integer array with images id and then trying to go through the image listed in drawable folder.

Upvotes: 0

Views: 102

Answers (3)

Sush
Sush

Reputation: 3874

You cannot use the id array directly. Initialise it first:

id[0] = R.drawable.aa;

Upvotes: 0

balaji koduri
balaji koduri

Reputation: 1321

You have to initialize the ids for the size:

int[] id = new int[size];

Upvotes: 0

Nitin Misra
Nitin Misra

Reputation: 4522

Change

Integer[] id;

to

int[] id;

Upvotes: 3

Related Questions