2014-01-10 79 views
0

我试图通过无线电对话日期格式进行更改。我写了这段代码。在Android中以编程方式设置简单数据格式

builder.setSingleChoiceItems(items, load(), new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int item) { 


        switch(item) 
        { 
         case 0: 
          dataFormat = "HH/mm/ss YYYY/MM/DD"; 
          index = 0; 
          break; 
         case 1: 
          index = 1; 
          break; 
         case 2: 
          index = 2; 
          break; 
         case 3: 

          break; 

        } 
        MyClass class = new MyClass(); 
        class.setDateFormat(dataFormat); 
        savePreferences("DataFormat", item); 

        } 
       }); 

private void savePreferences(String key, int value) { 
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); 
    Editor editor = sharedPreferences.edit(); 
    editor.putInt(key, value); 
    editor.commit(); 
} 

private int load() { 
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); 
    int value = sharedPreferences.getInt("DataFormat", 0); 

    return value; 
} 

它运行良好,并正确存储值,但是当我去到其他类时,所有的都保持如前(日期格式)。在其他班级(MyClass)我已经输入密码

SimpleDateFormat dateFormat; 
String data; 

    public void setDateFormat(String data) { 

     this.data = data; 

    } 

    public SimpleDateFormat getDateFormat() { 

     if(data != null) { 
      dateFormat = new SimpleDateFormat(data); 

     } 

     else { 
      dateFormat = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy"); 

     } 

     return dateFormat; 
    } 

问题出在这里。它返回null,因为通过我看到的记录进入else语句。为什么?哪里有问题?

+0

什么是“无线电对话“? –

回答

0

我怀疑你需要对空字符串保护像这样

if (data != null && data.length() > 0) 

我做了一个完全独立的测试,像这样

SimpleDateFormat dateFormat = null; 
String data = null; 

public void setDateFormat(String data) { 
    this.data = data; 
} 

public SimpleDateFormat getDateFormat() { 
    if (data != null && data.length() > 0) { 
     dateFormat = new SimpleDateFormat(data); 
    } else { 
     dateFormat = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy"); 
    } 
    return dateFormat; 
} 

public static void main(String args[]) { 
    String date = "2014-01-20"; 
    Question ja = new Question(); // this class 
    ja.setDateFormat("yyyy-MM-dd"); 
    try { 
     System.out.println(ja.getDateFormat().parse(date)); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
} 

其输出

Mon Jan 20 00:00:00 EST 2014 
相关问题