更改活动时,TimeStamp无法正常工作

时间:2016-03-13 16:57:43

标签: java android timestamp

我真的很喜欢Android编程(昨天开始),我正在开发一个应用程序,它应该给我第一次点击按钮和第二次点击按钮之间的时间。

当我留在活动中时它工作正常。但如果我改变活动,而时间是"运行"然后重新进入主要活动,它给了我一个奇怪的时间戳。

时间戳的工作原理:

我有一个开始/停止按钮 在单击开始时,它调用一个方法,我以毫秒为单位获取当前系统时间并将其保存到变量中。 单击停止时,它会执行相同操作并减去endTime-startTime。多数民众赞成我如何获得总时间。 (工作正常)

但是当改变活动时(我有一个按钮,它改变了我可以添加顾客的活动)并重新进入主要并停止计时器,它会将totalTime添加到我无法理解的东西..目前我的停留时间是45分钟。

也许我在保存我的价值观方面做错了什么?

我发布我的代码。也许有人可以帮助我并给我一个提示。谢谢,抱歉我的英文不好!

Class" Timerecording"

package com.example.cmsolutions.zeiterfassung;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.view.View;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;


public class ZeitErfassen extends AppCompatActivity {

public static LinkedList<Kunde> kunden = new LinkedList();
boolean running = false;
long startTime,endTime,totalTime;
public Date date = new Date();

private SharedPreferences app_preferences;
private SharedPreferences.Editor editor;
private static final int PREFERENCE_MODE_PRIVAT=0;
private TextView displayTime;
public Button startEndButton;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_zeit_erfassen);
    //Einstellungen laden
    app_preferences = getPreferences(PREFERENCE_MODE_PRIVAT);
    displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
    startTime= app_preferences.getLong("startTime", 0);
    endTime = app_preferences.getLong("endTime", 0);
    running = app_preferences.getBoolean("running", false);
    totalTime = app_preferences.getLong("totalTime", 0);
    displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
    startEndButton = (Button)findViewById(R.id.start_Timer);
    startEndButton.setText((CharSequence)app_preferences.getString("timerButton","Start Timer"));
    editor = app_preferences.edit();
    editor.commit();

    createDropDown();

}


public void startTimer(View view) {



    if(running == false) {
        startTime = getTime();
        displayTime.setText("Zeitstoppung läuft");
        editor.putString("zeitAnzeige",(String)displayTime.getText());
        running = true;
        editor.putBoolean("running",true);
        editor.putLong("startTimer", startTime);
        startEndButton.setText("End Timer");
        editor.putString("timerButton", (String)startEndButton.getText());
        editor.commit();

    } else {
        endTime = getTime();
        editor.putLong("endTime",endTime);
        totalTime = endTime - startTime;
        editor.putLong("totalTime",totalTime);
        int hours   = (int) ((totalTime / (1000*60*60)) % 24);
        int minutes = (int) ((totalTime / (1000*60)) % 60);
        int seconds = (int) (totalTime / 1000) % 60;
        displayTime.setText(String.valueOf(hours)+ ":"+String.valueOf(minutes)+":"+ String.valueOf(seconds));
        startEndButton.setText("Start Timer");
        editor.putString("timerButton",(String)startEndButton.getText());
        editor.commit();
        running = false;
    }
}

public void  neuerKunde(View view) {
    Intent intent = new Intent(this, AddKunde.class);
    startActivity(intent);
}

public long getTime() {
    long millis = System.currentTimeMillis();
    return millis;
}


public void createDropDown() {

    if(kunden.size() > 0) {
        Spinner spinner = (Spinner) findViewById(R.id.chooseCustomer);
        ArrayList<String> names = new ArrayList<>();
        for(Kunde k:kunden) {
            names.add(k.getName());
        }
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);

        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);
    }
}

}

类&#34; AddCusomter&#34;

    package com.example.cmsolutions.zeiterfassung;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;

import java.util.LinkedList;

public class AddKunde extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_kunde2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}



public void addKunde(View view) throws Exception {
    try {
        EditText strings = (EditText) findViewById(R.id.customerName);
        String name = strings.getText().toString();
        strings = (EditText) findViewById(R.id.addressField);
        String address = strings.getText().toString();
        Kunde customer = new Kunde(name,address);
        ZeitErfassen.kunden.add(customer);
    } catch (Exception e) {
        throw new Exception("Fehler in addKunde!");
    }
    startActivity(new Intent(this,ZeitErfassen.class));
}

}

我刚才意识到,也许是因为在方法结束时addKunde()我再次启动MainActivity?

PS:我认为我还可以改进我的编码风格。如果你有任何关于更好编码的提示(其他类的方法,......),我也很棒!谢谢!

1 个答案:

答案 0 :(得分:0)

您可以完成活动,而不是开始活动。

//startActivity(new Intent(this,ZeitErfassen.class));
finish();

检查共享pref是XML正在使用ddms存储值。

仅在您需要

时打开共享首选项
  //OnCreate

  app_preferences =  getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
  Editor editor = pref.edit();

public void startTimer(View view) { 
   SharedPreferences.Editor editor = = app_preferences.edit();
   if(running == false) { 
     startTime = getTime(); displayTime.setText("Zeitstoppung läuft");
     editor.putString("zeitAnzeige",(String)displayTime.getText()); 
     running = true; 
     editor.putBoolean("running",true); editor.putLong("startTimer", startTime);
     startEndButton.setText("End Timer");
     editor.putString("timerButton", (String)startEndButton.getText());
     editor.commit(); 
    } else { 
     endTime = getTime();
     editor.putLong("endTime",endTime); totalTime = endTime - startTime;
     editor.putLong("totalTime",totalTime);
     int hours = (int) ((totalTime / (1000*60*60)) % 24); int minutes = (int) ((totalTime / (1000*60)) % 60);
     int seconds = (int) (totalTime / 1000) % 60;
     displayTime.setText(String.valueOf(hours)+ ":"+String.valueOf(minutes)+":"+ String.valueOf(seconds));
     startEndButton.setText("Start Timer"); editor.putString("timerButton",(String)startEndButton.getText());
     editor.commit();
     running = false; 
    } 
}