0

我只得到 test30 作为输出我的失败是什么?

主要活动:

public class MainActivity extends Activity {
   ListView listview;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       listview = (ListView) findViewById(R.id.listView);

       Product[] items = {
               new Product("test1",07,07,2013),
               new Product("test2",07,07,2013),
               new Product("test3",07,07,2013),
       };

       ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this,
               android.R.layout.simple_list_item_1, items);

    listview.setAdapter(adapter);
       listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position,
                                   long id) {
               String item = ((TextView)view).getText().toString();
               Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
           }
       });
   }

   @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;
   }     
}

产品.java

public class Product {
    static String name;
    static int day;
    static int month;
    static int year;
    static String res; 

    public Product(){
        super();
    }

    public Product(String name, int day, int month, int year) {
        super();
        this.name = name;
        this.day = day;
        this.month = month;
        this.year = year;

        Calendar thatDay = Calendar.getInstance();
        thatDay.set(Calendar.DAY_OF_MONTH,this.day);
        thatDay.set(Calendar.MONTH,this.month-1); // 0-11 so 1 less
        thatDay.set(Calendar.YEAR, this.year);

        Calendar today = Calendar.getInstance();

        long diff =thatDay.getTimeInMillis()- today.getTimeInMillis(); //result in millis
        long days = diff / (24 * 60 * 60 * 1000);
            res=String.valueOf(days);
        }

    @Override
    public String toString() {
        return this.name+this.res ;
    }
}
4

2 回答 2

0

将源数组移出onCreate(). 你得到“test30”,因为你res是零。

你也不需要使用this.你做的方式。我不明白你可能想避免范围冲突,但 android 上的常见模式只是在类成员前面加上m,而不是:

static String name;

你有

static String mName;
于 2013-07-07T19:51:07.813 回答
0

你的错误是,(我从上面发布的代码中读到的)所有字段都是静态的(意味着它们每个类一次,而不是每个对象一次)。这使得你调用的构造函数onCreate变得毫无用处,因为每个产品都有一个唯一的名称,你每次都会覆盖 Product.name。

       Product[] items = {
           new Product("test1",07,07,2013), // Product.name = "test1"
           new Product("test2",07,07,2013), // Product.name = "test2"
           new Product("test3",07,07,2013), // Product.name = "test3"
       }

使您的字段非静态(并且可能是私有的)并且您的问题应该消失。

编辑1:有关静态/非静态字段的进一步阅读,请访问http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

编辑2:名称后面的零应该符合预期,因为今天和今天之间的差异为零,你应该用不同的日子进行测试;-)

于 2013-07-07T20:34:46.207 回答