开发者

Custom Class inside Extended application class not getting recognized?

I need to create a global Arraylist consisting Instances of my custom class 'Book' to be used across the application.

So I created a file 'MyBooks.java' containing 'MyBooks' class (extending application class) in which custom class 'Book' and Arraylist 'Booklist' are defined.

In the Main Activity file 'ExampledroidActivity.java' I need to load data from server, create 'Book' instances and add these instances to the ArrayList 'BookList'.

the problem is that it doesn't seem to recognize Book class in file 'ExampledroidActivity.java'.

Can Someone plz look at the code and point out what i am doing wrong.

Code from both files is given below

MyBooks.java -

package com.dubloo.exampledroid;

import java.util.ArrayList;
import android.app.Application;

public class MyBooks extends Application {

    public class Book {

        public int No;
        public String Name;
        public String Author;
        public boolean IsAvailable;

     //  constructor
        public Book(int bookNo, String bookName, String bookAuthor, boolean bookIsAvailable) {
                    No = bookNo;
                    Name = bookName;
                    Author = bookAuthor;
                    IsAvailable = bookIsAvailable;
        }
    }

    public ArrayList<Book> BookList  = new ArrayList<Book>();

}

ExampledroidActivity.java -

package com.dubloo.exampledroid;

import android.app.Activity;
import android.os.Bundle;


public class ExampledroidActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        MyBooks someBooks = ((MyBooks)getApplicationContext());

//here I get data from a server 
//for this example generating dummy data

        for(int n=1; n<20; n++){
            String Name = "The Book" + n;
            String Author = "Blah " + n;
            boolean IsAvailable = true;

//declare here an instance of class Book - in this part book class is not recognized
//definately doing some thing wrong here

            someBooks.Book thisBook = new someBooks.Book(n, Name, Author开发者_Go百科, IsAvailable);

//add book to the Booklist Arraylist

            someBooks.BookList.add(thisBook);
        }        


}

}

If its a noob question plz bear with me, Thanks in advance,

Shobhit


A better answer could be to

  • separate you class book in another file (Book.java)
  • make the BookList private and provide accessors (setter / getter )
  • respect java naming conventions : class start by upperCase letter then camel case, variables start with lowerCase letter then camel case.
  • make your android application class a singleton.

There are some flaws in your design so far, but go on learning, Android is fun.

Regards, Stéphane


Your inner class could be static.

Regards, Stéphane

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜