【问题标题】:call public String from other class从其他类调用公共字符串
【发布时间】:2013-10-28 11:47:33
【问题描述】:

我尝试获取带时间的字符串 (hh:mm:ss) 但我收到此错误:

     10-28 12:35:27.682: E/AndroidRuntime(14002): java.lang.NullPointerException

我的主班叫这个:

private TimeUpdater timeupdater;
.
.
.
private Runnable runnable = new Runnable(){ 

    public void run() {

        datasource = new DataSource(getBaseContext());
        datasource.open();

        comment = datasource.getComment("1");
        data = comment.toString().split(" ");



        /*for(int i=0;i<11;i++)
        {

            dataUpdate[i]=data[i+1];
            System.out.println("U " + dataUpdate[i]);
            System.out.println("D " + data[i+1]);
        }*/

        String a = timeupdater.upTime(dane[5]);

        System.out.println(a);

        time.setText(timeupdater.upTime(dane[5]));
        //for(int i=0;i<12;i++)
            //System.out.println(dane[i]);



        handler.postDelayed(this, 1000);
    }
};

内部数据[5]是00:00:00
这是我的时间更新课程:

public class TimeUpdater {

private int hh, mm, ss;
private String time;
private String shh, smm, sss;
public String upTime(String time) {

    String[] czas = time.split(":");
    hh = Integer.parseInt(czas[0]);
    mm = Integer.parseInt(czas[1]);
    ss = Integer.parseInt(czas[2]);
    if(ss<60)
        ss++;
    if(ss==60)
    {
        ss=0;
        mm++;
    }
    if(mm==60)
        hh++;
    if(hh<10)
        shh = "0"+hh;
    if(mm<10)
        smm = "0"+mm;
    if(ss<10)
        sss = "0"+ss;
    this.time = shh + ":" + smm + ":" + sss;
    System.out.println(time);
    return this.time;
}

我需要,因为以后我想做更多的电话。我需要知道如何在其他类中创建公共字符串以每秒更改数据

【问题讨论】:

  • 你是如何实例化 TimeUpdater 的?您可以在 String time = timeupdater.upTime(data[5]) 之前发布代码吗?
  • 旁注:使用SimpleDateFormat
  • @Raghav 我更新我的帖子

标签: java android class


【解决方案1】:

调用upTime方法时,需要先实例化其参数(time),然后再调用该方法。

这是发生异常的地方

String[] czas = time.split(":");

现在由于 time 没有被实例化,你得到的是NullPointerException

【讨论】:

    【解决方案2】:

    试试下面的方法,

    String time = timeupdater.upTime(data[5].toString());
    

    您的方法 upTime() 需要传递一个字符串参数。您的 data[] 数组可能是 String 类型,但为了防止错误,建议使用 .toString() 方法。

    【讨论】:

    • 在定时器之前的主类中,我使用私有 TimeUpdater timeupdater;在计时器中,我通过 timeupdater.upTime(dane[5]) 和所有 TimeUpdater 类调用这个类,你可以在我的帖子中看到
    • 尝试将其设为静态,然后检查结果。
    • String a = timeupdater.upTime(dane[5]); 中再次出现同样的问题
    【解决方案3】:

    我通过添加解决了我的问题

     timeupdater = new TimeUpdater();
    

    之前

     String a = timeupdater.upTime(dane[5]);
    

    感谢您尝试帮助我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2011-10-24
      • 2017-05-08
      相关资源
      最近更新 更多