I have been following a tutorial (http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/) in order to make a listview display nearest restaurant to your location in radius of 5km.
However i keep getting an error, in my Runnable it says that the status variable is null. I don't really understand why this error pops up. Can you guys give me a short explanation and help find a solution??
PlacesList.java
public class PlacesList implements Serializable {
public String status;
public List<Place> results;
}
DisplayLocations.java
public class DisplayLocations extends Activity {
boolean isInternetPresent = false;
ConnectionDetector cd;
GooglePlaces googlePlaces;
PlacesList nearPlaces;
GPSTracker gps;
Button shownOnMap;
ProgressDialog pDialog;
ListView lv;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
public static String KEY_REFERENCE = "reference";
public static String KEY_NAME = "name";
public static String KEY_VICINITY = "vicinity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_locations);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(!isInternetPresent){
Toast.makeText(getApplicationContext(), "Get a working connection", Toast.LENGTH_SHORT).show();
return;
}
gps = new GPSTracker(DisplayLocations.this);
if(gps.canGetLocation()){
}else{
gps.showSettingsAlert();
}
lv = (ListView)findViewById(R.id.list);
shownOnMap = (Button)findViewById(R.id.btn_show_map);
new LoadPlaces().execute();
shownOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Intent i = new Intent(getApplicationContext(), PlacesMapActivity.class);
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
i.putExtra("near_places", nearPlaces);
startActivity(i);
*/
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String reference = ((TextView) findViewById(R.id.reference)).getText().toString();
/*
Intent in = new Intent(getApplicationContext(), SingePlaceActivity.class);
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
*/
}
});
}
class LoadPlaces extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayLocations.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
googlePlaces = new GooglePlaces();
try{
String types = "cafe|restaurant";
double radius = 5000;
nearPlaces = googlePlaces.search(gps.getLatitude(), gps.getLongitude(), radius, types);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
String status = nearPlaces.status;
if (status.equals("OK")){
if(nearPlaces.results != null){
for (Place p : nearPlaces.results){
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name);
placesListItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(DisplayLocations.this, placesListItems, R.layout.location_listview_item,
new String[]{KEY_REFERENCE, KEY_NAME}, new int[]{R.id.reference, R.id.name});
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
Toast.makeText(getApplicationContext(), "No Results", Toast.LENGTH_SHORT);
}
else if(status.equals("UNKNOWN_ERROR"))
{
Toast.makeText(getApplicationContext(), "Unknown error", Toast.LENGTH_SHORT);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
Toast.makeText(getApplicationContext(), "Query limit reached !", Toast.LENGTH_SHORT);
}
else if(status.equals("REQUEST_DENIED"))
{
Toast.makeText(getApplicationContext(), "Request denied", Toast.LENGTH_SHORT);
}
else if(status.equals("INVALID_REQUEST"))
{
Toast.makeText(getApplicationContext(), "Invalid request", Toast.LENGTH_SHORT);
}
else
{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_locations, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
GooglePlaces.java
public class GooglePlaces {
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private final String API_KEY = "AIzaSyCxY1X7hC7SOab7V3GbWd1u42fGThgYOhg";
//GooglePlaces search URL
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";
private double mLatitiude;
private double mLongitude;
private double mRadius;
public PlacesList search(double latitude, double longitude, double radius, String types) throws Exception{
this.mLatitiude = latitude;
this.mLongitude = longitude;
this.mRadius = radius;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", mLatitiude + "," + mLongitude);
request.getUrl().put("radius", mRadius); // in meters
request.getUrl().put("sensor", "false");
if (types != null)
request.getUrl().put("types", types);
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
public PlaceDetails getPlaceDetails(String reference) throws Exception{
try{
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
request.getUrl().put("reference", reference);
request.getUrl().put("key", API_KEY);
request.getUrl().put("sensor",false);
PlaceDetails place = request.execute().parseAs(PlaceDetails.class);
return place;
}catch (HttpResponseException e){
throw e;
}
}
public static HttpRequestFactory createRequestFactory(final HttpTransport transport){
return transport.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setUserAgent("Application Test");
request.setHeaders(httpHeaders);
JsonObjectParser parser = new JsonObjectParser(new JsonFactory() {
#Override
public JsonParser createJsonParser(InputStream in) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(InputStream in, Charset charset) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(String value) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(Reader reader) throws IOException {
return null;
}
#Override
public JsonGenerator createJsonGenerator(OutputStream out, Charset enc) throws IOException {
return null;
}
#Override
public JsonGenerator createJsonGenerator(Writer writer) throws IOException {
return null;
}
});
request.setParser(parser);
}
});
}
}
Line 132 of DisplayLocations.java is :
String status = nearPlaces.status;
This is the stacktrace :
java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.example.dell.exampleapplication.PlacesList.status' on a null object reference
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces$1.run(DisplayLocations.java:132)
at android.app.Activity.runOnUiThread(Activity.java:5517)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:129)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:98)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Any help and explanation would be appreciated.
Thanks, have a nice day.
EDIT:
nearPlaces.status = ... (the status: probably from GooglePlaces) in doInBackGround
then you can do:
String status = nearPlaces.status; in onPostExecute
Add the line
#Override
protected String doInBackground(String... params) {
googlePlaces = new GooglePlaces();
try{
String types = "cafe|restaurant";
double radius = 5000;
nearPlaces = googlePlaces.search(gps.getLatitude(), gps.getLongitude(), radius, types);
nearPlaces.status = "OK"; //Add this line for testing, your code should work now, because status is not NULL anymore.
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Related
I keep getting an an error when trying to call WowZa GoCoder SDK's PlayerActivity and I am unable to understand the cause. The error appears when mStreamPlayerView.play(mStreamPlayerConfig, statusCallback) is called. Would really appreciate help on where i am going wrong
vodFragment.java
public class vodFragment extends Fragment {
private int mColumnCount = 1;
ListView videoView;
ArrayList <Vidoes> videoList;
private static String value;
String videoName;
String url = "http://192.168.43.149/twende/channelVOD.php";
public vodFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().setTitle(value);
}
View view = inflater.inflate(R.layout.fragment_vod_list, container, false);
videoView = (ListView) view.findViewById(R.id.listView);
videoList = new ArrayList<Vidoes>();
JSONObject channelInfo = new JSONObject();
try {
channelInfo.put("channelName", value);
channelInfo.put("channelOwner", "dan");
postJSONObject(url,channelInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return view;
}
public static void setChannel(String channel){
value = channel;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void postJSONObject(final String myurl, final JSONObject parameters) {
class postJSONObject extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoVodView(s);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
HttpURLConnection conn = null;
try {
StringBuffer response = null;
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("responseCode" + responseCode);
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
postJSONObject postJSONObject = new postJSONObject();
postJSONObject.execute();
}
private void loadIntoVodView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
final String[] videos = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
videos[i] = removeExtension(obj.getString("title"));
Vidoes vidoe = new Vidoes();
vidoe.setTitle(videos[i]);
videoList.add(vidoe);
}
VideoListAdapter adapter = new VideoListAdapter(getActivity(), R.layout.vodparsedata, videoList);
videoView.setAdapter(adapter);
videoView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
videoName = Arrays.asList(videos).get(position);
Intent intent = new Intent(getActivity(), PlayerActivity.class);
String message = videoName+".mp4";
intent.putExtra("videoName", message);
startActivity(intent);
System.out.println("arr: " + Arrays.asList(videos).get(position));
}
});
}
public static String removeExtension(String fileName) {
if (fileName.indexOf(".") > 0) {
return fileName.substring(0, fileName.lastIndexOf("."));
} else {
return fileName;
}
}
}
PlayerActivity.java
public class PlayerActivity extends GoCoderSDKActivityBase {
final private static String TAG = PlayerActivity.class.getSimpleName();
String videoName;
private WOWZPlayerView mStreamPlayerView = null;
private WOWZPlayerConfig mStreamPlayerConfig = new WOWZPlayerConfig();
private MultiStateButton mBtnPlayStream = null;
private MultiStateButton mBtnSettings = null;
private MultiStateButton mBtnMic = null;
private MultiStateButton mBtnScale = null;
private SeekBar mSeekVolume = null;
private ProgressDialog mBufferingDialog = null;
private StatusView mStatusView = null;
private TextView mHelp = null;
private TimerView mTimerView = null;
private ImageButton mStreamMetadata = null;
private boolean mUseHLSPlayback = false;
private WOWZPlayerView.PacketThresholdChangeListener packetChangeListener = null;
private VolumeChangeObserver mVolumeSettingChangeObserver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_player);
mRequiredPermissions = new String[]{};
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
videoName= null;
} else {
videoName= extras.getString("videoName");
}
} else {
videoName= (String) savedInstanceState.getSerializable("videoName");
}
System.out.print(videoName);
mStreamPlayerConfig.setIsPlayback(true);
mStreamPlayerConfig.setHostAddress("192.168.43.149");
mStreamPlayerConfig.setApplicationName("Dark Souls 2 Channel");
mStreamPlayerConfig.setStreamName(videoName);
mStreamPlayerConfig.setPortNumber(1935);
mStreamPlayerView = (WOWZPlayerView) findViewById(R.id.vwStreamPlayer);
mBtnPlayStream = (MultiStateButton) findViewById(R.id.ic_play_stream);
mBtnSettings = (MultiStateButton) findViewById(R.id.ic_settings);
mBtnMic = (MultiStateButton) findViewById(R.id.ic_mic);
mBtnScale = (MultiStateButton) findViewById(R.id.ic_scale);
mTimerView = (TimerView) findViewById(R.id.txtTimer);
mStatusView = (StatusView) findViewById(R.id.statusView);
mStreamMetadata = (ImageButton) findViewById(R.id.imgBtnStreamInfo);
mHelp = (TextView) findViewById(R.id.streamPlayerHelp);
mSeekVolume = (SeekBar) findViewById(R.id.sb_volume);
WOWZStatusCallback statusCallback = new StatusCallback();
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
mTimerView.setVisibility(View.GONE);
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
if (sGoCoderSDK != null) {
/*
Packet change listener setup
*/
final PlayerActivity activity = this;
packetChangeListener = new WOWZPlayerView.PacketThresholdChangeListener() {
#Override
public void packetsBelowMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have fallen below threshold "+packetCount+"... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have fallen below threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void packetsAboveMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have risen above threshold "+packetCount+" ... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have risen above threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
};
mStreamPlayerView.setShowAllNotificationsWhenBelowThreshold(false);
mStreamPlayerView.setMinimumPacketThreshold(20);
mStreamPlayerView.registerPacketThresholdListener(packetChangeListener);
///// End packet change notification listener
mTimerView.setTimerProvider(new TimerView.TimerProvider() {
#Override
public long getTimecode() {
return mStreamPlayerView.getCurrentTime();
}
#Override
public long getDuration() {
return mStreamPlayerView.getDuration();
}
});
mSeekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(progress);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// listen for volume changes from device buttons, etc.
mVolumeSettingChangeObserver = new VolumeChangeObserver(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mVolumeSettingChangeObserver);
mVolumeSettingChangeObserver.setVolumeChangeListener(new VolumeChangeObserver.VolumeChangeListener() {
#Override
public void onVolumeChanged(int previousLevel, int currentLevel) {
if (mSeekVolume != null)
mSeekVolume.setProgress(currentLevel);
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(currentLevel);
}
}
});
mBtnScale.setState(mStreamPlayerView.getScaleMode() == WOWZMediaConfig.FILL_VIEW);
// The streaming player configuration properties
mStreamPlayerConfig = new WOWZPlayerConfig();
mBufferingDialog = new ProgressDialog(this);
mBufferingDialog.setTitle(R.string.status_buffering);
mBufferingDialog.setMessage(getResources().getString(R.string.msg_please_wait));
mBufferingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
cancelBuffering(dialogInterface);
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onMetaData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
String meta = "";
if(eventParams!=null)
meta = eventParams.toString();
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+meta);
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onStatus", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+eventParams.toString());
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onTextData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> "+eventName+" = "+eventParams.get("text"));
return null;
}
});
} else {
mHelp.setVisibility(View.GONE);
mStatusView.setErrorMessage(WowzaGoCoder.getLastError().getErrorDescription());
}
}
#Override
protected void onDestroy() {
if (mVolumeSettingChangeObserver != null)
getApplicationContext().getContentResolver().unregisterContentObserver(mVolumeSettingChangeObserver);
super.onDestroy();
}
/**
* Android Activity class methods
*/
#Override
protected void onResume() {
super.onResume();
syncUIControlState();
}
#Override
protected void onPause() {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
// Wait for the streaming player to disconnect and shutdown...
mStreamPlayerView.getCurrentStatus().waitForState(WOWZState.IDLE);
}
super.onPause();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public boolean isPlayerConfigReady()
{
return false;
}
/*
Click handler for network pausing
*/
public void onPauseNetwork(View v)
{
Button btn = (Button)findViewById(R.id.pause_network);
if(btn.getText().toString().trim().equalsIgnoreCase("pause network")) {
WOWZLog.info("Pausing network...");
btn.setText("Unpause Network");
mStreamPlayerView.pauseNetworkStack();
}
else{
WOWZLog.info("Unpausing network... btn.getText(): "+btn.getText());
btn.setText("Pause Network");
mStreamPlayerView.unpauseNetworkStack();
}
}
/**
* Click handler for the playback button
*/
public void onTogglePlayStream(View v) {
if (mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
} else if (mStreamPlayerView.isReadyToPlay()) {
if(!this.isNetworkAvailable()){
displayErrorDialog("No internet connection, please try again later.");
return;
}
// if(!this.isPlayerConfigReady()){
// displayErrorDialog("Please be sure to include a host, stream, and application to playback a stream.");
// return;
// }
mHelp.setVisibility(View.GONE);
WOWZStreamingError configValidationError = mStreamPlayerConfig.validateForPlayback();
if (configValidationError != null) {
mStatusView.setErrorMessage(configValidationError.getErrorDescription());
} else {
// Set the detail level for network logging output
mStreamPlayerView.setLogLevel(mWZNetworkLogLevel);
// Set the player's pre-buffer duration as stored in the app prefs
float preBufferDuration = GoCoderSDKPrefs.getPreBufferDuration(PreferenceManager.getDefaultSharedPreferences(this));
mStreamPlayerConfig.setPreRollBufferDuration(preBufferDuration);
// Start playback of the live stream
mStreamPlayerView.play(mStreamPlayerConfig, this);
}
}
}
/**
* WOWZStatusCallback interface methods
*/
#Override
public synchronized void onWZStatus(WOWZStatus status) {
final WOWZStatus playerStatus = new WOWZStatus(status);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
WOWZStatus status = new WOWZStatus(playerStatus.getState());
switch(playerStatus.getState()) {
case WOWZPlayerView.STATE_PLAYING:
// Keep the screen on while we are playing back the stream
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mStreamPlayerConfig.getPreRollBufferDuration() == 0f) {
mTimerView.startTimer();
}
// Since we have successfully opened up the server connection, store the connection info for auto complete
GoCoderSDKPrefs.storeHostConfig(PreferenceManager.getDefaultSharedPreferences(PlayerActivity.this), mStreamPlayerConfig);
// Log the stream metadata
WOWZLog.debug(TAG, "Stream metadata:\n" + mStreamPlayerView.getMetadata());
break;
case WOWZPlayerView.STATE_READY_TO_PLAY:
// Clear the "keep screen on" flag
WOWZLog.debug(TAG, "STATE_READY_TO_PLAY player activity status!");
if(playerStatus.getLastError()!=null)
displayErrorDialog(playerStatus.getLastError());
playerStatus.clearLastError();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mTimerView.stopTimer();
break;
case WOWZPlayerView.STATE_PREBUFFERING_STARTED:
WOWZLog.debug(TAG, "Dialog for buffering should show...");
showBuffering();
break;
case WOWZPlayerView.STATE_PREBUFFERING_ENDED:
WOWZLog.debug(TAG, "Dialog for buffering should stop...");
hideBuffering();
// Make sure player wasn't signaled to shutdown
if (mStreamPlayerView.isPlaying()) {
mTimerView.startTimer();
}
break;
default:
break;
}
syncUIControlState();
}
});
}
#Override
public synchronized void onWZError(final WOWZStatus playerStatus) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
displayErrorDialog(playerStatus.getLastError());
syncUIControlState();
}
});
}
public void onToggleMute(View v) {
mBtnMic.toggleState();
if (mStreamPlayerView != null)
mStreamPlayerView.mute(!mBtnMic.isOn());
mSeekVolume.setEnabled(mBtnMic.isOn());
}
public void onToggleScaleMode(View v) {
int newScaleMode = mStreamPlayerView.getScaleMode() == WOWZMediaConfig.RESIZE_TO_ASPECT ? WOWZMediaConfig.FILL_VIEW : WOWZMediaConfig.RESIZE_TO_ASPECT;
mBtnScale.setState(newScaleMode == WOWZMediaConfig.FILL_VIEW);
mStreamPlayerView.setScaleMode(newScaleMode);
}
public void onStreamMetadata(View v) {
WOWZDataMap streamMetadata = mStreamPlayerView.getMetadata();
WOWZDataMap streamStats = mStreamPlayerView.getStreamStats();
// WOWZDataMap streamConfig = mStreamPlayerView.getStreamConfig().toDataMap();
WOWZDataMap streamConfig = new WOWZDataMap();
WOWZDataMap streamInfo = new WOWZDataMap();
streamInfo.put("- Stream Statistics -", streamStats);
streamInfo.put("- Stream Metadata -", streamMetadata);
//streamInfo.put("- Stream Configuration -", streamConfig);
DataTableFragment dataTableFragment = DataTableFragment.newInstance("Stream Information", streamInfo, false, false);
getFragmentManager().beginTransaction()
.add(android.R.id.content, dataTableFragment)
.addToBackStack("metadata_fragment")
.commit();
}
public void onSettings(View v) {
// Display the prefs fragment
GoCoderSDKPrefs.PrefsFragment prefsFragment = new GoCoderSDKPrefs.PrefsFragment();
prefsFragment.setFixedSource(true);
prefsFragment.setForPlayback(true);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, prefsFragment)
.addToBackStack(null)
.commit();
}
private void syncUIControlState() {
boolean disableControls = (!(mStreamPlayerView.isReadyToPlay() || mStreamPlayerView.isPlaying()) || sGoCoderSDK == null);
if (disableControls) {
mBtnPlayStream.setEnabled(false);
mBtnSettings.setEnabled(false);
mSeekVolume.setEnabled(false);
mBtnScale.setEnabled(false);
mBtnMic.setEnabled(false);
mStreamMetadata.setEnabled(false);
} else {
mBtnPlayStream.setState(mStreamPlayerView.isPlaying());
mBtnPlayStream.setEnabled(true);
if (mStreamPlayerConfig.isAudioEnabled()) {
mBtnMic.setVisibility(View.VISIBLE);
mBtnMic.setEnabled(true);
mSeekVolume.setVisibility(View.VISIBLE);
mSeekVolume.setEnabled(mBtnMic.isOn());
mSeekVolume.setProgress(mStreamPlayerView.getVolume());
} else {
mSeekVolume.setVisibility(View.GONE);
mBtnMic.setVisibility(View.GONE);
}
mBtnScale.setVisibility(View.VISIBLE);
mBtnScale.setVisibility(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled() ? View.VISIBLE : View.GONE);
mBtnScale.setEnabled(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled());
mBtnSettings.setEnabled(!mStreamPlayerView.isPlaying());
mBtnSettings.setVisibility(mStreamPlayerView.isPlaying() ? View.GONE : View.VISIBLE);
mStreamMetadata.setEnabled(mStreamPlayerView.isPlaying());
mStreamMetadata.setVisibility(mStreamPlayerView.isPlaying() ? View.VISIBLE : View.GONE);
}
}
private void showBuffering() {
try {
if (mBufferingDialog == null) return;
mBufferingDialog.show();
}
catch(Exception ex){}
}
private void cancelBuffering(DialogInterface dialogInterface) {
if(mStreamPlayerConfig.getHLSBackupURL()!=null || mStreamPlayerConfig.isHLSEnabled()){
mStreamPlayerView.stop(true);
}
else if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop(true);
}
}
private void hideBuffering() {
if (mBufferingDialog.isShowing())
mBufferingDialog.dismiss();
}
#Override
public void syncPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mWZNetworkLogLevel = Integer.valueOf(prefs.getString("wz_debug_net_log_level", String.valueOf(WOWZLog.LOG_LEVEL_DEBUG)));
mStreamPlayerConfig.setIsPlayback(true);
if (mStreamPlayerConfig != null)
GoCoderSDKPrefs.updateConfigFromPrefsForPlayer(prefs, mStreamPlayerConfig);
}
private class StatusCallback implements WOWZStatusCallback {
#Override
public void onWZStatus(WOWZStatus wzStatus) {
}
#Override
public void onWZError(WOWZStatus wzStatus) {
}
}
}
The error I get is;
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wowza.gocoder.sdk.sampleapp/com.wowza.gocoder.sdk.sampleapp.PlayerActivity}: java.lang.RuntimeException: Invalid surface: null
You start the stream in onCreate. At this time the Surface used by WOWZPlayerView is not ready yet and the app crashes with the 'Invalid surface' error.
If you look at the sample test in the GoCoder SDK, the playback is started when the user clicks a button. Eg. when the Surface is valid.
Create a button and move your 'mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);' to the button.onClick.
Or ... use any GoCoder SDK v1.7 and more recent.
Please, let me know if I can help any further.
Thanks
I'm parsing a json to display a list of files a user can tap to download. I want to display the files the users have chosen to download on my main screen. this is the code when they download a file.
public final class Main extends Activity {
// Log tag for this class
private static final String TAG = "Main";
// Callback code for request of storage permission
final private int PERMISSIONS_REQUEST_STORAGE = 735;
// JSON Node Names
private static final String TAG_TYPE = "plans";
private static final String TAG_NAME = "name";
private static final String TAG_FILENAME = "filename";
private static final String TAG_URL = "url";
private static final String TAG_SHOULD_NOT_CACHE = "shouldNotCache";
// Files to delete
private static final ArrayList<String> filesToGetDeleted = new ArrayList<>();
// Strings displayed to the user
private static String offline;
private static String noPDF;
private static String localLoc;
private static String jsonURL;
// PDF Download
private static DownloadManager downloadManager;
private static long downloadID;
private static File file;
#SuppressLint("StaticFieldLeak")
private static SwipeRefreshLayout swipeRefreshLayout;
private final BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
final DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
final Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
final int columnIndex = cursor
.getColumnIndex(DownloadManager.COLUMN_STATUS);
final int status = cursor.getInt(columnIndex);
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
final Uri path = Uri.fromFile(file);
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
break;
case DownloadManager.STATUS_FAILED:
Utils.makeLongToast(Main.this,
getString(R.string.down_error));
break;
case DownloadManager.STATUS_PAUSED:
Utils.makeLongToast(Main.this,
getString(R.string.down_paused));
break;
case DownloadManager.STATUS_PENDING:
Utils.makeLongToast(Main.this,
getString(R.string.down_pending));
break;
case DownloadManager.STATUS_RUNNING:
Utils.makeLongToast(Main.this,
getString(R.string.down_running));
break;
}
}
}
};
// Data from JSON file
private ArrayList<HashMap<String, String>> downloadList = new ArrayList<>();
private static void checkDir() {
final File dir = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/");
if (!dir.exists()) dir.mkdir();
}
#Override
protected void onResume() {
super.onResume();
final IntentFilter intentFilter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(downloadReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Delete files which should not get cached.
for (String file : filesToGetDeleted) {
final File f = new File(file);
if (f.exists()) {
f.delete();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Utils.makeLongToast(Main.this, getString(R.string.permission_write_external_storage_success));
}
else {
final String permission_write_external_storage_failure = getString(R.string.permission_write_external_storage_failure);
final String app_title = getString(R.string.app_name);
final String message = String.format(permission_write_external_storage_failure, app_title);
Utils.makeLongToast(Main.this, message);
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(Main.this, permissions[0]);
if (!showRationale) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
break;
}
}
private void update(boolean force, boolean firstLoad) {
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout_main);
offline = getString(R.string.status_offline);
noPDF = getString(R.string.except_nopdf);
localLoc = getString(R.string.gen_loc);
jsonURL = getString(R.string.gen_json);
checkDir();
if (firstLoad) {
try {
downloadList = (ArrayList<HashMap<String, String>>) Utils.readObject(this, "downloadList");
if (downloadList != null) {
setList(true, true);
}
} catch (ClassNotFoundException | IOException e) {
Log.e(TAG, e.getMessage());
}
}
// Parse the JSON file of the plans from the URL
JSONParse j = new JSONParse();
j.force = force;
j.online = !Utils.isNoNetworkAvailable(this);
j.execute();
}
private void setList(final boolean downloadable, final boolean itemsAvailable) {
if (itemsAvailable) {
try {
Utils.writeObject(this, "downloadList", downloadList);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
final ListView list = (ListView) findViewById(R.id.listView_main);
final ListAdapter adapter = new SimpleAdapter(this, downloadList,
android.R.layout.simple_list_item_1, new String[]{TAG_NAME},
new int[]{android.R.id.text1});
list.setAdapter(adapter);
// React when user click on item in the list
if (itemsAvailable) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
int hasStoragePermission = ContextCompat.checkSelfPermission(Main.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Main.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_REQUEST_STORAGE);
return;
}
final Uri downloadUri = Uri.parse(downloadList.get(pos).get(TAG_URL));
final String title = downloadList.get(pos).get(TAG_NAME);
final String shouldNotCache = downloadList.get(pos).get(TAG_SHOULD_NOT_CACHE);
file = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/"
+ downloadList.get(pos).get(TAG_FILENAME) + ".pdf");
final Uri dst = Uri.fromFile(file);
if (file.exists()) {
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(dst, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
return;
}
if (downloadable && !Utils.isNoNetworkAvailable(Main.this)) {
// Download PDF
final Request request = new Request(downloadUri);
request.setTitle(title).setDestinationUri(dst);
downloadID = downloadManager.enqueue(request);
if (shouldNotCache.equals("true")) {
filesToGetDeleted.add(file.toString());
}
} else {
Utils.makeLongToast(Main.this, offline);
}
}
});
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
update(true, false);
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public boolean force = false;
public boolean online = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
#Override
protected JSONObject doInBackground(String... args) {
return JSONParser.getJSONFromUrl(Main.this, jsonURL, force, online);
}
#Override
protected void onPostExecute(JSONObject json) {
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
});
downloadList.clear();
if (json == null) {
String error = getString(R.string.except_json);
if (!online) {
error = offline;
}
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_NAME, error);
downloadList.add(map);
setList(false, false);
return;
}
try {
// Get JSON Array from URL
final JSONArray j_plans = json.getJSONArray(TAG_TYPE);
for (int i = 0; i < j_plans.length(); i++) {
final JSONObject c = j_plans.getJSONObject(i);
// Storing JSON item in a Variable
final String ver = c.getString(TAG_FILENAME);
final String name = c.getString(TAG_NAME);
final String api = c.getString(TAG_URL);
String shouldNotCache = "";
if (c.has(TAG_SHOULD_NOT_CACHE)) {
shouldNotCache = c.getString(TAG_SHOULD_NOT_CACHE);
}
// Adding value HashMap key => value
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_FILENAME, ver);
map.put(TAG_NAME, name);
map.put(TAG_URL, api);
map.put(TAG_SHOULD_NOT_CACHE, shouldNotCache);
downloadList.add(map);
setList(online, true);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}
SO how do I get the result of the above code and display it on main screen every time the user opens app
Im new to Android Developement and currently working on an app that should give me the time between first time clicking a button and second time clicking the button and add it to a currently selected customer.
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
public class ZeitErfassen extends AppCompatActivity {
public static LinkedList<Kunde> kunden = new LinkedList<Kunde>();
boolean running = false;
long startTime,endTime,totalTime;
private SharedPreferences app_preferences;
private SharedPreferences.Editor editor;
private TextView displayTime;
public Button startEndButton;
private ArrayAdapter<String> adapter;
private Spinner spinner;
public static Kunde selectedCustomer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zeit_erfassen);
//Einstellungen laden
app_preferences = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
startTime= app_preferences.getLong("startTime", 0);
endTime = app_preferences.getLong("endTime", 0);
running = app_preferences.getBoolean("running", false);
displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
startEndButton = (Button)findViewById(R.id.start_Timer);
startEndButton.setText((CharSequence) app_preferences.getString("timerButton", "Start Timer"));
DatabaseHelper.customerFromDatabaseToList(this);
editor = app_preferences.edit();
editor.commit();
}
public void onDestroy() {
super.onDestroy();
editor.putLong("startTime", startTime);
editor.putString("zeitAnzeige", (String) displayTime.getText());
editor.putString("timerButton", (String) startEndButton.getText());
editor.putLong("endTime", endTime);
editor.putLong("totalTime", totalTime);
editor.putBoolean("running", app_preferences.getBoolean("running", false));
editor.commit();
this.finish();
}
public void onResume() {
super.onResume();
// saveCustomers();
// createDropDown();
}
public void startTimer(View view) {
editor = app_preferences.edit();
if(running == false) {
startTime = getTime();
running = true;
editor.putLong("startTime", startTime);
startEndButton.setText("End Timer");
displayTime.setText("Zeitstoppung läuft");
editor.putString("zeitAnzeige", (String) displayTime.getText());
editor.putString("timerButton", (String) startEndButton.getText());
editor.putBoolean("running", true);
editor.commit();
} else {
setSelectedCustomer();
endTime = getTime();
editor.putLong("endTime",endTime);
totalTime = endTime - startTime;
editor.putLong("totalTime", totalTime);
displayTime.setText(formatTime(totalTime));
editor.putString("zeitAnzeige", (String) displayTime.getText());
startEndButton.setText("Start Timer");
editor.putString("timerButton", (String) startEndButton.getText());
running = false;
editor.putBoolean("running", false);
editor.commit();
DatabaseHelper.timeToDatabase(String.valueOf(selectedCustomer.getId()),formatTime(totalTime),this);
// selectedCustomer.saveTimeToCustomer(selectedCustomer, formatTimeForCustomer(totalTime));
}
}
public String formatTime(Long totalTime) {
int hours = (int) ((totalTime / (1000*60*60)) % 24);
int minutes = (int) ((totalTime / (1000*60)) % 60);
int seconds = (int) (totalTime / 1000) % 60;
String time = (String.valueOf(hours) + ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds));
return time;
}
public String formatTimeForCustomer(Long totalTime) {
StringBuilder time = new StringBuilder();
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
time.append((String.valueOf(year) + "." + String.valueOf(month) + "." + String.valueOf(day))).append(formatTime(totalTime));
return time.toString();
}
public void neuerKunde(View view) {
Intent intent = new Intent(this, AddKunde.class);
startActivity(intent);
}
public void kundenĂbersicht(View view) {
// setSelectedCustomer();
Intent intent = new Intent(this, DisplayCustomer.class);
startActivity(intent);
}
public long getTime() {
long millis = System.currentTimeMillis();
return millis;
}
public void setSelectedCustomer() {
if(kunden.size() > 0) {
if (spinner.getSelectedItem().toString() != null) {
String tempCustomer = spinner.getSelectedItem().toString();
for (Kunde k : kunden) {
if (k.getName().equals(tempCustomer)) {
selectedCustomer = k;
}
}
}
}
}
public void createDropDown() {
/*File file = new File(this.getFilesDir(),"kunden.ser"); NOT USED BECAUSE DATABASE WORKS
if(file.exists()) {
Kunde.importFromFile(this);
}*/
if (kunden.size() > 0) {
spinner = (Spinner) findViewById(R.id.chooseCustomer);
// Create an ArrayAdapter using the string array and a default spinner layout
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DisplayCustomer.namesOfCustomers());
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
}
}
DisplayCustomer(Where all customers are displayed with data from Database)
public class DisplayCustomer extends AppCompatActivity {
CustomerAdapter customerAdapter;
public ArrayAdapter<String> adapterCustomerView;
private ListView listCustomerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ArrayList<Kunde> customerList = getCustomerObjects();
customerAdapter = new CustomerAdapter(this,customerList);
listCustomerView = (ListView)findViewById(R.id.list_View_Customers);
// adapterCustomerView = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namesOfCustomers());
listCustomerView.setAdapter(customerAdapter);
openCustomerDetails();
}
public static ArrayList<String> namesOfCustomers() {
ArrayList<String> customerNames = new ArrayList<>();
if(ZeitErfassen.kunden.size() > 0 ) {
for (Kunde k : ZeitErfassen.kunden) {
customerNames.add(k.getName());
}
}
return customerNames;
}
public static ArrayList<Kunde> getCustomerObjects() {
ArrayList<Kunde> customerList = new ArrayList<>();
if(ZeitErfassen.kunden.size() > 0 ) {
for (Kunde k : ZeitErfassen.kunden) {
customerList.add(k);
}
}
return customerList;
}
public void openCustomerDetails() {
listCustomerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Kunde kunde = new Kunde();
kunde = (Kunde)listCustomerView.getItemAtPosition(position);
Intent intent = new Intent(DisplayCustomer.this, DisplayDetailedCustomer.class);
intent.putExtra("selectedCustomerObject",(Parcelable)kunde);
startActivity(intent);
}
});
}
}
My CustomerAdapter to pass data from one intent to another.
public class CustomerAdapter extends ArrayAdapter<Kunde> {
public CustomerAdapter(Context context, ArrayList<Kunde> customerList) {
super(context,0,customerList);
}
public View getView(int position, View convertView, ViewGroup parent) {
//Data for this position
Kunde kunde = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.items_customer_layout, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvCustomerName);
// Populate the data into the template view using the data object
tvName.setText(kunde.getName());
// Return the completed view to render on screen
return convertView;
}
}
DatabaseHelper Class
public class DatabaseHelper {
public static RequestQueue requestQueue;
public static String host = "http://192.168.150.238/";
public static final String insertUrl = host+"insertCustomer.php";
public static final String showUrl = host+"showCustomer.php";
public static final String insertTimeUrl = host+"insertTime.php";
public static final String showTimeUrl = host+"showTimes.php";
public static void customerFromDatabaseToList(final Context context) {
//Display customer from database
requestQueue = Volley.newRequestQueue(context);
final ArrayList<String> customerNames = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray customers = response.getJSONArray("customers");
if(customers.length() > 0) {
for (int i = 0; i < customers.length(); i++) {
JSONObject customer = customers.getJSONObject(i);
String customerName = customer.getString("cus_name");
String customerAddress = customer.getString("cus_address");
int customerID = Integer.valueOf(customer.getString("cus_id"));
if (customerName != null && customerAddress != null) {
try {
Kunde k = new Kunde(customerName, customerAddress, customerID);
if (!listContainsObject(k)) {
ZeitErfassen.kunden.add(k);
}
} catch (Exception e) {
showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
}
} else {
showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
public static boolean listContainsObject(Kunde cust) {
for(Kunde k : ZeitErfassen.kunden) {
if(k.getId() == cust.getId()) {
return true;
}
}
return false;
}
public static void timeToDatabase(final String customer_id, final String time_value, final Context context) {
requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST, DatabaseHelper.insertTimeUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showAlert("Fehler","Fehler bei Verbindung zur Datenbank",context);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("customerid",customer_id);
parameters.put("timevalue",time_value);
return parameters;
}
};
requestQueue.add(request);
};
public static void showAlert(String title, String message, Context context) {
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(message)
.setTitle(title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
}
public static ArrayList<String> timesFromDataBaseToList(final Context context,final int customer_id) {
requestQueue = Volley.newRequestQueue(context);
final String cus_id = String.valueOf(customer_id) ;
final ArrayList<String> customerTimes = new ArrayList<>();
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, showTimeUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response.toString());
JSONArray times = object.getJSONArray("customertimes");
if (times.length() > 0) {
for (int i = 0; i < times.length(); i++) {
JSONObject jsonObject = times.getJSONObject(i);
String timeValue = jsonObject.getString("time_value");
if (timeValue != null) {
customerTimes.add(timeValue);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Fehler beim Holen der Zeiten",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("cus_id",cus_id);
return parameters;
}
};
requestQueue.add(jsonObjectRequest);
return customerTimes;
};
}
DisplayDetailedCustomer / Display the times
public class DisplayDetailedCustomer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_detailed_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent getCustomerParcable = getIntent();
Kunde customer = getCustomerParcable.getExtras().getParcelable("selectedCustomerObject");
TextView displayCustomerNameDetailed =(TextView) findViewById(R.id.detailedCustomerViewName);
TextView displayCustomerAddressDetailed =(TextView) findViewById(R.id.detailedCustomerAddress);
ListView timeListView = (ListView)findViewById(R.id.detailedTimeListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, DatabaseHelper.timesFromDataBaseToList(this,customer.getId()));
timeListView.setAdapter(adapter);
displayCustomerNameDetailed.setText(customer.getName());
displayCustomerAddressDetailed.setText(customer.getAdresse());
}
}
Kunde Class / Customer Class with interface Parcelable
public class Kunde implements Serializable,Parcelable {
private String name;
private String adresse;
private int id;
public LinkedList<String> zeiten;
public Kunde(String name, String adresse) throws Exception{
setName(name);
setAdresse(adresse);
zeiten = new LinkedList<String>();
}
public Kunde(String name, String adresse,int id) throws Exception{
setName(name);
setAdresse(adresse);
setId(id);
zeiten = new LinkedList<String>();
}
public Kunde(){};
public void setId(int id) {
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name) throws Exception {
if(name != null) {
this.name = name;
} else throw new Exception("Name ist ungueltig! in setName");
}
public void setAdresse(String adresse) throws Exception{
if(adresse != null) {
this.adresse = adresse;
}else throw new Exception("Adresse ist ungueltig! in setAdresse");
}
public String getName() {
return name;
}
public String getAdresse() {
return adresse;
}
public void saveZeit(Long totalTime) {
zeiten.add(String.valueOf(totalTime));
}
public void saveTimeToCustomer(Kunde customer,String time){
customer.zeiten.add(time);
}
//------------------------------------Parcelable Methods to pass Daata from one Intent to another----------------------------------------
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
dest.writeString(this.adresse);
// dest.writeList(this.zeiten);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Kunde> CREATOR = new Parcelable.Creator<Kunde>() {
public Kunde createFromParcel(Parcel in) {
return new Kunde(in);
}
public Kunde[] newArray(int size) {
return new Kunde[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Kunde(Parcel in) {
LinkedList<String> zeiten = null;
id = in.readInt();
name = in.readString();
adresse = in.readString();
}
}
Thanks for taking your time!!
I am developing an app which would talk to the server which is developed using spring. I got to a point where we i was getting data from the google api and wanted to pass it to the spring server. But when i do pass it, the server accepts it but the data is not being stored in the mysql database.
Here is the code I am using:
This is the main spring application + controller:
#EnableJpaRepositories(basePackageClasses = StudentRepository.class)
#SpringBootApplication
public class Demo3Application {
public static void main(String[] args) {
SpringApplication.run(Demo3Application.class, args);
}
}
#RestController
class StudentController
{
#Autowired
public StudentRepository students;
#RequestMapping(value = "/getstudent", method = RequestMethod.GET)
public #ResponseBody List<Student> fetchStudents()
{
if(students.count() == 0)
{
Vector<VideoList> no_video = new Vector<VideoList>();
VideoList no_v = new VideoList("No Videos found", null, null, null);
no_video.add(no_v);
return no_video;
return null;
}
return null;
}
#RequestMapping(value = "/poststudent" , method = RequestMethod.POST)
public #ResponseBody String putStudents(#RequestBody Student v )
{
students.save(v);
return "Student Successfully Added";
}
#RequestMapping(value = "/searchstudent/{str}" , method = RequestMethod.GET)
public #ResponseBody String searchStudent(
#PathVariable("str") String searchQuery
)
{
if(students.existsByEmail(searchQuery)){
List<Student> sList = students.findEmail(searchQuery,new PageRequest(0, 1));
Student s = sList.get(0);
String str = "";
Vector<CourseList> c = s.getCourses();
Iterator<CourseList> it = c.iterator();
while(it.hasNext()){
str.concat(it.next().toString());
str.concat("\n");
}
return str;
}
return null ;
}
#RequestMapping(value = "/addcourse" , method = RequestMethod.POST)
public #ResponseBody String postCourse(#RequestParam String email, #RequestParam String course){
List<Student> sList = students.findEmail(email,new PageRequest(0, 1));
Student s = sList.get(0);
CourseList c = new CourseList();
c.setName(course);
s.addCourse(c);
students.save(s);
return null;
}
}
This is the Student class:
#Entity
#Table(name = "table1")
public class Student {
private String name;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String email;
private Vector<CourseList> courses = new Vector<CourseList>();//CourseList is just a class to store data about various courses.
public Student(){}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public Vector<CourseList> getCourses(){
return courses;
}
public void setName(String name){
this.name = name;
}
public void setEmail(String email){
this.email = email;
}
public void setCourses(Vector<CourseList> courses){
this.courses = courses;
}
public void addCourse(CourseList c){
courses.add(c);
}
}
This is my repository:
#Repository
#Transactional
public interface StudentRepository extends CrudRepository<Student,String>{
#Query("SELECT s FROM Student s WHERE email = ?1")
public List<Student> findEmail(String searchQuery, Pageable pageable);
#Query("SELECT CASE WHEN COUNT(s) > 0 THEN 'true' ELSE 'false' END FROM Student s WHERE s.email = ?1")
public boolean existsByEmail(String searchQuery);
}
This is my application.properties file:
spring.datasource.url: jdbc:mysql://localhost/mydb
spring.datasource.driverClassName: com.mysql.jdbc.Driver
spring.datasource.username: root
spring.datasource.password:root
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
And finally here is the android code to test the above:
public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "MainActivity";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut;
private ImageView imgProfilePic;
private TextView txtName, txtEmail, course;
private LinearLayout llProfileLayout;
private Button SC;
private String personName;
private String personPhotoUrl;
private String personGooglePlusProfile;
private String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
course = (TextView) findViewById(R.id.txtCourses);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
SC=(Button)findViewById(R.id.Scourse);
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
SC.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
getCourses();
SC.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
course.setText(" ");
SC.setVisibility(View.GONE);
}
}
private void getCourses(){
new StudentSearch().execute();
}
private class StudentSearch extends AsyncTask<String, Void, String >
{
String content = "";
#Override
protected String doInBackground(String... urls) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://192.168.49.8:8080/searchstudent/"+email);
StringBuffer studentString = new StringBuffer();
try {
HttpResponse response = httpClient.execute(httpget);
InputStream responseString = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseString));
String res = "";
if ((res = reader.readLine()) == null) {
studentString.append("");
HttpPost httpPost = new HttpPost("http://192.168.49.8:8080/poststudent/");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", personName);
jsonObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
try {
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httpPost.setEntity(se);
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
} else {
studentString.append(res);
studentString.append("\n");
while ((res = reader.readLine()) != null) {
studentString.append(res);
studentString.append("\n");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return studentString.toString();
}
#Override
protected void onPostExecute(String s) {
if (!s.isEmpty()){
course.setText("Courses Taken:\n"+s);}
else
course.setText("No Courses Taken!");
}
}
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
personName = currentPerson.getDisplayName();
personPhotoUrl = currentPerson.getImage().getUrl();
personGooglePlusProfile = currentPerson.getUrl();
email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
/**
* Button on click listener
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.Scourse:
{
Intent intent=new Intent(MainActivity.this,SelectCourse.class);
startActivity(intent);
break;
}
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
I am a total newbie when it comes to developing spring code and would really appreciate some help.
I have an app that makes use of an xml obtained with a HttpGet. In the url of the xml request has a key that changes every hour, this key is obtained through another url.
Example: www.test.com/xml?hr=123456
The app tries to get the xml. If errors occur, get the key in another HttpGet and updates in the xml url.
In the emulator works perfectly, but not on the device. Already put a trace and the key is successfully updated. But the xml request error continues.
I tried to put "no cache" in HttpGet
HttpClient client = new DefaultHttpClient (httpParams);
HttpGet get = new HttpGet (url);
get.addHeader ("Cache-Control", "no-cache"); / / HTTP/1.1
get.addHeader ("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");
but it did not work, is there anything that can be done?
My Complete Activity:
public class ShowActivity extends AdModctivity implements
bbbAndroidConstantes, OnItemClickListener, OnCheckedChangeListener {
private ProgressDialog dialog;
private Retf p;
private Handler handler = new Handler();
private Exception ex;
private CheckBox check;
private ParametrosTO parTO;
ParametrosDataBase parDB;
String ref;
String pId;
String logR;
String kId;
String ldesc;
TextView txtRef;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listaprevisoeslayout);
Bundle bundle = getIntent().getExtras();
parDB = new ParametrosDataBase(this);
parTO = parDB.listParametros();
pId = bundle.getString(VAR_P_ID);
ref = bundle.getString(VAR_P_REF);
logR = bundle.getString(VAR_LOGR);
kId = bundle.getString(VAR_KID);
ldesc = bundle.getString(VAR_LDESC);
txtRef = (TextView) findViewById(R.id.txtRef);
check = (CheckBox) findViewById(R.id.checkWidget);
WidgetDataBase wDb = new WidgetDataBase(this);
if (wDb.searchWidget(pId, kId) != null)
check.setChecked(true);
check.setOnCheckedChangeListener(this);
dialog = ProgressDialog.show(ShowActivity.this, "",
"Wait...", true);
if (!Utilities.chkStatus(ShowActivity.this))
return;
downloadInfo();
fillAdMod();
}
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
}
private void downloadInfo() {
new Thread() {
#Override
public void run() {
boolean flag = false;
try {
p = Controller.getInstance().getRetf(parTO.getUrl(), pId, kId);
if ((p.getInfoP() == null) || (p.getInfoP().size() == 0)) {
flag = true;
String newUrl = getNewUrl();
Utilities.updateUrl(ShowActivity.this, newUrl);
parTO = parDB.listParametros();
p = Controller.getInstance().getRetf(newUrl, pId, kId);
}
refreshScreen();
} catch (Exception e) {
if (!flag) {
try {
String newUrl = getNewUrl();
Utilities.updateUrl(ShowActivity.this, newUrl);
parTO = parDB.listParametros();
p = Controller.getInstance().getRetf(newUrl, pId, kId);
refreshScreen();
} catch (Exception e1) {
ex = e1;
refreshScreenException();
}
}
else
{
ex = e;
refreshScreenException();
}
}
}
}.start();
}
/**
* Thread to close dialog and show information
*/
private void refreshScreen() {
handler.post(new Runnable() {
#Override
public void run() {
dialog.dismiss();
fillInfo();
}
});
}
/**
* Thread to close dialog and show exception
*/
private void refreshScreenException() {
handler.post(new Runnable() {
#Override
public void run() {
dialog.dismiss();
fillInfoExcecao();
}
});
}
/**
* Fill information on screen
*/
private void fillInfo() {
if (p == null) {
Toast.makeText(ShowActivity.this, MSG_SEM_Retf,
MSG_TIME_MILIS).show();
this.finish();
}
if ((p.getErro() != null) && (p.getErro().trim().length() > 0)) {
Toast.makeText(ShowActivity.this, p.getErro(),
MSG_TIME_MILIS).show();
this.finish();
}
if ((p.getPonto() == null) || (p.getPonto().size() == 0)) {
Toast.makeText(ShowActivity.this, MSG_SEM_Retf,
MSG_TIME_MILIS).show();
this.finish();
}
SimpleDateFormat spf = new SimpleDateFormat("HH:mm:ss");
long localTime = Long.parseLong(p.getLocalTime());
txtRef.setText(txtRef.getText() + " "
+ spf.format(new Date(localTime)));
RetfAdapter RetfAdapter = new RetfAdapter(this, p);
ListView lista = (ListView) findViewById(R.id.listView1);
lista.setAdapter(RetfAdapter);
lista.setOnItemClickListener(this);
}
/**
* Apresenta mensagem em caso de exceo
*/
private void fillInfoExcecao() {
if (ex instanceof bbbException) {
Toast.makeText(ShowActivity.this,
((bbbException) ex).getMessage(), MSG_TIME_MILIS).show();
ShowActivity.this.finish();
} else {
Toast.makeText(ShowActivity.this,
getString(R.string.msg_erroSistema), MSG_TIME_MILIS).show();
ShowActivity.this.finish();
}
}
#Override
public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
PBean PBean = new PBean(pId, logR,
ref, kId, ldesc);
WidgetDataBase wDb = new WidgetDataBase(this);
if (isChecked)
wDb.addWidget(PBean);
else
wDb.deleteWidget(PBean);
}
private String getNewUrl() throws Exception
{
String newUrl = Utilities.getHttp(bbbAndroidConstantes.URL_HOST_HORARIOS);
return newUrl;
}
}