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

Apps Spinner / ListView wont refresh after DataBase update.

Discussion in 'Android Development' started by ConzT, Mar 21, 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 new to Android Developement and currently working on my first app that should give me the time between first time clicking a button and second time clicking the button and save it to a currently selected customer.(I know there are already tons of those applications out there, but since im still learning and want an app that can be usefull for myself i decided to try [​IMG])


    To the problem:

    When my app starts, in the main activity i call a method, that requests all my "customers" from the database and stores them in a list.
    This list i use to display the customers in a ListView and a spinner.
    The spinner is also created in the main activity onCreate(). So after i get the data from the database i want to fill the spinner with this data. But it doesnt work, to show the data when starting the app.

    What doesnt work either:

    When adding a new customer in the app, the customer is saved to the database.
    then i have to open my ListView(Button: Kundenübersicht) two times till the new customers is displayed. After that, the data is also visible in the spinner.


    Heres my code:

    MainActivity(ZeitErfassen)

    Code (Java):
    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.     private static int numberOfCustomers = -1;
    42.  
    43.  
    44.  
    45.  
    46.     @Override
    47.     protected void onCreate(Bundle savedInstanceState) {
    48.         super.onCreate(savedInstanceState);
    49.         setContentView(R.layout.activity_zeit_erfassen);
    50.         //Einstellungen laden
    51.         app_preferences =  getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
    52.         startTime= app_preferences.getLong("startTime", 0);
    53.         endTime = app_preferences.getLong("endTime", 0);
    54.         running = app_preferences.getBoolean("running", false);
    55.         displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
    56.         displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
    57.         startEndButton = (Button)findViewById(R.id.start_Timer);
    58.         startEndButton.setText((CharSequence) app_preferences.getString("timerButton", "Start Timer"));
    59.         editor = app_preferences.edit();
    60.         editor.commit();
    61.     }
    62.  
    63.  
    64.     public void onDestroy() {
    65.         super.onDestroy();
    66.  
    67.         editor.putLong("startTime", startTime);
    68.         editor.putString("zeitAnzeige", (String) displayTime.getText());
    69.         editor.putString("timerButton", (String) startEndButton.getText());
    70.         editor.putLong("endTime", endTime);
    71.         editor.putLong("totalTime", totalTime);
    72.         editor.putBoolean("running", app_preferences.getBoolean("running", false));
    73.         editor.commit();
    74.         this.finish();
    75.     }
    76.  
    77.  
    78.     public void onStart() {
    79.         super.onStart();
    80.         DatabaseHelper.customerFromDatabaseToList(this);
    81.         createDropDown();
    82.         numberOfCustomers= kunden.size();
    83.     }
    84.     public void onResume() {
    85.         super.onResume();
    86.        // DatabaseHelper.customerFromDatabaseToList(this);
    87.        // createDropDown();
    88.        // numberOfCustomers = kunden.size();
    89.     }
    90.  
    91.  
    92.     public void startTimer(View view) {
    93.         editor = app_preferences.edit();
    94.  
    95.         if(running == false) {
    96.             startTime = getTime();
    97.             running = true;
    98.             editor.putLong("startTime", startTime);
    99.             startEndButton.setText("End Timer");
    100.             displayTime.setText("Zeitstoppung läuft");
    101.             editor.putString("zeitAnzeige", (String) displayTime.getText());
    102.             editor.putString("timerButton", (String) startEndButton.getText());
    103.             editor.putBoolean("running", true);
    104.             editor.commit();
    105.  
    106.         } else {
    107.             setSelectedCustomer();
    108.             endTime = getTime();
    109.             editor.putLong("endTime",endTime);
    110.             totalTime = endTime - startTime;
    111.             editor.putLong("totalTime", totalTime);
    112.             displayTime.setText(formatTime(totalTime));
    113.             editor.putString("zeitAnzeige", (String) displayTime.getText());
    114.             startEndButton.setText("Start Timer");
    115.             editor.putString("timerButton", (String) startEndButton.getText());
    116.             running = false;
    117.             editor.putBoolean("running", false);
    118.             editor.commit();
    119.             DatabaseHelper.timeToDatabase(String.valueOf(selectedCustomer.getId()),formatTime(totalTime),this);
    120.         //    selectedCustomer.saveTimeToCustomer(selectedCustomer, formatTimeForCustomer(totalTime));
    121.  
    122.         }
    123.     }
    124.  
    125.     public String formatTime(Long totalTime) {
    126.         int hours   = (int) ((totalTime / (1000*60*60)) % 24);
    127.         int minutes = (int) ((totalTime / (1000*60)) % 60);
    128.         int seconds = (int) (totalTime / 1000) % 60;
    129.  
    130.         String time = (String.valueOf(hours) + ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds));
    131.         return time;
    132.     }
    133.  
    134.     public String formatTimeForCustomer(Long totalTime) {
    135.         StringBuilder time = new StringBuilder();
    136.         Calendar cal = Calendar.getInstance();
    137.         int year    = cal.get(Calendar.YEAR);
    138.         int month   = cal.get(Calendar.MONTH);
    139.         int day     = cal.get(Calendar.DAY_OF_MONTH);
    140.         time.append((String.valueOf(year) + "." + String.valueOf(month) + "." + String.valueOf(day))).append(formatTime(totalTime));
    141.         return time.toString();
    142.     }
    143.  
    144.     public void  neuerKunde(View view) {
    145.         Intent intent = new Intent(this, AddKunde.class);
    146.         startActivity(intent);
    147.     }
    148.     public void kundenÜbersicht(View view) {
    149.     //    setSelectedCustomer();
    150.         Intent intent = new Intent(this, DisplayCustomer.class);
    151.         startActivity(intent);
    152.     }
    153.  
    154.     public long getTime() {
    155.         long millis = System.currentTimeMillis();
    156.         return millis;
    157.     }
    158.  
    159.     public void setSelectedCustomer() {
    160.         if(kunden.size() > 0) {
    161.             if (spinner.getSelectedItem().toString() != null) {
    162.                 String tempCustomer = spinner.getSelectedItem().toString();
    163.                 for (Kunde k : kunden) {
    164.                     if (k.getName().equals(tempCustomer)) {
    165.                         selectedCustomer = k;
    166.                     }
    167.                 }
    168.             }
    169.         }
    170.     }
    171.  
    172.  
    173.     public void createDropDown() {
    174.             if (kunden.size() > 0) {
    175.                 spinner = (Spinner) findViewById(R.id.chooseCustomer);
    176.                 // Create an ArrayAdapter using the string array and a default spinner layout
    177.                 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DisplayCustomer.namesOfCustomers());
    178.  
    179.                 // Specify the layout to use when the list of choices appears
    180.                 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    181.                 // Apply the adapter to the spinner
    182.                 spinner.setAdapter(adapter);
    183.             }
    184.     }
    185. }
    186.  

    DatabaseHelper Class

    Code (Java):
    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 final 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.                                     Toast.makeText(context, "Fehler in customerFromDatabaseToListn!Code:X1", Toast.LENGTH_SHORT).show();
    60.                                 }
    61.                             } else {
    62.                                 Toast.makeText(context,"Fehler in customerFromDatabaseToListn!Code:X2", Toast.LENGTH_SHORT).show();
    63.                             }
    64.                         }
    65.                     }
    66.                 } catch (JSONException e) {
    67.                     Toast.makeText(context,"Fehler bei holen der Daten!Code:X3",Toast.LENGTH_SHORT).show();
    68.                 }
    69.             }
    70.         }, new Response.ErrorListener() {
    71.             @Override
    72.             public void onErrorResponse(VolleyError error) {
    73.                 Toast.makeText(context,"Fehler beim holen der Daten!Code:X4",Toast.LENGTH_SHORT).show();
    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() >0 )&& (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.                 Toast.makeText(context,"Fehler beim holen der Daten!Code:X5",Toast.LENGTH_SHORT).show();
    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.     public static ArrayList<String> timesFromDataBaseToList(final Context context,final int customer_id) {
    113.         requestQueue = Volley.newRequestQueue(context);
    114.         final String cus_id = String.valueOf(customer_id) ;
    115.         final ArrayList<String> customerTimes = new ArrayList<>();
    116.  
    117.         StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, showTimeUrl, new Response.Listener<String>() {
    118.             @Override
    119.             public void onResponse(String response) {
    120.                 try {
    121.                     JSONObject object = new JSONObject(response.toString());
    122.                     JSONArray times = object.getJSONArray("customertimes");
    123.                     if (times.length() > 0) {
    124.                         for (int i = 0; i < times.length(); i++) {
    125.                             JSONObject jsonObject = times.getJSONObject(i);
    126.                             String timeValue = jsonObject.getString("time_value");
    127.                             if (timeValue != null) {
    128.                                 customerTimes.add(timeValue);
    129.                             }
    130.                         }
    131.                     }
    132.                 } catch (JSONException e) {
    133.                     Toast.makeText(context,"Fehler beim holen der Daten!Code:X6",Toast.LENGTH_SHORT).show();
    134.                 }
    135.             }
    136.         }, new Response.ErrorListener() {
    137.                 @Override
    138.                 public void onErrorResponse(VolleyError error) {
    139.                     Toast.makeText(context,"Fehler beim Holen der Zeiten, keine Verbindung zur Datenbank!Code: X7",Toast.LENGTH_LONG).show();
    140.                     error.printStackTrace();
    141.                 }
    142.         }){
    143.             protected Map<String, String> getParams() throws AuthFailureError {
    144.                 Map<String,String> parameters = new HashMap<String,String>();
    145.                 parameters.put("cus_id",cus_id);
    146.                 return parameters;
    147.             }
    148.         };
    149.         requestQueue.add(jsonObjectRequest);
    150.         return customerTimes;
    151.     };
    152. }
    153.  
    DisplayCustomer, where all my customers are displayed

    Code (Java):
    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.  
    AddKunde / Class for adding customer

    Code (Text):
    1.     package com.example.cmsolutions.zeiterfassung;
    2.  
    3.     import android.content.Context;
    4.     import android.os.Bundle;
    5.     import android.provider.ContactsContract;
    6.     import android.support.v7.app.AppCompatActivity;
    7.     import android.support.v7.widget.Toolbar;
    8.     import android.text.TextUtils;
    9.     import android.view.View;
    10.     import android.widget.EditText;
    11.     import android.widget.Toast;
    12.  
    13.     import com.android.volley.AuthFailureError;
    14.     import com.android.volley.Request;
    15.     import com.android.volley.RequestQueue;
    16.     import com.android.volley.Response;
    17.     import com.android.volley.VolleyError;
    18.     import com.android.volley.toolbox.StringRequest;
    19.     import com.android.volley.toolbox.Volley;
    20.  
    21.     import java.io.File;
    22.     import java.util.HashMap;
    23.     import java.util.Map;
    24.  
    25.  
    26.     public class AddKunde extends AppCompatActivity {
    27.  
    28.     public RequestQueue requestQueue;
    29.     @Override
    30.     protected void onCreate(Bundle savedInstanceState) {
    31.         super.onCreate(savedInstanceState);
    32.         setContentView(R.layout.activity_add_kunde);
    33.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    34.         setSupportActionBar(toolbar);
    35.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    36.     }
    37.  
    38.  
    39.  
    40.     public void addKunde(View view) throws Exception {
    41.         try {
    42.             EditText nameField = (EditText) findViewById(R.id.customerName);
    43.             String name = nameField.getText().toString();
    44.             EditText addressField = (EditText) findViewById(R.id.addressField);
    45.             String address = addressField.getText().toString();
    46.             if(TextUtils.isEmpty(name)){
    47.                 nameField.setError("Ungültiger Name!");
    48.                 return;
    49.             } else if(TextUtils.isEmpty(address)){
    50.                 addressField.setError("Ungültige Adresse");
    51.                 return;
    52.             } else {
    53.                 try {
    54.                     customerToDatabase(name, address);
    55.                     Kunde customer = new Kunde(name, address);
    56.                 } catch (VolleyError e) {
    57.                     Toast.makeText(this,"Fehler: Keine Verbindung zur Datenbank!",Toast.LENGTH_SHORT).show();
    58.                 }
    59.             }
    60.         } catch (Exception e) {
    61.             throw new Exception("Fehler in addKunde!");
    62.         }
    63.         finish();
    64.     }
    65.  
    66.  
    67.  
    68.         public void customerToDatabase(final String name, final String address) {
    69.             requestQueue = Volley.newRequestQueue(getApplicationContext());
    70.             StringRequest request = new StringRequest(Request.Method.POST, DatabaseHelper.insertUrl, new Response.Listener<String>() {
    71.                 @Override
    72.                 public void onResponse(String response) {
    73.  
    74.                 }
    75.             }, new Response.ErrorListener() {
    76.                 @Override
    77.                 public void onErrorResponse(VolleyError error) {
    78.                     error.printStackTrace();
    79.                 }
    80.             }) {
    81.                 @Override
    82.                 protected Map<String, String> getParams() throws AuthFailureError {
    83.                    Map<String,String> parameters = new HashMap<String,String>();
    84.                     parameters.put("customername",name);
    85.                     parameters.put("customeraddress",address);
    86.                     return parameters;
    87.                 }
    88.             };
    89.             requestQueue.add(request);
    90.         };
    91. }
    92.  

    If you need more information, please let me know!
     

    Advertisement

  2. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    So when your app starts, does the spinner have any entries in it?
    Might be worth verifying that when the application starts, this piece of code is not returning an empty list:

    Code (Text):
    1.  
    2. public static ArrayList<String> namesOfCustomers() {
    3.         ArrayList<String> customerNames = new ArrayList<>();
    4.         if(ZeitErfassen.kunden.size() > 0 ) {
    5.             for (Kunde k : ZeitErfassen.kunden) {
    6.                 customerNames.add(k.getName());
    7.             }
    8.         }
    9.         return customerNames;
    10.     }
    11.  
     
  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 response!

    No the spinner doesnt have any entries.

    The spinner should get its entries from the list "kunden".
    The list "kunden" is filled by the method customerFromDatabaseToList(). This method, i call in the main activity onCreate() but it doesnt fill the list when first calling this method.
    So the spinner wont get any data on first opening the app, because the list is empty...
     
  4. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    So is your problem that you expect the list to be populated when you initially call customerFromDatabaseToList()?

    If so, then that question can't be answered because the code is calling a remote web service which returns the data. If it returns nothing, then the problem lies on the server side, with the code which constructs and returns the data.
     
  5. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    EDIT: Video Link:
    Yes exactly, i expect it to be populated when creating the app but it doesnt...



    So a server side problem...

    This is the showCustomer.php script is use to get the information from database. It works fine when testing with Postman...

    I'll install the app on my phone to see if im facing the same problems and maybe ill take a video of it so you can see better what i mean.

    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($result);
    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. ?>
    And the connection.php

    Code (Text):
    1. <?php
    2.     define('hostname','localhost');
    3.     define('user','root');
    4.     define('password','********');
    5.     define('databaseName','zeiterfassung');
    6.  
    7.  
    8.     $connect = mysqli_connect(hostname,user,password,databaseName);
    9. ?>
    10.  
     
    #5 ConzT, Mar 22, 2016
    Last edited: Mar 22, 2016
  6. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    Looks ok to me
     
  7. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    hmm and the video?
     
  8. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    I notice in your code that you start the Activity to handle entering a new customer. But the parent activity doesn't deal with the child activity completing.

    You should be using StartActivityForResult(), and on completion, the parent activity should update the list used to populate the spinner. This is basically why you're not seeing the new customer in the spinner, you haven't updated the list used in its adapter.

    See here for information on how to use StartActivityForResult(). There's tons more stuff on this

    http://developer.android.com/training/basics/intents/result.html
     
  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 your reply!
    I tried it with startActivityForResult() and passed the new customer to the main activity. There in the onActivityResult() method, i added the new customer to my list "kunden", because the adapter is using this list to get the customer names.

    So now it shows this new customer in the spinner, !but! , it is a wrong entry, because it doesnt have an ID yet.

    I get the ID from the database, and add it to the customers when calling customerFromDatabaseToList.


    I know that the new customer has a wrong id because when opening the overview of my customers, i see the new customer twice.
    When clicking on them, i get all the times stored in the database from that customer.
    When clicking on those new customer(s) i shouldnt get any timerecords because i just created it.

    But for one of them I get all the times where customer_id="" in the database. And this is the customer I just added in the onActivityResult() method because i didnt asign any id to it...
     
  10. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    I just read about AsyncTasks. Do you think this could be a solution? Ill give it a try
     
  11. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    it didnt work... in the asynctask in the doBackground i called the method customerFromDatabaseToList() but it didnt work...
     
  12. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    I may be stating the blindingly obvious here, but if you're getting the ID from the database, why don't you insert the new customer record into the table, before re-populating the spinner?

    So the workflow would be:-

    1. User enters new customer details
    2 Details are sent to remote web server
    3 Web server returns data
    4 Your app inserts new record into the database
    5 Read all records from the database to populate the spinner
     
  13. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    Thanks, ill try it like you mentioned! I will let you know as soon as i got it ;-)

    I ran into another problem...

    I set up a public webserver with a database and install my app on the phone.

    For the internet connection i use my mobile internet connection.

    The app works fine. Its inserting customers into the database and also reciving the customers from the database to display them. It even works to insert times into the database.

    But what doesnt work is to display the times when clicking on a specific customer in the ListView.
    It just shows no data when using my mobiles internet connection.

    On the other side it works when i use my wireless lan. The mobile internet connection works(browsing and other apps), I have tried that...

    EDIT: It doesnt show any Error. If an exception is thrown it shows me a Toast msg
     
  14. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    About the workflow... I dont know the best way how to perceive it.

    1. User enters customer details - I wouldnt change anything here

    2. Details are sent to the webserver - Should i just let the Database know that I want to receive information about the highest customer ID(To insert data into db in step 5)?

    3. Web server returns data - Webserver returns the highest customer id from the database

    4. App inserts new record into database - Now insert the new user into the database with customer id+1, which the database returned.

    5. Read all records from database to populate Spinner - Should i make the adapter a custom adapter like I used for my ListView to populate the customers? I actually just need to know the names but if i create one adapter, i can use it for both, the ListView for customers and for the spinner, right?
    To create the adapter I would use a list of object "Kunde". Do you think that this is a good idea? Should i all store them in an ArrayList?

    For the performance, when adding a customer to the database, should i automaticly also add the user to my List?


    Thanks LV for taking your time to help us out here!

    EDIT: Should i continue working with Volley? Or is there a better alternative?
     
    #14 ConzT, Mar 24, 2016
    Last edited: Mar 24, 2016
  15. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    Correct, that stuff is fine

    You could do that. Your app aldready has the customer name, so all you need to know is the ID of the record inserted in the server's database.

    You can't use the same adapter for both Spinner and ListView because they use different layouts. But you can use the same ArrayList for both adapters.
     
    ConzT likes this.
  16. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    Thank you! Im on to that!

    What i thought about...
    Is it a "clever" idea to pass a context to my database methods? I mean is this the way to "do it"? Could this may be one of my mistakes why it doesnt work properly?
     
  17. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    There's no problem doing that. If you database methods need to use the context, pass it in.
     
    ConzT likes this.
  18. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    Man it works!! The spinner updates right after inserting a new customer :) Now i just need to figure out how to update it right on start of the app.
    edit: that youll have something to laugh about.. yesterday i tried to update it, with a while loop, that it should try fill my list kunden as long as its length is equal to 0 ;D Didnt work though ;-)

    To the question with the app not working correctly on my mobile phone.. Do you have any idea where that comes from?
    It's a S5 mini, when debugging the app in the emulator im using a Nexus 5, Api 23...

    Edit: Thanks again! ;-)


    Edit: It didnt work as i wanted to... im on it again
     
    #18 ConzT, Mar 24, 2016
    Last edited: Mar 24, 2016
  19. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #17
    Points:
    1,488
    Posts:
    6,732
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    6,732
    9,498
    1,488
    Male
    Software developer
    South West of England
    Yeah you're not going to get much out of a 0 length list :)
    What's the problem running it on your phone?
     
    ConzT likes this.
  20. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    On my phone, when using mobile internet, everything works fine but displaying the times from the database. I display them by clicking on a customer in my ListView, but it shows no data.

    On the other hand when using wireless lan it works and shows me the times...


    To populating the spinner.. I stilled tried to populate it with my method, customerFromDatabaseToList and i call this method after inserting the new user into the database. While debuggin i saw that the response on this request is an empty array:
    "jsonObjectRequest: "[] http://10.0.0.7/showCustomer.php 0x1e7daaac NORMAL 1"

    I just dont get why the array it returns me is once empty and then at another point of time filled with the database information. Just doesnt get into my head^^


    EDIT: I just found out that the [ ] doesnt mean that the array is empty... It shows the same on a succesfull(full arry) response.

    But what really drives me crazy is finding the data in the variables while debugging.
    A "hint" i found, and a personall success ;-), is that under requestQueue -> mWaitingRequests -> 0 -> key -> count = 34

    count = 34 must be the number of customers i should get returned...
    EDIT: It is not, there are just 24 values in my database.

    But, i searched really deep through all those variables, i didnt find any variables where it shows me the data that im getting from the database....

    I also tried to google it but i didnt get any info on that...



    EDIT2:

    In the onCreate method I fetch all my data from the database, now finally after days of debugging it I had the great Idea to log the response from the jsonobjcrequest: Whats interesting, is that the response is delivering the data, at least this it what logd says...... and i call it right before adding my customers to the list... Maybe this will help us?

    If i debug the method, it never jumps into the onreponse body... i always stepped into and it didnt show the LOG on the Android Monitor..?

    Method body of onResponse:

    Code (Java):
    1.  public void onResponse(JSONObject response) {
    2.                 try {
    3.                     String LOG ="DEBUG RESPONSE";
    4.                     Log.d(LOG, "onResponse: "+ response.toString());
    5.                     JSONArray customers = response.getJSONArray("customers");
    6.                     ZeitErfassen.kunden.removeAll(ZeitErfassen.kunden);
    7.                     if(customers.length() > 0) {
    8.                         for (int i = 0; i < customers.length(); i++) {
    9.                             JSONObject customer = customers.getJSONObject(i);
    10.                             String customerName = customer.getString("cus_name");
    11.                             String customerAddress = customer.getString("cus_address");
    12.                             int customerID = Integer.valueOf(customer.getString("cus_id"));
    13.                             if (customerName != null && customerAddress != null) {
    14.                                 try {
    15.                                     Kunde k = new Kunde(customerName, customerAddress, customerID);
    16.                                     ZeitErfassen.kunden.add(k);
    17.  
    18.                                 } catch (Exception e) { public void onResponse(JSONObject response) {
    19.                 try {
    20.                     String LOG ="DEBUG RESPONSE";
    21.                     Log.d(LOG, "onResponse: "+ response.toString());
    22.                     JSONArray customers = response.getJSONArray("customers");
    23.                     ZeitErfassen.kunden.removeAll(ZeitErfassen.kunden);
    24.                     if(customers.length() > 0) {
    25.                         for (int i = 0; i < customers.length(); i++) {
    26.                             JSONObject customer = customers.getJSONObject(i);
    27.                             String customerName = customer.getString("cus_name");
    28.                             String customerAddress = customer.getString("cus_address");
    29.                             int customerID = Integer.valueOf(customer.getString("cus_id"));
    30.                             if (customerName != null && customerAddress != null) {
    31.                                 try {
    32.                                     Kunde k = new Kunde(customerName, customerAddress, customerID);
    33.                                     ZeitErfassen.kunden.add(k);
    34.  
    35.                                 } catch (Exception e) {

    LOG
    Code (Java):
    1. 03-24 23:00:18.408 7644-7644/? I/art: Not late-enabling -Xcheck:jni (already on)
    2. 03-24 23:00:18.549 7644-7644/com.example.cmsolutions.zeiterfassung W/System: ClassLoader referenced unknown path: /data/app/com.example.cmsolutions.zeiterfassung-2/lib/x86
    3. 03-24 23:00:18.823 7644-7682/com.example.cmsolutions.zeiterfassung D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
    4. 03-24 23:00:18.832 7644-7644/com.example.cmsolutions.zeiterfassung D/DEBUG RESPONSE: onResponse: {"customers":[{"cus_id":"70","cus_name":"Kundenname","cus_address":"Adresse"},{"cus_id":"71","cus_name":"test","cus_address":"Adresse"},{"cus_id":"72","cus_name":"name","cus_address":"Adresse"},{"cus_id":"73","cus_name":"test2","cus_address":"Adresse"},{"cus_id":"74","cus_name":"Knname","cus_address":"Adresse"},{"cus_id":"75","cus_name":"e","cus_address":"Adresse"},{"cus_id":"76","cus_name":"test","cus_address":"Adresse"},{"cus_id":"77","cus_name":"testme","cus_address":"Adresse"},{"cus_id":"78","cus_name":"Kundenname","cus_address":"Adresse"},{"cus_id":"79","cus_name":"Kundenname","cus_address":"Adresse"},{"cus_id":"80","cus_name":"e","cus_address":"Adresse"},{"cus_id":"81","cus_name":"enname","cus_address":"Adresse"},{"cus_id":"82","cus_name":"Kundenname","cus_address":"Adresse"},{"cus_id":"83","cus_name":"Kundenn","cus_address":"Adresse"},{"cus_id":"84","cus_name":"\"Test\"","cus_address":"\"test"},{"cus_id":"85","cus_name":"Kundenname","cus_address":"Adresse"},{"cus_id":"86","cus_name":"Kundenname","cus_address":"Adresse"},{"cus_id":"87","cus_name":"e","cus_address":"Adresse"},{"cus_id":"88","cus_name":"Kundenname","cus_address":"Adresse"},{"cus_id":"89","cus_name":"me","cus_address":"Adresse"},{"cus_id":"90","cus_name":"Kukkjjjjjjjje","cus_address":"Adresse"},{"cus_id":"91","cus_name":"Kujjmnnname","cus_address":"Adresse"},{"cus_id":"92","cus_name":"ame","cus_address":"Adresse"},{"cus_id":"93","cus_name":"Kundenname","cus_address":"Adresse"}]}
    5. 03-24 23:00:18.893 7644-7682/com.example.cmsolutions.zeiterfassung I/OpenGLRenderer: Initialized EGL, version 1.4
    6. 03-24 23:00:18.968 7644-7682/com.example.cmsolutions.zeiterfassung W/EGL_emulation: eglSurfaceAttrib not implemented
    7. 03-24 23:00:18.968 7644-7682/com.example.cmsolutions.zeiterfassung W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabe7e0e0, error=EGL_SUCCESS
    8. 03-24 23:00:19.665 7644-7644/com.example.cmsolutions.zeiterfassung I/Choreographer: Skipped 33 frames!  The application may be doing too much work on its main thread.
     
    #20 ConzT, Mar 24, 2016
    Last edited: Mar 24, 2016
  21. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    I set another Log in the for loop in the on response.
    It even prints i so 1,2,3,4,5,6,7... .
    So there must be a problem in the add or Constructor method...

    I set a Breakpoint at the Zeiterfassen.kunden.add() method, and when its working on that method, the activity is allready visible! How can i tell the activity to wait till the method is completed?
     
    #21 ConzT, Mar 25, 2016
    Last edited: Mar 25, 2016
  22. ConzT

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

    Mar 13, 2016
    25
    1
    16
    Male
    Adding a callback worked here!

    Code (Java):
    1. public class DatabaseHelper {
    2.     public static void customerFromDatabaseToList(final Context context) {
    3.         customerFromDatabaseToList(context, null);
    4.     }
    5.  
    6.     public static void customerFromDatabaseToList(final Context context, final Runnable onSuccess)  {
    7.         //Display customer from database
    8.         requestQueue = Volley.newRequestQueue(context);
    9.         final ArrayList<String> customerNames = new ArrayList<>();
    10.         JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, new Response.Listener<JSONObject>() {
    11.             @Override
    12.             public void onResponse(JSONObject response) {
    13.                 try {
    14.                     JSONArray customers = response.getJSONArray("customers");
    15.                     if(customers.length() > 0) {
    16.                         for (int i = 0; i < customers.length(); i++) {
    17.                             JSONObject customer = customers.getJSONObject(i);
    18.                             String customerName = customer.getString("cus_name");
    19.                             String customerAddress = customer.getString("cus_address");
    20.                             int customerID = Integer.valueOf(customer.getString("cus_id"));
    21.                             if (customerName != null && customerAddress != null) {
    22.                                 try {
    23.                                     Kunde k = new Kunde(customerName, customerAddress, customerID);
    24.                                     if (!listContainsObject(k)) {
    25.                                         ZeitErfassen.kunden.add(k);
    26.                                     }
    27.                                 } catch (Exception e) {
    28.                                     showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
    29.                                 }
    30.                             } else {
    31.                                 showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
    32.                             }
    33.                         }
    34.                     }
    35.                 } catch (JSONException e) {
    36.                     e.printStackTrace();
    37.                 }
    38.  
    39.                 if (onSuccess != null)
    40.                     onSuccess.run();
    41.             }
    42.         }, new Response.ErrorListener() {
    43.             @Override
    44.             public void onErrorResponse(VolleyError error) {
    45.                 error.printStackTrace();
    46.             }
    47.         });
    48.         requestQueue.add(jsonObjectRequest);
    49.     }
    50. }
    51.  
    52. public class ZeitErfassen extends AppCompatActivity {
    53.     @Override
    54.     protected void onCreate(Bundle savedInstanceState) {
    55.         super.onCreate(savedInstanceState);
    56.         setContentView(R.layout.activity_zeit_erfassen);
    57.         //Einstellungen laden
    58.         app_preferences =  getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
    59.         startTime= app_preferences.getLong("startTime", 0);
    60.         endTime = app_preferences.getLong("endTime", 0);
    61.         running = app_preferences.getBoolean("running", false);
    62.         displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
    63.         displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
    64.         startEndButton = (Button)findViewById(R.id.start_Timer);
    65.         startEndButton.setText((CharSequence) app_preferences.getString("timerButton", "Start Timer"));
    66.         DatabaseHelper.customerFromDatabaseToList(this, new Runnable() {
    67.             @Override
    68.             public void run() {
    69.                 createDropDown();
    70.             }
    71.         });
    72.         // the list can still be populated here as well if desiered
    73.         createDropDown();
    74.         editor = app_preferences.edit();
    75.         editor.commit();
    76.     }
    77. }
     

Share This Page

Loading...