1. Download our Official Android App: Forums for Android!

Apps TimeStamp not working correctly, when changing Activity!

Discussion in 'Android Development' started by ConzT, Mar 13, 2016.

  1. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    Hey everyone!

    Im really new to Android programming(started yesterday) and im currently working on an App that should give me the time between first time clicking a button and second time clicking the button.

    It works fine when i stay in the Activity. But if i change the activity while the time is "running" and then reenter the main activity it gives me a strange timestamp.

    How the timestamp works:

    I have a button for Start/Stop
    On clicking start it calls a Method where i get the current system time in milliseconds and saves it to a variable.
    On clicking stop it does the same and subtracts endTime-startTime. Thats how i get the time.
    (Works fine)


    But when changing activity(I got a button where it changes to an activity where i can add a customer) and reentering main and stopping the timer, it adds the totalTime up to something i cant relate to.. currently my stop time is at 45 minutes.

    Maybe i do something wrong on saving my values?

    I'll just post my code. Maybe someone can help me and give me a hint. Thanks and sorry for my bad english!

    Class "Timerecording"
    Code (Java):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Intent;
    4. import android.content.SharedPreferences;
    5. import android.os.SystemClock;
    6. import android.preference.PreferenceManager;
    7. import android.support.v7.app.AppCompatActivity;
    8. import android.os.Bundle;
    9. import android.widget.ArrayAdapter;
    10. import android.widget.Button;
    11. import android.widget.Spinner;
    12. import android.widget.TextView;
    13. import android.view.View;
    14.  
    15. import java.lang.reflect.Array;
    16. import java.sql.Time;
    17. import java.util.ArrayList;
    18. import java.util.Date;
    19. import java.util.LinkedList;
    20.  
    21.  
    22. public class ZeitErfassen extends AppCompatActivity {
    23.  
    24.     public static LinkedList<Kunde> kunden = new LinkedList();
    25.     boolean running = false;
    26.     long startTime,endTime,totalTime;
    27.     public Date date = new Date();
    28.  
    29.     private SharedPreferences app_preferences;
    30.     private SharedPreferences.Editor editor;
    31.     private static final int PREFERENCE_MODE_PRIVAT=0;
    32.     private TextView displayTime;
    33.     public Button startEndButton;
    34.  
    35.  
    36.     @Override
    37.     protected void onCreate(Bundle savedInstanceState) {
    38.         super.onCreate(savedInstanceState);
    39.         setContentView(R.layout.activity_zeit_erfassen);
    40.         //Einstellungen laden
    41.         app_preferences = getPreferences(PREFERENCE_MODE_PRIVAT);
    42.         displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
    43.         startTime= app_preferences.getLong("startTime", 0);
    44.         endTime = app_preferences.getLong("endTime", 0);
    45.         running = app_preferences.getBoolean("running", false);
    46.         totalTime = app_preferences.getLong("totalTime", 0);
    47.         displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
    48.         startEndButton = (Button)findViewById(R.id.start_Timer);
    49.         startEndButton.setText((CharSequence)app_preferences.getString("timerButton","Start Timer"));
    50.         editor = app_preferences.edit();
    51.         editor.commit();
    52.  
    53.         createDropDown();
    54.  
    55.     }
    56.  
    57.  
    58.     public void startTimer(View view) {
    59.  
    60.        
    61.  
    62.         if(running == false) {
    63.             startTime = getTime();
    64.             displayTime.setText("Zeitstoppung läuft");
    65.             editor.putString("zeitAnzeige",(String)displayTime.getText());
    66.             running = true;
    67.             editor.putBoolean("running",true);
    68.             editor.putLong("startTimer", startTime);
    69.             startEndButton.setText("End Timer");
    70.             editor.putString("timerButton", (String)startEndButton.getText());
    71.             editor.commit();
    72.  
    73.         } else {
    74.             endTime = getTime();
    75.             editor.putLong("endTime",endTime);
    76.             totalTime = endTime - startTime;
    77.             editor.putLong("totalTime",totalTime);
    78.             int hours   = (int) ((totalTime / (1000*60*60)) % 24);
    79.             int minutes = (int) ((totalTime / (1000*60)) % 60);
    80.             int seconds = (int) (totalTime / 1000) % 60;
    81.             displayTime.setText(String.valueOf(hours)+ ":"+String.valueOf(minutes)+":"+ String.valueOf(seconds));
    82.             startEndButton.setText("Start Timer");
    83.             editor.putString("timerButton",(String)startEndButton.getText());
    84.             editor.commit();
    85.             running = false;
    86.         }
    87.     }
    88.  
    89.     public void  neuerKunde(View view) {
    90.         Intent intent = new Intent(this, AddKunde.class);
    91.         startActivity(intent);
    92.     }
    93.  
    94.     public long getTime() {
    95.         long millis = System.currentTimeMillis();
    96.         return millis;
    97.     }
    98.  
    99.  
    100.     public void createDropDown() {
    101.  
    102.         if(kunden.size() > 0) {
    103.             Spinner spinner = (Spinner) findViewById(R.id.chooseCustomer);
    104.             ArrayList<String> names = new ArrayList<>();
    105.             for(Kunde k:kunden) {
    106.                 names.add(k.getName());
    107.             }
    108.             // Create an ArrayAdapter using the string array and a default spinner layout
    109.             ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
    110.  
    111.             // Specify the layout to use when the list of choices appears
    112.             adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    113.             // Apply the adapter to the spinner
    114.             spinner.setAdapter(adapter);
    115.         }
    116.     }
    117.  
    118. }
    119.  
    Class "AddCustomer"
    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Intent;
    4. import android.os.Bundle;
    5. import android.support.design.widget.FloatingActionButton;
    6. import android.support.design.widget.Snackbar;
    7. import android.support.v7.app.AppCompatActivity;
    8. import android.support.v7.widget.Toolbar;
    9. import android.view.View;
    10. import android.widget.EditText;
    11.  
    12. import java.util.LinkedList;
    13.  
    14. public class AddKunde extends AppCompatActivity {
    15.     @Override
    16.     protected void onCreate(Bundle savedInstanceState) {
    17.         super.onCreate(savedInstanceState);
    18.         setContentView(R.layout.activity_add_kunde2);
    19.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    20.         setSupportActionBar(toolbar);
    21.  
    22.         FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    23.         fab.setOnClickListener(new View.OnClickListener() {
    24.             @Override
    25.             public void onClick(View view) {
    26.                 Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
    27.                         .setAction("Action", null).show();
    28.             }
    29.         });
    30.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    31.     }
    32.  
    33.  
    34.  
    35.     public void addKunde(View view) throws Exception {
    36.         try {
    37.             EditText strings = (EditText) findViewById(R.id.customerName);
    38.             String name = strings.getText().toString();
    39.             strings = (EditText) findViewById(R.id.addressField);
    40.             String address = strings.getText().toString();
    41.             Kunde customer = new Kunde(name,address);
    42.             ZeitErfassen.kunden.add(customer);
    43.         } catch (Exception e) {
    44.             throw new Exception("Fehler in addKunde!");
    45.         }
    46.         startActivity(new Intent(this,ZeitErfassen.class));
    47.     }
    48. }
    49.  

    I just realised, maybe its because at the end of method addKunde() I start the MainActivity again?
     

    Advertisement

  2. LV426

    LV426 I say we take off and nuke this place from orbit
    Recognized Developer
    Rank:
     #12
    Points:
    1,988
    Posts:
    9,176
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    9,176
    13,681
    1,988
    Male
    Software developer
    South West of England
    You definitely do not want to restart your first activity. You have some basic misunderstanding about how sub-activities terminate, and are managed by the parent activity.
    The child activity should call finish(), not restart the parent activity

    http://developer.android.com/guide/components/activities.html
     
    ConzT likes this.
  3. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    Hey LV426,

    thanks for your answer! It works in my cas :)

    The only problem i still have ist that on starting the time, exiting the app and reentering it doesnt show the time/button correctly. But I think that i need to call an onPause(),onRestart(),... method to save the activity state. Ill find out :)
     
  4. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    So i implemented an onDestroy() method, in case i kill/close the app. In there I save the current start/stop/total- time, running and buttonstate.
    But the problem is when i hit start, close the app and start it again, it gives me a time of 3h:12m:9s , increases everytime i do that.... I dont know where this is coming from -.-
     
  5. LV426

    LV426 I say we take off and nuke this place from orbit
    Recognized Developer
    Rank:
     #12
    Points:
    1,988
    Posts:
    9,176
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    9,176
    13,681
    1,988
    Male
    Software developer
    South West of England
    Your architecture is wrong. I have never seen an app where a child activity restarts the parent. Why would you do that, the parent activity has already started.
    Follow the standard design patterns for starting and handling sub activities.
     
    ConzT likes this.
  6. LV426

    LV426 I say we take off and nuke this place from orbit
    Recognized Developer
    Rank:
     #12
    Points:
    1,988
    Posts:
    9,176
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    9,176
    13,681
    1,988
    Male
    Software developer
    South West of England
    Plus why use SharedPreferences? This isn't necessary for what you want to do, you're over complicating things.
    Simply store the time values in class variables. That will do the job if all you wish to do is calculate the time between two button clicks.
     
    ConzT likes this.
  7. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    Hey again,

    i changed my code so i wouldnt restart the parent activity anymore. I changed it to finish().

    Im using the SharedPreferences, because in case i start the timer, close the app and start the app again to end the timer i want to save the start time to calculate the end time. But this isnt working...

    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Intent;
    4. import android.content.SharedPreferences;
    5. import android.os.SystemClock;
    6. import android.preference.PreferenceManager;
    7. import android.support.v7.app.AppCompatActivity;
    8. import android.os.Bundle;
    9. import android.widget.ArrayAdapter;
    10. import android.widget.Button;
    11. import android.widget.Spinner;
    12. import android.widget.TextView;
    13. import android.view.View;
    14. import java.io.File;
    15.  
    16.  
    17.  
    18. public class ZeitErfassen extends AppCompatActivity {
    19.  
    20.     public static LinkedList<Kunde> kunden = new LinkedList();
    21.     boolean running = false;
    22.     long startTime,endTime,totalTime;
    23.  
    24.     private SharedPreferences app_preferences;
    25.     private SharedPreferences.Editor editor;
    26.     private TextView displayTime;
    27.     public Button startEndButton;
    28.  
    29.  
    30.     @Override
    31.     protected void onCreate(Bundle savedInstanceState) {
    32.         super.onCreate(savedInstanceState);
    33.         setContentView(R.layout.activity_zeit_erfassen);
    34.         //Einstellungen laden
    35.      //   app_preferences = getPreferences(PREFERENCE_MODE_PRIVAT);
    36.         app_preferences =  getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
    37.        startTime= app_preferences.getLong("startTime", 0);
    38.         endTime = app_preferences.getLong("endTime", 0);
    39.         running = app_preferences.getBoolean("running", false);
    40.         displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
    41.         displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
    42.         startEndButton = (Button)findViewById(R.id.start_Timer);
    43.         startEndButton.setText((CharSequence)app_preferences.getString("timerButton","Start Timer"));
    44.         editor = app_preferences.edit();
    45.         editor.commit();
    46.     }
    47.  
    48.     public void onDestroy() {
    49.         super.onDestroy();
    50.  
    51.         editor.putLong("startTimer", startTime);
    52.         editor.putString("zeitAnzeige", (String) displayTime.getText());
    53.         editor.putString("timerButton", (String) startEndButton.getText());
    54.         editor.putLong("endTime", endTime);
    55.         editor.putLong("totalTime", totalTime);
    56.         editor.putBoolean("running",app_preferences.getBoolean("running", false));
    57.         editor.commit();
    58.         this.finish();
    59.     }
    60.  
    61.     public void onResume() {
    62.         super.onResume();
    63.         createDropDown();
    64.     }
    65.  
    66.  
    67.     public void startTimer(View view) {
    68.         editor = app_preferences.edit();
    69.  
    70.         if(running == false) {
    71.             startTime = getTime();
    72.             displayTime.setText("Zeitstoppung läuft");
    73.             editor.putString("zeitAnzeige", (String) displayTime.getText());
    74.             running = true;
    75.             editor.putBoolean("running", true);
    76.             editor.putLong("startTimer", startTime);
    77.             startEndButton.setText("End Timer");
    78.             editor.putString("timerButton", (String)startEndButton.getText());
    79.             editor.commit();
    80.  
    81.         } else {
    82.             endTime = getTime();
    83.             editor.putLong("endTime",endTime);
    84.             totalTime = endTime - startTime;
    85.             editor.putLong("totalTime",totalTime);
    86.             int hours   = (int) ((totalTime / (1000*60*60)) % 24);
    87.             int minutes = (int) ((totalTime / (1000*60)) % 60);
    88.             int seconds = (int) (totalTime / 1000) % 60;
    89.             displayTime.setText(String.valueOf(hours)+ ":"+String.valueOf(minutes)+":"+ String.valueOf(seconds));
    90.             startEndButton.setText("Start Timer");
    91.             editor.putString("timerButton", (String) startEndButton.getText());
    92.             running = false;
    93.             editor.putBoolean("running",false);
    94.             editor.commit();
    95.  
    96.         }
    97.     }
    98.  
    99.     public void  neuerKunde(View view) {
    100.         Intent intent = new Intent(this, AddKunde.class);
    101.         startActivity(intent);
    102.     }
    103.  
    104.     public long getTime() {
    105.         long millis = System.currentTimeMillis();
    106.         return millis;
    107.     }
    108.  
    109.  
    110.     public void createDropDown() {
    111.        //File i want to use to import cusomters to list.
    112.        // File file = new File("kunden.ser");
    113.        // if(file.exists()) {
    114.        //     Kunde.importFromFile();
    115.        // }
    116.             if (kunden.size() > 0) {
    117.                 Spinner spinner = (Spinner) findViewById(R.id.chooseCustomer);
    118.                 ArrayList<String> names = new ArrayList<>();
    119.                 for (Kunde k : kunden) {
    120.                     names.add(k.getName());
    121.                 }
    122.                 // Create an ArrayAdapter using the string array and a default spinner layout
    123.                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
    124.  
    125.                 // Specify the layout to use when the list of choices appears
    126.                 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    127.                 // Apply the adapter to the spinner
    128.                 spinner.setAdapter(adapter);
    129.             }
    130.     }
    131. }
    132.  

    Code (Text):
    1.     package com.example.cmsolutions.zeiterfassung;
    2.  
    3.     import android.content.Intent;
    4.     import android.os.Bundle;
    5.     import android.support.design.widget.FloatingActionButton;
    6.     import android.support.design.widget.Snackbar;
    7.     import android.support.v7.app.AppCompatActivity;
    8.     import android.support.v7.widget.Toolbar;
    9.     import android.view.View;
    10.     import android.widget.EditText;
    11.  
    12.     import java.util.LinkedList;
    13.  
    14.     public class AddKunde extends AppCompatActivity {
    15.     @Override
    16.     protected void onCreate(Bundle savedInstanceState) {
    17.         super.onCreate(savedInstanceState);
    18.         setContentView(R.layout.activity_add_kunde2);
    19.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    20.         setSupportActionBar(toolbar);
    21.  
    22.         FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    23.         fab.setOnClickListener(new View.OnClickListener() {
    24.             @Override
    25.             public void onClick(View view) {
    26.                 Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
    27.                         .setAction("Action", null).show();
    28.             }
    29.         });
    30.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    31.     }
    32.  
    33.  
    34.  
    35.     public void addKunde(View view) throws Exception {
    36.         try {
    37.             EditText strings = (EditText) findViewById(R.id.customerName);
    38.             String name = strings.getText().toString();
    39.             strings = (EditText) findViewById(R.id.addressField);
    40.             String address = strings.getText().toString();
    41.             Kunde customer = new Kunde(name,address);
    42.             ZeitErfassen.kunden.add(customer);
    43.         } catch (Exception e) {
    44.             throw new Exception("Fehler in addKunde!");
    45.         }
    46.     //Method i want to use to export customers to file
    47.     //    Kunde.writeToFile();
    48.         finish();
    49.     }
    50. }
    51.  
     
  8. LV426

    LV426 I say we take off and nuke this place from orbit
    Recognized Developer
    Rank:
     #12
    Points:
    1,988
    Posts:
    9,176
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    9,176
    13,681
    1,988
    Male
    Software developer
    South West of England
    Is it a problem with your calculated times?
    What I would suggest is running your app in debug mode, and putting a breakpoint in your startTimer() method. Step through the code and examine the values of all variables as the code executes. This may shed some light on what is causing your problems.
     
    ConzT likes this.
  9. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    Hey LV426, thanks for the help.
    Debugging helped! The calculated time wasnt wrong but i once saved the time as startTime and once as startTimer ..... Debugging helped finding that mistakte ;-) Second Problem was, in else condition of startTimer() I forgot to save the current state of the TextView for displayTime....


    Next i want to save my Customers, stored in a LinkedList, to a .ser file, to load them on startup. Do you think its clever to write my list to a file? I read about it on the net and havent really found another option except a database...


    edit: App works fine but currently i get the following output on startup:

    Code (Text):
    1. 03-14 14:09:01.219 2531-2531/com.example.cmsolutions.zeiterfassung I/art: Not late-enabling -Xcheck:jni (already on)
    2. 03-14 14:09:01.373 2531-2531/com.example.cmsolutions.zeiterfassung W/System: ClassLoader referenced unknown path: /data/app/com.example.cmsolutions.zeiterfassung-1/lib/x86
    3. 03-14 14:09:01.506 2531-2546/com.example.cmsolutions.zeiterfassung D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
    4. 03-14 14:09:01.711 2531-2546/com.example.cmsolutions.zeiterfassung I/OpenGLRenderer: Initialized EGL, version 1.4
    5. 03-14 14:09:01.960 2531-2546/com.example.cmsolutions.zeiterfassung W/EGL_emulation: eglSurfaceAttrib not implemented
    6. 03-14 14:09:01.960 2531-2546/com.example.cmsolutions.zeiterfassung W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabeaf560, error=EGL_SUCCESS
    7. 03-14 14:09:02.247 2531-2537/com.example.cmsolutions.zeiterfassung W/art: Suspending all threads took: 10.546ms
    8. 03-14 14:09:02.252 2531-2531/com.example.cmsolutions.zeiterfassung I/Choreographer: Skipped 38 frames!  The application may be doing too much work on its main thread.
    What irritates me, is the ClassLoader referenced unknown path..
    I dont know where this i coming from and have tried find the error on debugging, commenting out most of onCreate() but it keeps showing the message. Plus what i realised is that the apk in the path varies from com.example.cmsolutions.zeiterfassung-1 and com.example.cmsolutions.zeiterfassung-2.

    I havent found out yet why this message appears and why it is changing from 1 to 2...
     
    #9 ConzT, Mar 14, 2016
    Last edited: Mar 14, 2016
    LV426 likes this.
  10. LV426

    LV426 I say we take off and nuke this place from orbit
    Recognized Developer
    Rank:
     #12
    Points:
    1,988
    Posts:
    9,176
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    9,176
    13,681
    1,988
    Male
    Software developer
    South West of England
    I would go with a database, rather than a flat file. Once you have the DB tables set up, it offers a more flexible and extensible solution.
    And also, if you do use a file, then you need some means to parse the data in that file.
     
    ConzT likes this.
  11. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    I totally forgot to come back here and have done it already with a file, because i already knew how to do it from "normal" java. But im thinking about changing it to a database. Should i start with sqlite or can i go straigth to web databases? First i'd use a local webserver(xampp for windows) and if i know how it works change it to a webserver on my network...
     
  12. LV426

    LV426 I say we take off and nuke this place from orbit
    Recognized Developer
    Rank:
     #12
    Points:
    1,988
    Posts:
    9,176
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    9,176
    13,681
    1,988
    Male
    Software developer
    South West of England
    It's up to you. If you want to administer this data from a centrally accessible database, then use a web server. If you want the app to be able to function offline without access to the remote database, then use a local sqlite database.
     
    ConzT likes this.
  13. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    Ok thanks, maybe if the app will work, my boss wants to implement it in our database, so ill go straigth to database via webservice ;-) Thanks!
     
  14. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    Heeeey..... so i have been playing aroung with a datababaseconnection via php.
    After loads of time looking for a mistake i found out that i forgot to print an Exception.. The one when trying to get the data...

    What im trying to do is call a JSON Object from the database that returns me an array of the data stored in the database.
    But the problem is that the exception says that it failed to parse the json Object because there is a <br in it. For me it sounds like this is part of an HTML tag?
    I tried debugging but as the response value has so many values i dont know what value i need to check. Besides i dont know why the JSON Object im reciving is wrong, i found a similar example on the net.


    Error:
    Code (Text):
    1. 03-15 19:34:23.201 18222-18287/com.example.cmsolutions.zeiterfassung W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xaf71a380, error=EGL_SUCCESS
    2. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err: com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    3. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:108)
    4. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:125)
    5. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err: Caused by: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    6. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
    7. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
    8. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
    9. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:103)
    10. 03-15 19:34:23.480 18222-18222/com.example.cmsolutions.zeiterfassung W/System.err:     ... 1 more
    11. 03-15 19:34:23.561 18222-18287/com.example.cmsolutions.zeiterfassung E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab790340

    PHP Codefor showCustomer
    PHP:
    1. <?php
    2.     if($_SERVER["REQUEST_METHOD"]=="POST") {
    3.     include 'connection.php';
    4.     showCustomer();
    5.     }
    6.  
    7.  
    8. function showCustomer()
    9. {
    10.     global $connect;
    11.  
    12.    
    13.    
    14.     $query = " SELECT * FROM zeiterfassung.customer;";
    15.    
    16.     $result = mysqli_query($connect,$query);
    17.     $number_of_rows = mysqli_num_rows($query);
    18.    
    19.     $temp_array = array();
    20.    
    21.     if($number_of_rows > 0) {
    22.         while($row = mysqli_fetch_assoc($result)){
    23.             $temp_array[] = $row;
    24.         }
    25.     }
    26.    
    27.     header('Content-Type: application/json');
    28.     echo json_encode(array("customers"=>$temp_array));
    29.     mysqli_close($connect);
    30. }
    31.    
    32. ?>

    Code where i call the data from database

    Code (Java):
    1. //Display customer from database
    2.         requestQueue = Volley.newRequestQueue(getApplicationContext());
    3.  
    4.         JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, ZeitErfassen.showUrl, new Response.Listener<JSONObject>() {
    5.             @Override
    6.             public void onResponse(JSONObject response) {
    7.                 try {
    8.                     JSONArray customers = response.getJSONArray("customers");
    9.                     //I know this loop doesnt make sense but it should show me at least the last enry of the array in the TextViews
    10.                     for (int i = 0; i < customers.length(); i++) {
    11.                         JSONObject customer = customers.getJSONObject(i);
    12.                         String customerName = customer.getString("customername");
    13.                         String customerAddress = customer.getString("customeraddress");
    14.                         displayCustomerName.setText(customerName);
    15.                         displayCustomerAddress.setText(customerAddress);
    16.                     }
    17.                 } catch (JSONException e) {
    18.                     e.printStackTrace();
    19.                 }
    20.             }
    21.         }, new Response.ErrorListener() {
    22.                 @Override
    23.                 public void onErrorResponse(VolleyError error) {
    24.                     error.printStackTrace();
    25.                 }
    26.             });
    27.         requestQueue.add(jsonObjectRequest);
    28.  
    29.  
    30.     }
     
  15. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    -.- found the mistake with the tool postman... mysql_num_rows expected the result... not the query -.-
    $number_of_rows = mysqli_num_rows($result);
     
  16. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    How can i tell if the connectIon to the database was established/ a Insert or select Statement was successfull? Im using a response listener. But how can i Check it if it was successfull or not? In eitler case id like to Show a Message
    thanks
     
  17. ConzT

    ConzT Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    25
    Joined:
    Mar 13, 2016

    Mar 13, 2016
    25
    1
    16
    Male
    Hey everyone.. its me again...
    Im not sure if it's ok, that i post my questions here in the comments but its concerning the same project.. If not just tell me please ;-)


    Current Status of App:
    I established a connection to da mySql Database using Volley and a local webservice.

    It works to insert my customers and time stamps to the table, but when loading times for a specific customer i get a strange result in one case. I tried debugging it but the app keeps crashing on debugging without a message. When not debugging it doesnt crash but shows weird data.

    To the problem:

    In my main activity called "ZeitErfassen" i have a button to get an overview of all customers display in a ListView.
    I create the Listview with a custom ArrayAdapter because i want to pass my objects to the next Activity where my customers are displayed.

    So onCreate of the overview of customers i create a new arraylist and fill it with all customers from my database. this list i pass to my customadapter and then set it as my adapter of the Listview.
    Now, when i click on an item, i call a php script and pass the customer_id to the query to fetch all times from database where customer_id = customer_id.


    Now the part where i get "strange" data...

    1.(Source:ZeitErfassen;Destination:AddCustomer) I create a new customer,example xyz, in the app, data gets passed to the database.
    2.(Source:ZeitErfassen;Destination:DisplayCustomer) I call my overview for all customers where the ListView is filled with data as described above. At the end ob the List I see the customer i just created,xyz.
    3.Go back to Main Activity(ZeitErfassen)
    4.(Source:ZeitErfassen;Destination:DisplayCustomer)I open the overview for all customers again, and it shows my last created user two times! so last entry, xyz, entry before last, xyz!

    After that, i can open the view as many times as i want, the customer never gets duplicated again!

    The debugger stopps after step 2.


    Now when i click on the new customers, it calls the script to fetch the times by customer_id.
    One of the xyz entrys display the correct times from database.
    The second one, i just found out, display the times where customer_id="". In the database the value for "" is 0.

    I have no clue where the second customer suddenly appears from and debugging didnt help me either -.-
    When i close the app an open it again, there ist just one entry for the user that was visible twice before closing the app. It doesnt duplicate on opening view...


    Here is my code..

    Main Activity ZeitErfassen
    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Context;
    4. import android.content.Intent;
    5. import android.content.SharedPreferences;
    6. import android.os.SystemClock;
    7. import android.preference.PreferenceManager;
    8. import android.support.v7.app.AppCompatActivity;
    9. import android.os.Bundle;
    10. import android.util.Log;
    11. import android.widget.ArrayAdapter;
    12. import android.widget.Button;
    13. import android.widget.Spinner;
    14. import android.widget.TextView;
    15. import android.view.View;
    16.  
    17. import java.io.File;
    18. import java.lang.reflect.Array;
    19. import java.sql.Time;
    20. import java.util.ArrayList;
    21. import java.util.Calendar;
    22. import java.util.Date;
    23. import java.util.LinkedList;
    24. import java.util.Map;
    25. import java.util.Set;
    26.  
    27.  
    28. public class ZeitErfassen extends AppCompatActivity {
    29.  
    30.     public static LinkedList<Kunde> kunden = new LinkedList<Kunde>();
    31.     boolean running = false;
    32.     long startTime,endTime,totalTime;
    33.  
    34.     private SharedPreferences app_preferences;
    35.     private SharedPreferences.Editor editor;
    36.     private TextView displayTime;
    37.     public Button startEndButton;
    38.     private ArrayAdapter<String> adapter;
    39.     private Spinner spinner;
    40.     public static Kunde selectedCustomer;
    41.  
    42.  
    43.  
    44.  
    45.     @Override
    46.     protected void onCreate(Bundle savedInstanceState) {
    47.         super.onCreate(savedInstanceState);
    48.         setContentView(R.layout.activity_zeit_erfassen);
    49.         //Einstellungen laden
    50.         app_preferences =  getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
    51.         startTime= app_preferences.getLong("startTime", 0);
    52.         endTime = app_preferences.getLong("endTime", 0);
    53.         running = app_preferences.getBoolean("running", false);
    54.         displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
    55.         displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
    56.         startEndButton = (Button)findViewById(R.id.start_Timer);
    57.         startEndButton.setText((CharSequence) app_preferences.getString("timerButton", "Start Timer"));
    58.         DatabaseHelper.customerFromDatabaseToList(this);
    59.         editor = app_preferences.edit();
    60.         editor.commit();
    61.     }
    62.  
    63.     public void onDestroy() {
    64.         super.onDestroy();
    65.  
    66.         editor.putLong("startTime", startTime);
    67.         editor.putString("zeitAnzeige", (String) displayTime.getText());
    68.         editor.putString("timerButton", (String) startEndButton.getText());
    69.         editor.putLong("endTime", endTime);
    70.         editor.putLong("totalTime", totalTime);
    71.         editor.putBoolean("running", app_preferences.getBoolean("running", false));
    72.         editor.commit();
    73.         this.finish();
    74.     }
    75.  
    76.     public void onResume() {
    77.         super.onResume();
    78.      //   saveCustomers();
    79.      //   createDropDown();
    80.     }
    81.  
    82.  
    83.     public void startTimer(View view) {
    84.         editor = app_preferences.edit();
    85.  
    86.         if(running == false) {
    87.             startTime = getTime();
    88.             running = true;
    89.             editor.putLong("startTime", startTime);
    90.             startEndButton.setText("End Timer");
    91.             displayTime.setText("Zeitstoppung läuft");
    92.             editor.putString("zeitAnzeige", (String) displayTime.getText());
    93.             editor.putString("timerButton", (String) startEndButton.getText());
    94.             editor.putBoolean("running", true);
    95.             editor.commit();
    96.  
    97.         } else {
    98.             setSelectedCustomer();
    99.             endTime = getTime();
    100.             editor.putLong("endTime",endTime);
    101.             totalTime = endTime - startTime;
    102.             editor.putLong("totalTime", totalTime);
    103.             displayTime.setText(formatTime(totalTime));
    104.             editor.putString("zeitAnzeige", (String) displayTime.getText());
    105.             startEndButton.setText("Start Timer");
    106.             editor.putString("timerButton", (String) startEndButton.getText());
    107.             running = false;
    108.             editor.putBoolean("running", false);
    109.             editor.commit();
    110.             DatabaseHelper.timeToDatabase(String.valueOf(selectedCustomer.getId()),formatTime(totalTime),this);
    111.         //    selectedCustomer.saveTimeToCustomer(selectedCustomer, formatTimeForCustomer(totalTime));
    112.  
    113.         }
    114.     }
    115.  
    116.     public String formatTime(Long totalTime) {
    117.         int hours   = (int) ((totalTime / (1000*60*60)) % 24);
    118.         int minutes = (int) ((totalTime / (1000*60)) % 60);
    119.         int seconds = (int) (totalTime / 1000) % 60;
    120.  
    121.         String time = (String.valueOf(hours) + ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds));
    122.         return time;
    123.     }
    124.     public String formatTimeForCustomer(Long totalTime) {
    125.         StringBuilder time = new StringBuilder();
    126.  
    127.         Calendar cal = Calendar.getInstance();
    128.         int year    = cal.get(Calendar.YEAR);
    129.         int month   = cal.get(Calendar.MONTH);
    130.         int day     = cal.get(Calendar.DAY_OF_MONTH);
    131.         time.append((String.valueOf(year) + "." + String.valueOf(month) + "." + String.valueOf(day))).append(formatTime(totalTime));
    132.         return time.toString();
    133.     }
    134.  
    135.     public void  neuerKunde(View view) {
    136.         Intent intent = new Intent(this, AddKunde.class);
    137.         startActivity(intent);
    138.     }
    139.     public void kundenÜbersicht(View view) {
    140.     //    setSelectedCustomer();
    141.         Intent intent = new Intent(this, DisplayCustomer.class);
    142.         startActivity(intent);
    143.     }
    144.  
    145.     public long getTime() {
    146.         long millis = System.currentTimeMillis();
    147.         return millis;
    148.     }
    149.  
    150.     public void setSelectedCustomer() {
    151.         if(kunden.size() > 0) {
    152.             if (spinner.getSelectedItem().toString() != null) {
    153.                 String tempCustomer = spinner.getSelectedItem().toString();
    154.                 for (Kunde k : kunden) {
    155.                     if (k.getName().equals(tempCustomer)) {
    156.                         selectedCustomer = k;
    157.                     }
    158.                 }
    159.             }
    160.         }
    161.     }
    162.  
    163.  
    164.     public void createDropDown() {
    165.         /*File file = new File(this.getFilesDir(),"kunden.ser"); NOT USED BECAUSE DATABASE WORKS
    166.         if(file.exists()) {
    167.             Kunde.importFromFile(this);
    168.         }*/
    169.             if (kunden.size() > 0) {
    170.                 spinner = (Spinner) findViewById(R.id.chooseCustomer);
    171.                 // Create an ArrayAdapter using the string array and a default spinner layout
    172.                 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DisplayCustomer.namesOfCustomers());
    173.  
    174.                 // Specify the layout to use when the list of choices appears
    175.                 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    176.                 // Apply the adapter to the spinner
    177.                 spinner.setAdapter(adapter);
    178.             }
    179.     }
    180. }
    181.  

    DisplayCustomer(Where all customers are displayed with data from Database)
    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Intent;
    4. import android.os.Bundle;
    5. import android.os.Parcelable;
    6. import android.support.design.widget.FloatingActionButton;
    7. import android.support.design.widget.Snackbar;
    8. import android.support.v7.app.AppCompatActivity;
    9. import android.support.v7.widget.Toolbar;
    10. import android.view.View;
    11. import android.widget.AdapterView;
    12. import android.widget.ArrayAdapter;
    13. import android.widget.ListView;
    14. import android.widget.TextView;
    15.  
    16.  
    17. import java.util.ArrayList;
    18.  
    19. public class DisplayCustomer extends AppCompatActivity {
    20.     CustomerAdapter customerAdapter;
    21.     public ArrayAdapter<String> adapterCustomerView;
    22.     private ListView listCustomerView;
    23.     @Override
    24.     protected void onCreate(Bundle savedInstanceState) {
    25.         super.onCreate(savedInstanceState);
    26.         setContentView(R.layout.activity_display_customer);
    27.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    28.         setSupportActionBar(toolbar);
    29.  
    30.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    31.  
    32.         ArrayList<Kunde> customerList = getCustomerObjects();
    33.         customerAdapter = new CustomerAdapter(this,customerList);
    34.         listCustomerView = (ListView)findViewById(R.id.list_View_Customers);
    35.         //  adapterCustomerView = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namesOfCustomers());
    36.         listCustomerView.setAdapter(customerAdapter);
    37.         openCustomerDetails();
    38.     }
    39.  
    40.  
    41.     public static ArrayList<String> namesOfCustomers() {
    42.         ArrayList<String> customerNames = new ArrayList<>();
    43.         if(ZeitErfassen.kunden.size() > 0 ) {
    44.             for (Kunde k : ZeitErfassen.kunden) {
    45.                 customerNames.add(k.getName());
    46.             }
    47.         }
    48.         return customerNames;
    49.     }
    50.  
    51.  
    52.     public static ArrayList<Kunde> getCustomerObjects() {
    53.         ArrayList<Kunde> customerList = new ArrayList<>();
    54.         if(ZeitErfassen.kunden.size() > 0 ) {
    55.             for (Kunde k : ZeitErfassen.kunden) {
    56.                 customerList.add(k);
    57.             }
    58.         }
    59.         return customerList;
    60.     }
    61.  
    62.  
    63.     public void openCustomerDetails() {
    64.         listCustomerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    65.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    66.                 Kunde kunde = new Kunde();
    67.                 kunde = (Kunde)listCustomerView.getItemAtPosition(position);
    68.                 Intent intent = new Intent(DisplayCustomer.this, DisplayDetailedCustomer.class);
    69.                 intent.putExtra("selectedCustomerObject",(Parcelable)kunde);
    70.                 startActivity(intent);
    71.             }
    72.         });
    73.     }
    74. }
    75.  

    My CustomerAdapter to pass data from one intent to another.
    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Context;
    4. import android.view.LayoutInflater;
    5. import android.view.View;
    6. import android.view.ViewGroup;
    7. import android.widget.ArrayAdapter;
    8. import android.widget.TextView;
    9.  
    10. import java.util.ArrayList;
    11.  
    12. /**
    13. * Created by cm.solutions on 17.03.2016.
    14. */
    15. public class CustomerAdapter extends ArrayAdapter<Kunde> {
    16.     public CustomerAdapter(Context context, ArrayList<Kunde> customerList) {
    17.         super(context,0,customerList);
    18.     }
    19.  
    20.     public View getView(int position, View convertView, ViewGroup parent) {
    21.         //Data for this position
    22.         Kunde kunde = getItem(position);
    23.         if (convertView == null) {
    24.             convertView = LayoutInflater.from(getContext()).inflate(R.layout.items_customer_layout, parent, false);
    25.         }
    26.         // Lookup view for data population
    27.         TextView tvName = (TextView) convertView.findViewById(R.id.tvCustomerName);
    28.         // Populate the data into the template view using the data object
    29.         tvName.setText(kunde.getName());
    30.  
    31.         // Return the completed view to render on screen
    32.         return convertView;
    33.     }
    34. }
    35.  
    DatabaseHelper Class
    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.app.AlertDialog;
    4. import android.content.Context;
    5. import android.widget.ArrayAdapter;
    6. import android.widget.Toast;
    7.  
    8. import com.android.volley.AuthFailureError;
    9. import com.android.volley.Request;
    10. import com.android.volley.RequestQueue;
    11. import com.android.volley.Response;
    12. import com.android.volley.VolleyError;
    13. import com.android.volley.toolbox.JsonObjectRequest;
    14. import com.android.volley.toolbox.StringRequest;
    15. import com.android.volley.toolbox.Volley;
    16.  
    17. import org.json.JSONArray;
    18. import org.json.JSONException;
    19. import org.json.JSONObject;
    20.  
    21. import java.util.ArrayList;
    22. import java.util.HashMap;
    23. import java.util.LinkedList;
    24. import java.util.Map;
    25.  
    26. /**
    27. * Created by cm.solutions on 15.03.2016.
    28. */
    29. public class DatabaseHelper {
    30.     public static RequestQueue requestQueue;
    31.     public static String host = "http://192.168.150.238/";
    32.     public static final String insertUrl = host+"insertCustomer.php";
    33.     public static final String showUrl = host+"showCustomer.php";
    34.     public static final String insertTimeUrl = host+"insertTime.php";
    35.     public static final String showTimeUrl = host+"showTimes.php";
    36.  
    37.     public static void customerFromDatabaseToList(final Context context)  {
    38.         //Display customer from database
    39.         requestQueue = Volley.newRequestQueue(context);
    40.         final ArrayList<String> customerNames = new ArrayList<>();
    41.         JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, new Response.Listener<JSONObject>() {
    42.             @Override
    43.             public void onResponse(JSONObject response) {
    44.                 try {
    45.                     JSONArray customers = response.getJSONArray("customers");
    46.                     if(customers.length() > 0) {
    47.                         for (int i = 0; i < customers.length(); i++) {
    48.                             JSONObject customer = customers.getJSONObject(i);
    49.                             String customerName = customer.getString("cus_name");
    50.                             String customerAddress = customer.getString("cus_address");
    51.                             int customerID = Integer.valueOf(customer.getString("cus_id"));
    52.                             if (customerName != null && customerAddress != null) {
    53.                                 try {
    54.                                     Kunde k = new Kunde(customerName, customerAddress, customerID);
    55.                                     if (!listContainsObject(k)) {
    56.                                         ZeitErfassen.kunden.add(k);
    57.                                     }
    58.                                 } catch (Exception e) {
    59.                                     showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
    60.                                 }
    61.                             } else {
    62.                                 showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
    63.                             }
    64.                         }
    65.                     }
    66.                 } catch (JSONException e) {
    67.                     e.printStackTrace();
    68.                 }
    69.             }
    70.         }, new Response.ErrorListener() {
    71.             @Override
    72.             public void onErrorResponse(VolleyError error) {
    73.                 error.printStackTrace();
    74.             }
    75.         });
    76.         requestQueue.add(jsonObjectRequest);
    77.     }
    78.  
    79.     public static boolean listContainsObject(Kunde cust) {
    80.         for(Kunde k : ZeitErfassen.kunden) {
    81.             if(k.getId() == cust.getId()) {
    82.                 return true;
    83.             }
    84.         }
    85.         return false;
    86.     }
    87.  
    88.     public static void timeToDatabase(final String customer_id, final String time_value, final Context context) {
    89.         requestQueue = Volley.newRequestQueue(context);
    90.         StringRequest request = new StringRequest(Request.Method.POST, DatabaseHelper.insertTimeUrl, new Response.Listener<String>() {
    91.             @Override
    92.             public void onResponse(String response) {
    93.  
    94.             }
    95.         }, new Response.ErrorListener() {
    96.             @Override
    97.             public void onErrorResponse(VolleyError error) {
    98.                 showAlert("Fehler","Fehler bei Verbindung zur Datenbank",context);
    99.             }
    100.         }) {
    101.             @Override
    102.             protected Map<String, String> getParams() throws AuthFailureError {
    103.                 Map<String,String> parameters = new HashMap<String,String>();
    104.                 parameters.put("customerid",customer_id);
    105.                 parameters.put("timevalue",time_value);
    106.                 return parameters;
    107.             }
    108.         };
    109.         requestQueue.add(request);
    110.     };
    111.  
    112.  
    113.  
    114.     public static void showAlert(String title, String message, Context context) {
    115.         // 1. Instantiate an AlertDialog.Builder with its constructor
    116.         AlertDialog.Builder builder = new AlertDialog.Builder(context);
    117.  
    118.         // 2. Chain together various setter methods to set the dialog characteristics
    119.         builder.setMessage(message)
    120.                 .setTitle(title);
    121.  
    122.         // 3. Get the AlertDialog from create()
    123.         AlertDialog dialog = builder.create();
    124.     }
    125.  
    126.  
    127.     public static ArrayList<String> timesFromDataBaseToList(final Context context,final int customer_id) {
    128.         requestQueue = Volley.newRequestQueue(context);
    129.         final String cus_id = String.valueOf(customer_id) ;
    130.         final ArrayList<String> customerTimes = new ArrayList<>();
    131.  
    132.         StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, showTimeUrl, new Response.Listener<String>() {
    133.             @Override
    134.             public void onResponse(String response) {
    135.                 try {
    136.                     JSONObject object = new JSONObject(response.toString());
    137.                     JSONArray times = object.getJSONArray("customertimes");
    138.                     if (times.length() > 0) {
    139.                         for (int i = 0; i < times.length(); i++) {
    140.                             JSONObject jsonObject = times.getJSONObject(i);
    141.                             String timeValue = jsonObject.getString("time_value");
    142.                             if (timeValue != null) {
    143.                                 customerTimes.add(timeValue);
    144.                             }
    145.                         }
    146.                     }
    147.                 } catch (JSONException e) {
    148.                     e.printStackTrace();
    149.                 }
    150.             }
    151.         }, new Response.ErrorListener() {
    152.                 @Override
    153.                 public void onErrorResponse(VolleyError error) {
    154.                     Toast.makeText(context,"Fehler beim Holen der Zeiten",Toast.LENGTH_LONG).show();
    155.                     error.printStackTrace();
    156.                 }
    157.         }){
    158.             protected Map<String, String> getParams() throws AuthFailureError {
    159.                 Map<String,String> parameters = new HashMap<String,String>();
    160.                 parameters.put("cus_id",cus_id);
    161.                 return parameters;
    162.             }
    163.         };
    164.         requestQueue.add(jsonObjectRequest);
    165.         return customerTimes;
    166.     };
    167. }
    168.  
    DisplayDetailedCustomer / Display the times
    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Intent;
    4. import android.os.Bundle;
    5. import android.support.design.widget.FloatingActionButton;
    6. import android.support.design.widget.Snackbar;
    7. import android.support.v7.app.AppCompatActivity;
    8. import android.support.v7.widget.Toolbar;
    9. import android.view.View;
    10. import android.widget.ArrayAdapter;
    11. import android.widget.ListView;
    12. import android.widget.TextView;
    13.  
    14. public class DisplayDetailedCustomer extends AppCompatActivity {
    15.  
    16.     @Override
    17.     protected void onCreate(Bundle savedInstanceState) {
    18.         super.onCreate(savedInstanceState);
    19.         setContentView(R.layout.activity_display_detailed_customer);
    20.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    21.         setSupportActionBar(toolbar);
    22.  
    23.  
    24.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    25.         Intent getCustomerParcable = getIntent();
    26.         Kunde customer = getCustomerParcable.getExtras().getParcelable("selectedCustomerObject");
    27.  
    28.         TextView displayCustomerNameDetailed =(TextView) findViewById(R.id.detailedCustomerViewName);
    29.         TextView displayCustomerAddressDetailed =(TextView) findViewById(R.id.detailedCustomerAddress);
    30.         ListView timeListView = (ListView)findViewById(R.id.detailedTimeListView);
    31.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, DatabaseHelper.timesFromDataBaseToList(this,customer.getId()));
    32.         timeListView.setAdapter(adapter);
    33.         displayCustomerNameDetailed.setText(customer.getName());
    34.         displayCustomerAddressDetailed.setText(customer.getAdresse());
    35.     }
    36.  
    37. }
    38.  


    Kunde Class / Customer Class with interface Parcelable
    Code (Text):
    1. package com.example.cmsolutions.zeiterfassung;
    2.  
    3. import android.content.Context;
    4. import android.os.Parcel;
    5. import android.os.Parcelable;
    6.  
    7. import java.io.File;
    8. import java.io.FileInputStream;
    9. import java.io.FileNotFoundException;
    10. import java.io.FileOutputStream;
    11. import java.io.IOException;
    12. import java.io.ObjectInputStream;
    13. import java.io.ObjectOutputStream;
    14. import java.io.Serializable;
    15. import java.util.ArrayList;
    16. import java.util.LinkedList;
    17. import java.util.List;
    18.  
    19. /**
    20. * Created by cm.solutions on 12.03.2016.
    21. */
    22. public class Kunde implements Serializable,Parcelable {
    23.     private String name;
    24.     private String adresse;
    25.     private int id;
    26.     public LinkedList<String> zeiten;
    27.  
    28.     public Kunde(String name, String adresse) throws Exception{
    29.         setName(name);
    30.         setAdresse(adresse);
    31.         zeiten = new LinkedList<String>();
    32.     }
    33.  
    34.     public Kunde(String name, String adresse,int id) throws Exception{
    35.         setName(name);
    36.         setAdresse(adresse);
    37.         setId(id);
    38.         zeiten = new LinkedList<String>();
    39.     }
    40.     public Kunde(){};
    41.  
    42.  
    43.     public void setId(int id) {
    44.         this.id = id;
    45.     }
    46.     public int getId(){
    47.         return id;
    48.     }
    49.     public void setName(String name) throws Exception {
    50.         if(name != null) {
    51.             this.name = name;
    52.         } else throw new Exception("Name ist ungueltig! in setName");
    53.     }
    54.  
    55.     public void setAdresse(String adresse) throws Exception{
    56.         if(adresse != null) {
    57.             this.adresse = adresse;
    58.         }else throw new Exception("Adresse ist ungueltig! in setAdresse");
    59.     }
    60.  
    61.     public String getName() {
    62.         return name;
    63.     }
    64.  
    65.     public String getAdresse() {
    66.         return adresse;
    67.     }
    68.  
    69.  
    70.     public void saveZeit(Long totalTime) {
    71.         zeiten.add(String.valueOf(totalTime));
    72.     }
    73.  
    74.  
    75.     public void saveTimeToCustomer(Kunde customer,String time){
    76.        customer.zeiten.add(time);
    77.     }
    78.  
    79.     //------------------------------------Parcelable Methods to pass Daata from one Intent to another----------------------------------------
    80.     @Override
    81.     public int describeContents() {
    82.         return 0;
    83.     }
    84.  
    85.     @Override
    86.     public void writeToParcel(Parcel dest, int flags) {
    87.         dest.writeInt(this.id);
    88.         dest.writeString(this.name);
    89.         dest.writeString(this.adresse);
    90.     //    dest.writeList(this.zeiten);
    91.     }
    92.     // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    93.     public static final Parcelable.Creator<Kunde> CREATOR = new Parcelable.Creator<Kunde>() {
    94.         public Kunde createFromParcel(Parcel in) {
    95.             return new Kunde(in);
    96.         }
    97.  
    98.         public Kunde[] newArray(int size) {
    99.             return new Kunde[size];
    100.         }
    101.     };
    102.  
    103.     // example constructor that takes a Parcel and gives you an object populated with it's values
    104.     private Kunde(Parcel in) {
    105.         LinkedList<String> zeiten = null;
    106.         id = in.readInt();
    107.         name = in.readString();
    108.         adresse = in.readString();
    109.     }
    110. }
    111.  

    If you need anything else please let me know. Thanks guys for taking your time!
     

Share This Page

Loading...