Java tutorial
/* * Travey is an open source mobile and web application for travel survey research. * For more information see <http://travey.org/>. * Copyright (C) 2015 Jonathan Stiles * * This file is part of Travey. Travey is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Travey is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Travey. * If not, see <http://www.gnu.org/licenses/>. */ package org.travey.travey; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.location.Location; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.os.Handler; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import de.greenrobot.event.EventBus; public class SurveysFragment extends Fragment implements AsyncResponse { ProgressDialog dialog; private ListView mainListView; private ArrayAdapter<String> listAdapter; DataConnection dataConnection = new DataConnection(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat readableDateFormat = new SimpleDateFormat("MMMM d, HH:mm aa"); String participantID; Boolean isRegistered; private SharedPreferences myPrefs; private SharedPreferences.Editor myPrefsEditor; ArrayList<Trip> tripList; EventBus bus = EventBus.getDefault(); View rootView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); bus.register(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_surveys, container, false); dataConnection.delegate = this; // Find the ListView resource. mainListView = (ListView) rootView.findViewById(R.id.mainListView); mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //tbd launch question activity from here Log.i("**************", "output=" + position); doQuestion(position); } }); myPrefs = getActivity().getSharedPreferences("myPrefs", getActivity().MODE_PRIVATE); isRegistered = myPrefs.getBoolean("isRegistered", false); return rootView; } @Override public void onResume() { super.onResume(); myPrefs = getActivity().getSharedPreferences("myPrefs", getActivity().MODE_PRIVATE); isRegistered = myPrefs.getBoolean("isRegistered", false); if (isRegistered) { loadTrips(); } } public void loadTrips() { if (this.isVisible() && this.getUserVisibleHint()) { dialog = new ProgressDialog(getActivity()); dialog.setMessage(getResources().getString(R.string.surveys_search)); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setIndeterminate(true); dialog.setCanceledOnTouchOutside(false); dialog.show(); timerDelayRemoveDialog(8000, dialog); } myPrefs = getActivity().getSharedPreferences("myPrefs", getActivity().MODE_PRIVATE); participantID = myPrefs.getString("participantID", ""); Resources res = getResources(); String RESTFUL_URL = res.getString(R.string.restful_url); String url = RESTFUL_URL + "?method=get-trips-no-survey&format=json&pid=" + participantID; Log.i("**************", "url=" + url); dataConnection.connect(getActivity(), url); //the rest of the action happens in processFinish(String output) } public void timerDelayRemoveDialog(long time, final ProgressDialog d) { new Handler().postDelayed(new Runnable() { public void run() { if (d.isShowing()) { TextView textView = (TextView) rootView.findViewById(R.id.textView); textView.setText(R.string.surveys_nointernet); d.dismiss(); } } }, time); } public void processFinish(String output) { //assuming success for the moment Log.i("**************", "output=" + output); //split array into usable parts try { TextView textView = (TextView) rootView.findViewById(R.id.textView); JSONObject obj = new JSONObject(output); String raw = obj.getString("data"); if (raw.equals("error")) { //no surveys Log.i("**************", "error means no surveys"); textView.setText(R.string.surveys_havenone); mainListView.setAdapter(null); } else { String[] tripsRaw = raw.split(";", -1); tripList = new ArrayList<Trip>(); ArrayList<String> tripDisplayList = new ArrayList<String>(); int i = 0; for (String s : tripsRaw) { if (s.length() > 10) { String[] tripRaw = s.split(",", -1); Date tripDate = simpleDateFormat.parse(tripRaw[6]); tripDisplayList.add("Trip ending " + dateToQuarters(tripDate)); Trip tempTrip = new Trip(); tempTrip.id = tripRaw[0]; tempTrip.origin_lat = Double.parseDouble(tripRaw[1]); tempTrip.origin_long = Double.parseDouble(tripRaw[2]); tempTrip.destination_lat = Double.parseDouble(tripRaw[3]); tempTrip.destination_long = Double.parseDouble(tripRaw[4]); tempTrip.start = simpleDateFormat.parse(tripRaw[5]); tempTrip.finish = simpleDateFormat.parse(tripRaw[6]); tripList.add(tempTrip); i++; } } if (i == 1 && (this.isVisible() && this.getUserVisibleHint()) && getActivity().getIntent().getStringExtra("fromNotify") != null) { Log.i("**************", "one question only detected"); doQuestion(0); } else if (i > 0) { Collections.reverse(tripList); Collections.reverse(tripDisplayList); textView.setText(R.string.surveys_havesome); listAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_row, tripDisplayList); mainListView.setAdapter(listAdapter); } else { textView.setText(R.string.surveys_havenone); } } } catch (Exception e) { Log.i("**************", "error:" + e.toString()); } if (dialog != null) { dialog.dismiss(); } } public void doQuestion(int i) { Intent questionIntent = new Intent(getActivity(), QuestionActivity.class); //Pass along trip data (maybe can do this better with Parcelable) questionIntent.putExtra("tripId", String.valueOf(((Trip) tripList.get(i)).id)); questionIntent.putExtra("originLatitude", String.valueOf(((Trip) tripList.get(i)).origin_lat)); questionIntent.putExtra("originLongitude", String.valueOf(((Trip) tripList.get(i)).origin_long)); questionIntent.putExtra("destinationLatitude", String.valueOf(((Trip) tripList.get(i)).destination_lat)); questionIntent.putExtra("destinationLongitude", String.valueOf(((Trip) tripList.get(i)).destination_long)); questionIntent.putExtra("distance", String.valueOf((int) getDistanceInMeters(((Trip) tripList.get(i)).origin_lat, ((Trip) tripList.get(i)).origin_long, ((Trip) tripList.get(i)).destination_lat, ((Trip) tripList.get(i)).destination_long))); questionIntent.putExtra("startTime", String.valueOf(((Trip) tripList.get(i)).start.getTime())); questionIntent.putExtra("finishTime", String.valueOf(((Trip) tripList.get(i)).finish.getTime())); Log.i("**************", "launching question"); startActivity(questionIntent); } public double getDistanceInMeters(Double lat1, Double lon1, Double lat2, Double lon2) { float[] dist = new float[1]; Location.distanceBetween(lat1, lon1, lat2, lon2, dist); return dist[0]; } public String dateToQuarters(Date d) { Calendar calendar = Calendar.getInstance(); calendar.setTime(d); int unroundedMinutes = calendar.get(Calendar.MINUTE); int mod = unroundedMinutes % 15; calendar.add(Calendar.MINUTE, mod < 8 ? -mod : (15 - mod)); return readableDateFormat.format(calendar.getTime()); } //catch Event from fragment A public void onEvent(RegistrationStatusChanged event) { loadTrips(); } }