为什么这个arraylist不起作用?

时间:2012-11-14 22:50:07

标签: android

以下是以下作品

package com.ahmad.actionBar;

import java.util.ArrayList;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FragMent1 extends Fragment {

    private String arry[] = { "Tofeeq", "Ahmad", "Fragment", "Example",
            "Tofeeq", "Ahmad", "Fragment", "Example" };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ListView listView = new ListView(getActivity());
        ArrayAdapter<String> array = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1);

        for (String str : arry)
            array.add(str);
        listView.setAdapter(array);
        return listView;
    }
}

但是当我尝试用字符串objetcs填充我的数组时,它不起作用

package com.ahmad.actionBar;

import java.util.ArrayList;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FragMent1 extends Fragment {

    private String bookNames[];

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ListView listView = new ListView(getActivity());
        ArrayAdapter<String> array = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1);

        bookNames= bookNames();//This doesn't work
        for (String str : bookNames)//This doesn't work
            array.add(str);
        listView.setAdapter(array);
        return listView;
    }

    private String[] bookNames(){
        SimpleBookManager testBook = new SimpleBookManager();
        for(int i=0; i < testBook.count(); i++){
        bookNames[i]= testBook.getBook(i).getTitle();
    }
        return bookNames;
    }
}

我得到以下错误NullpointeException ??

11-14 23:36:54.531: E/AndroidRuntime(1949): FATAL EXCEPTION: main
11-14 23:36:54.531: E/AndroidRuntime(1949): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ahmad.actionBar/com.ahmad.actionBar.ActionBarMain}: java.lang.NullPointerException
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.os.Looper.loop(Looper.java:137)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at java.lang.reflect.Method.invokeNative(Native Method)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at java.lang.reflect.Method.invoke(Method.java:511)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at dalvik.system.NativeStart.main(Native Method)
11-14 23:36:54.531: E/AndroidRuntime(1949): Caused by: java.lang.NullPointerException
11-14 23:36:54.531: E/AndroidRuntime(1949):     at com.ahmad.actionBar.FragMent1.bookNames(FragMent1.java:39)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at com.ahmad.actionBar.FragMent1.onCreateView(FragMent1.java:29)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.BackStackRecord.run(BackStackRecord.java:635)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.Activity.performStart(Activity.java:5017)
11-14 23:36:54.531: E/AndroidRuntime(1949):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)

这是我的SimpleBookManager类,我手动填充它,所以它不能为空。

package com.ahmad.actionBar;

import java.util.ArrayList;

public class SimpleBookManager implements BookManager {
    private ArrayList<Book> allBooks = new ArrayList<Book>();

    public ArrayList<Book> getAllBooks(){
    return  allBooks;
    }

    public int count(){
        return getAllBooks().size();
    }


    public Book getBook(int index){

        return allBooks.get(index);
    }
    public Book createBook(){
        Book book = new Book();
        allBooks.add(book);
        return book;
    }
    public void removeBook(Book book){
        allBooks.remove(book);
        //Remove instance of book
    }
    public void moveBook (int from, int to){
        Book book1 = allBooks.get(from);
        Book book2 = allBooks.get(to);
        allBooks.add(to, book1);
        allBooks.add(from, book2);

    }
    public int getMinPrice(){
    ArrayList<Integer> allPrices = getAllPrices();
    int smallestElem=allPrices.get(0);
    for(int i=0; i < allPrices.size(); i++){
         if (smallestElem > allPrices.get(i)){
             smallestElem = allPrices.get(i);
         }
      }
        return smallestElem;


    }
    public int getMaxPrice(){
        ArrayList<Integer> allPrices = getAllPrices();
        int biggestElem=allPrices.get(0);
        for(int i=0; i < allPrices.size(); i++){
             if (biggestElem < allPrices.get(i)){
                 biggestElem = allPrices.get(i);
             }
          }
            return biggestElem; 
    }
    public float getMeanPrice(){
        ArrayList<Integer> allPrices = getAllPrices();
        int total=0;
        for(int i=0; i < allPrices.size(); i++){
             total+=allPrices.get(i);
          }
            return total/allPrices.size();  

    }
    public int getTotalCost(){
        ArrayList<Integer> allPrices = getAllPrices();
        int total=0;
        for(int i=0; i < allPrices.size(); i++){
             total+=allPrices.get(i);
          }
            return total;
    }
    public void saveChanges(){
        //What to do here
    }
    private ArrayList<Integer> getAllPrices(){
        int totalElements = allBooks.size();
        ArrayList<Integer> allBookPrices = new ArrayList<Integer>();
        //loop through it
        for(int i=0; i < totalElements; i++){
          allBookPrices.add(allBooks.get(i).getPrice());
        }
        return allBookPrices;
    }

    public SimpleBookManager(){
        Book harryPotter1 = createBook();
        Book harryPotter2 = createBook();


        harryPotter1.setAuthor("JK Rowling");
        harryPotter1.setCourse("Harry Potter Kunskap");
        harryPotter1.setPrice(199);
        harryPotter1.setTitle("Harry Potter and the philosifer Stone");
        harryPotter1.setIsbn("9780590353403");

        harryPotter2.setAuthor("JK Rowling");
        harryPotter2.setCourse("Harry Potter Kunskap");
        harryPotter2.setPrice(299);
        harryPotter2.setTitle("Harry Potter and snake");
        harryPotter2.setIsbn("0439064872");
    }
}

可能与List有关,就像这个例子here一样,但我无法弄清楚我的例子中的确切语法,所以任何帮助都会非常适合。

2 个答案:

答案 0 :(得分:4)

在您的代码中,您不会初始化bookNames数组

private String[] bookNames(){
    SimpleBookManager testBook = new SimpleBookManager();
    bookNames = new String[testBook.count ()]; // this is what you should add
    for(int i=0; i < testBook.count(); i++){
        bookNames[i]= testBook.getBook(i).getTitle();
    }
    return bookNames;
}

答案 1 :(得分:2)

我没看到您初始化String[] bookNames ...

的位置
private void bookNames(){
    SimpleBookManager testBook = new SimpleBookManager();
    bookNames = new String[testBook.count()];
    for(int i=0; i < testBook.count(); i++){
        bookNames[i]= testBook.getBook(i).getTitle();
    }
}

由于bookNames是一个字段变量,您只需要自己调用:bookNames()。 如果方法和名称相同的变量有点令人困惑,请考虑给bookNames()一个更具描述性的名称。