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
Related
I am a beginner in the world of programming, and now I am working on developing an audio player by adding an equalizer, but I encountered a problem, which is after 10 seconds of pressing the back button and exiting the fragment, the equalizer stops and does not work until after opening the page again.
Also, when playing another audio, the equalizer stops and does not work until the fragment is opened again.
I have tried to fix it but to no avail, Plz Help..
public class MainActivityEqualizer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_equalizer);
loadEqualizerSettings();
final int sessionId = MyConstants.exoPlayer.getAudioSessionId();
EqualizerFragment equalizerFragment = EqualizerFragment.newBuilder()
.setAccentColor(Color.parseColor("#4caf50"))
.setAudioSessionId(sessionId)
.build();
getSupportFragmentManager().beginTransaction()
.replace(R.id.eqFrame, equalizerFragment)
.commit();
}
public void newBuild()
{
final int sessionId = MyConstants.exoPlayer.getAudioSessionId();
EqualizerFragment equalizerFragment = EqualizerFragment.newBuilder()
.setAccentColor(Color.parseColor("#4caf50"))
.setAudioSessionId(sessionId)
.build();
getSupportFragmentManager().beginTransaction()
.replace(R.id.eqFrame, equalizerFragment)
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.itemEqDialog) {
showInDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
saveEqualizerSettings();
}
#Override
protected void onPause() {
try {
newBuild();
//mediaPlayer.pause();
} catch (Exception ex) {
Toast.makeText(MainActivityEqualizer.this,ex+"",Toast.LENGTH_LONG).show();
//ignore
}
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
newBuild();
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//loadEqualizerSettings();
//mediaPlayer.start();
}
}, 200);
} catch (Exception ex) {
//ignore
}
}
private void showInDialog() {
int sessionId = MyConstants.exoPlayer.getAudioSessionId();
if (sessionId > 0) {
DialogEqualizerFragment fragment = DialogEqualizerFragment.newBuilder()
.setAudioSessionId(sessionId)
.title(R.string.app_name)
.themeColor(ContextCompat.getColor(this, R.color.primaryColor))
.textColor(ContextCompat.getColor(this, R.color.textColor))
.accentAlpha(ContextCompat.getColor(this, R.color.playingCardColor))
.darkColor(ContextCompat.getColor(this, R.color.primaryDarkColor))
.setAccentColor(ContextCompat.getColor(this, R.color.secondaryColor))
.build();
fragment.show(getSupportFragmentManager(), "eq");
}
}
private void saveEqualizerSettings(){
if (Settings.equalizerModel != null){
EqualizerSettings settings = new EqualizerSettings();
settings.bassStrength = Settings.equalizerModel.getBassStrength();
settings.presetPos = Settings.equalizerModel.getPresetPos();
settings.reverbPreset = Settings.equalizerModel.getReverbPreset();
settings.seekbarpos = Settings.equalizerModel.getSeekbarpos();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
preferences.edit()
.putString(PREF_KEY, gson.toJson(settings))
.apply();
}
}
private void loadEqualizerSettings(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
EqualizerSettings settings = gson.fromJson(preferences.getString(PREF_KEY, "{}"), EqualizerSettings.class);
EqualizerModel model = new EqualizerModel();
model.setBassStrength(settings.bassStrength);
model.setPresetPos(settings.presetPos);
model.setReverbPreset(settings.reverbPreset);
model.setSeekbarpos(settings.seekbarpos);
Settings.isEqualizerEnabled = true;
Settings.isEqualizerReloaded = true;
Settings.bassStrength = settings.bassStrength;
Settings.presetPos = settings.presetPos;
Settings.reverbPreset = settings.reverbPreset;
Settings.seekbarpos = settings.seekbarpos;
Settings.equalizerModel = model;
}
public static final String PREF_KEY = "equalizer";
public static void newLoadEqualizerSettings(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyConstants.context);
Gson gson = new Gson();
EqualizerSettings settings = gson.fromJson(preferences.getString(PREF_KEY, "{}"), EqualizerSettings.class);
EqualizerModel model = new EqualizerModel();
model.setBassStrength(settings.bassStrength);
model.setPresetPos(settings.presetPos);
model.setReverbPreset(settings.reverbPreset);
model.setSeekbarpos(settings.seekbarpos);
Settings.isEqualizerEnabled = true;
Settings.isEqualizerReloaded = true;
Settings.bassStrength = settings.bassStrength;
Settings.presetPos = settings.presetPos;
Settings.reverbPreset = settings.reverbPreset;
Settings.seekbarpos = settings.seekbarpos;
Settings.equalizerModel = model;
}
}
and here is onCreate method of EqualizerFragment
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Settings.isEditing = true;
if (getArguments() != null && getArguments().containsKey(ARG_AUDIO_SESSIOIN_ID)) {
audioSesionId = getArguments().getInt(ARG_AUDIO_SESSIOIN_ID);
}
if (Settings.equalizerModel == null) {
Settings.equalizerModel = new EqualizerModel();
Settings.equalizerModel.setReverbPreset(PresetReverb.PRESET_NONE);
Settings.equalizerModel.setBassStrength((short) (1000 / 19));
}
mEqualizer = new Equalizer(0, audioSesionId);
bassBoost = new BassBoost(0, audioSesionId);
bassBoost.setEnabled(Settings.isEqualizerEnabled);
BassBoost.Settings bassBoostSettingTemp = bassBoost.getProperties();
BassBoost.Settings bassBoostSetting = new BassBoost.Settings(bassBoostSettingTemp.toString());
bassBoostSetting.strength = Settings.equalizerModel.getBassStrength();
bassBoost.setProperties(bassBoostSetting);
presetReverb = new PresetReverb(0, audioSesionId);
presetReverb.setPreset(Settings.equalizerModel.getReverbPreset());
presetReverb.setEnabled(Settings.isEqualizerEnabled);
mEqualizer.setEnabled(Settings.isEqualizerEnabled);
if (Settings.presetPos == 0) {
for (short bandIdx = 0; bandIdx < mEqualizer.getNumberOfBands(); bandIdx++) {
mEqualizer.setBandLevel(bandIdx, (short) Settings.seekbarpos[bandIdx]);
}
} else {
mEqualizer.usePreset((short) Settings.presetPos);
}
}
View Complaint Activity:
In this i have done debugging but i was unable to know the reason why the data is coming twice after scrolling. I have even check the data coming from server through postman but the data is not coming duplicate its coming perfectly fine the problem seems to be in front end while we are putting the data through adapter inside activity on scrolling.
public class ViewComplaintActivity extends AppCompatActivity implements AbsListView.OnScrollListener, View.OnClickListener {
TextView tv_notData;
List<Ticket> _data = new ArrayList<Ticket>();
ComplaintsAdapter settlementAdapter;
private String TAG = "ViewComplaintActivity";
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
private boolean userScrolled = false;
a) Its is a Complaints Activity where we are showing the data comimg from server through adapter.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_compliants);
ButterKnife.bind(this);
try {
settlementAdapter = new ComplaintsAdapter(ViewComplaintActivity.this, _data);
AlphaInAnimationAdapter animationAdapter = new AlphaInAnimationAdapter(settlementAdapter);
animationAdapter.setAbsListView(ll_complaint_list);
ll_complaint_list.setAdapter(animationAdapter);
getComplaints(Utility.getTerminalId(ViewComplaintActivity.this), 0);
ll_complaint_list.setOnScrollListener(this);
fab_raise_complaint.setOnClickListener(this);
fab_call_customer.setOnClickListener(this);
ivBackButton.setOnClickListener(this);
} catch (NullPointerException e) {
Log.e(TAG, e.toString());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
private void getComplaints(String terminalid, int pagenumber) {
if (!NetworkConnection.isConnected(this)) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("subIdentifier", terminalid);
jsonObject.addProperty("pageLimit", "10");
jsonObject.addProperty("lastPageIndex", "" + pagenumber);
IRetrofit iRetrofit = MoApplication.getInstance().getRetrofitOsTickets(this).create(IRetrofit.class);
Log.e(TAG,"jsonObject "+jsonObject);
iRetrofit.getAllTicket(jsonObject, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
progressBar.setVisibility(View.GONE);
try {
if (response.getStatus() == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody().in()));
String resultFromJson = bufferedReader.readLine();
/* Log.e(TAG, "resultFromJson " + resultFromJson);*/
GetTicketsResponse getSettlementsResDTO = new Gson().fromJson(resultFromJson, GetTicketsResponse.class);
switch (getSettlementsResDTO.getResCode()) {
case "0001":
if (null != getSettlementsResDTO.getTickets()) {
_data.addAll(getSettlementsResDTO.getTickets());
settlementAdapter.notifyDataSetChanged();
if (_data.isEmpty()) {
tv_notData.setVisibility(View.VISIBLE);
} else {
tv_notData.setVisibility(View.GONE);
}
} else {
Utility.showToast(ViewComplaintActivity.this, "No data found.");
}
break;
default:
Utility.showToast(ViewComplaintActivity.this, "Please try later.");
break;
}
}
} catch (NullPointerException e) {
Log.e(TAG, "" + e.toString());
} catch (Exception e) {
Log.e(TAG, "" + e.toString());
}
}
#Override
public void failure(RetrofitError error) {
if (Utility.parseException(error)){
Utility.mPosLogoutService((AppCompatActivity) ViewComplaintActivity.this);
}
progressBar.setVisibility(View.GONE);
}
});
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
/*Log.e(TAG,"one");*/
Log.e(TAG,"scrollState "+scrollState);
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
fab_call_customer.hide();
fab_raise_complaint.hide();
} else {
fab_call_customer.show();
fab_raise_complaint.show();
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
/*Log.e(TAG,"two");*/
view.getSelectedItemPosition();
if (userScrolled) {
Log.e(TAG,"loading "+loading);
if (loading) {
Log.e(TAG,"totalItemCount "+totalItemCount);
Log.e(TAG,"previousTotal "+previousTotal);
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
Log.e(TAG,"loadin after scroll "+loading);
if (!loading && ((totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold))) {
getComplaints(Utility.getTerminalId(ViewComplaintActivity.this), currentPage);
loading = true;
}
}
else {
Log.e(TAG,"user is idle");
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public void onClick(View v) {
if (NetworkConnection.isConnected(this)) {
if (v == fab_raise_complaint) {
Utility.navigate(this, RaiseComplaintActivity.class);
} else if (v == fab_call_customer) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + Uri.encode(Constant.helplineNumber.trim())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else if (v == ivBackButton) {
startActivity(new Intent(ViewComplaintActivity.this, HomeQrActivity.class));
finish();
}
} else {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
}
}
public class ComplaintsAdapter extends BaseAdapter {
private static String TAG = "ComplaintsAdapter";
List<Ticket> _data;
Context _c;
ViewHolder holder;
public ComplaintsAdapter(Context context, List<Ticket> getData) {
_data = getData;
_c = context;
}
#Override
public int getCount() {
Log.e(TAG,"_data.size()"+_data.size());
return _data.size();
}
#Override
public Object getItem(int position) {
Log.e(TAG,"_data.get(position)"+_data.get(position));
return _data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
/*Log.e(TAG,"getData"+_data.toString());*/
try {
if (view == null) {
/*Log.e(TAG,"getData1"+_data.toString());*/
LayoutInflater li = (LayoutInflater)
_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.row_item_view_complaints,
null);
} else {
/*Log.e(TAG,"getData2"+_data.toString());*/
view = convertView;
}
holder = new ViewHolder();
holder.tv_ticketNo = (TextView)
view.findViewById(R.id.tv_ticketNo);
holder.tv_submitDate = (TextView)
view.findViewById(R.id.tv_submitDate); //ticket comments
holder.tv_updatedDate = (TextView)
view.findViewById(R.id.tv_updatedDate);//will act as ticket
last modified time
holder.tv_ticketStatus = (TextView)
view.findViewById(R.id.tv_ticketStatus); //ticket status open
or close
holder.tv_comment = (TextView)
view.findViewById(R.id.tv_comment);
holder.tv_subject = (TextView)
view.findViewById(R.id.tv_subject);
final Ticket ticket = _data.get(position);
holder.tv_ticketNo.setText("#" + ticket.getTicketNo());
holder.tv_submitDate.setText(Html.fromHtml("<b> Created On:
</b>" + Utility.dateReformatting("yyyy-MM-dd HH:mm:ss", "dd
MMM yyyy", ticket.getCreated())));
holder.tv_updatedDate.setText(Html.fromHtml("<b> Modified On:
</b>" + Utility.dateReformatting("yyyy-MM-dd HH:mm:ss", "dd
MMM yyyy", ticket.getModified())));
holder.tv_ticketStatus.setText(ticket.getStatus());
holder.tv_subject.setText(null != ticket.getSubject() && !ticket.getSubject().isEmpty() ? ticket.getSubject().trim().replace("|", "") : "NA"); //comments
if (null != ticket.getComment() && !ticket.getComment().isEmpty()) {
holder.tv_comment.setText(Html.fromHtml(ticket.getComment()));
holder.tv_comment.setVisibility(View.VISIBLE);
} else {
holder.tv_comment.setVisibility(View.GONE);
}
//holder.tv_comment.setText(null != ticket.getComment() && !ticket.getComment().isEmpty() ? ticket.getComment() : ""); //comments
if (ticket.getStatus().startsWith("Open"))
holder.tv_ticketStatus.setTextColor(_c.getResources().getColor(R.color.green_success));
else
Log.e(TAG,"getData4"+_data.toString());
holder.tv_ticketStatus.setTextColor(_c.getResources().getColor(R.color_color));
} catch (NullPointerException e) {
Log.e(TAG, e.toString());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return view;
}
public void set_data(List<Ticket> _data) {
this._data = _data;
}
static class ViewHolder {
public TextView tv_ticketStatus, tv_ticketNo, tv_submitDate,
tv_updatedDate, tv_comment, tv_subject;
}
}
I am trying to adapt code from Bluetooth BLE developer starter kit to my own app (i.e this exact same code is working well on the example app).
But, I can't connect to any device, because, when I am pressing the Connect button (method onConnect), bluetooth_le_adapter is null.
I think that the bluetooth_le_adapter is not well initialized, and so, is null at startup.
Do you have any idea on how to fix this problem ? Thanks
PeripheralControlActivity.java:
public class PeripheralControlActivity extends Activity {
public static final String EXTRA_NAME = "name";
public static final String EXTRA_ID = "id";
private String device_name;
private String device_address;
private Timer mTimer;
private boolean sound_alarm_on_disconnect = false;
private int alert_level;
private boolean back_requested = false;
private boolean share_with_server = false;
private Switch share_switch;
private BleAdapterService bluetooth_le_adapter;
private final ServiceConnection service_connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
bluetooth_le_adapter = ((BleAdapterService.LocalBinder) service).getService();
bluetooth_le_adapter.setActivityHandler(message_handler);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
bluetooth_le_adapter = null;
}
};
private Handler message_handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle bundle;
String service_uuid = "";
String characteristic_uuid = "";
byte[] b = null;
switch (msg.what) {
case BleAdapterService.MESSAGE:
bundle = msg.getData();
String text = bundle.getString(BleAdapterService.PARCEL_TEXT);
showMsg(text);
break;
case BleAdapterService.GATT_CONNECTED:
((Button) PeripheralControlActivity.this
.findViewById(R.id.connectButton)).setEnabled(false);
((Button) PeripheralControlActivity.this.findViewById(R.id.noiseButton))
.setEnabled(true);
share_switch.setEnabled(true);
// we're connected
showMsg("CONNECTED");
/*AlarmManager am = AlarmManager.getInstance();
Log.d(Constants.TAG, "alarmIsSounding=" + am.alarmIsSounding());
if (am.alarmIsSounding()) {
Log.d(Constants.TAG, "Stopping alarm");
am.stopAlarm();
}*/
bluetooth_le_adapter.discoverServices();
break;
case BleAdapterService.GATT_DISCONNECT:
((Button) PeripheralControlActivity.this
.findViewById(R.id.connectButton)).setEnabled(true);
// we're disconnected
showMsg("DISCONNECTED");
// hide the rssi distance colored rectangle
((LinearLayout) PeripheralControlActivity.this
.findViewById(R.id.rectangle))
.setVisibility(View.INVISIBLE);
share_switch.setEnabled(false);
// disable the LOW/MID/HIGH alert level selection buttons
((Button) PeripheralControlActivity.this.findViewById(R.id.lowButton)).setEnabled(false);
((Button) PeripheralControlActivity.this.findViewById(R.id.midButton)).setEnabled(false);
((Button) PeripheralControlActivity.this.findViewById(R.id.highButton)).setEnabled(false);
// stop the rssi reading timer
stopTimer();
/*if (alert_level > 0) {
AlarmManager.getInstance().soundAlarm(getResources().openRawResourceFd(R.raw.alarm));
}*/
if (back_requested) {
PeripheralControlActivity.this.finish();
}
break;
case BleAdapterService.GATT_SERVICES_DISCOVERED:
// validate services and if ok....
List<BluetoothGattService> slist = bluetooth_le_adapter.getSupportedGattServices();
boolean link_loss_present = false;
boolean immediate_alert_present = false;
boolean tx_power_present = false;
boolean proximity_monitoring_present = false;
for (BluetoothGattService svc : slist) {
Log.d(Constants.TAG, "UUID=" + svc.getUuid().toString().toUpperCase() + " INSTANCE=" + svc.getInstanceId());
if (svc.getUuid().toString().equalsIgnoreCase(BleAdapterService.LINK_LOSS_SERVICE_UUID)) {
link_loss_present = true;
continue;
}
if (svc.getUuid().toString().equalsIgnoreCase(BleAdapterService.IMMEDIATE_ALERT_SERVICE_UUID)) {
immediate_alert_present = true;
continue;
}
if (svc.getUuid().toString().equalsIgnoreCase(BleAdapterService.TX_POWER_SERVICE_UUID)) {
tx_power_present = true;
continue;
}
if (svc.getUuid().toString().equalsIgnoreCase(BleAdapterService.PROXIMITY_MONITORING_SERVICE_UUID)) {
proximity_monitoring_present = true;
continue;
}
}
if (link_loss_present && immediate_alert_present && tx_power_present && proximity_monitoring_present) {
showMsg("Device has expected services");
// show the rssi distance colored rectangle
((LinearLayout) PeripheralControlActivity.this
.findViewById(R.id.rectangle))
.setVisibility(View.VISIBLE);
// enable the LOW/MID/HIGH alert level selection buttons
((Button) PeripheralControlActivity.this.findViewById(R.id.lowButton)).setEnabled(true);
((Button) PeripheralControlActivity.this.findViewById(R.id.midButton)).setEnabled(true);
((Button) PeripheralControlActivity.this.findViewById(R.id.highButton)).setEnabled(true);
showMsg("Reading alert_level");
bluetooth_le_adapter.readCharacteristic(
BleAdapterService.LINK_LOSS_SERVICE_UUID,
BleAdapterService.ALERT_LEVEL_CHARACTERISTIC);
} else {
showMsg("Device does not have expected GATT services");
}
break;
case BleAdapterService.GATT_REMOTE_RSSI:
bundle = msg.getData();
int rssi = bundle.getInt(BleAdapterService.PARCEL_RSSI);
PeripheralControlActivity.this.updateRssi(rssi);
break;
case BleAdapterService.GATT_CHARACTERISTIC_READ:
bundle = msg.getData();
Log.d(Constants.TAG, "Service=" + bundle.get(BleAdapterService.PARCEL_SERVICE_UUID).toString().toUpperCase() + " Characteristic=" + bundle.get(BleAdapterService.PARCEL_CHARACTERISTIC_UUID).toString().toUpperCase());
if (bundle.get(BleAdapterService.PARCEL_CHARACTERISTIC_UUID).toString().toUpperCase()
.equals(BleAdapterService.ALERT_LEVEL_CHARACTERISTIC)
&& bundle.get(BleAdapterService.PARCEL_SERVICE_UUID).toString().toUpperCase()
.equals(BleAdapterService.LINK_LOSS_SERVICE_UUID)) {
b = bundle.getByteArray(BleAdapterService.PARCEL_VALUE);
if (b.length > 0) {
PeripheralControlActivity.this.setAlertLevel((int) b[0]);
Log.d(Constants.TAG, "Current alert_level is set to: " + b[0]);
// show the rssi distance colored rectangle
((LinearLayout) PeripheralControlActivity.this
.findViewById(R.id.rectangle))
.setVisibility(View.VISIBLE);
// start off the rssi reading timer
startReadRssiTimer();
}
}
break;
case BleAdapterService.GATT_CHARACTERISTIC_WRITTEN:
bundle = msg.getData();
Log.d(Constants.TAG, "Service=" + bundle.get(BleAdapterService.PARCEL_SERVICE_UUID).toString().toUpperCase() + " Characteristic=" + bundle.get(BleAdapterService.PARCEL_CHARACTERISTIC_UUID).toString().toUpperCase());
if (bundle.get(BleAdapterService.PARCEL_CHARACTERISTIC_UUID).toString()
.toUpperCase().equals(BleAdapterService.ALERT_LEVEL_CHARACTERISTIC)
&& bundle.get(BleAdapterService.PARCEL_SERVICE_UUID).toString()
.toUpperCase().equals(BleAdapterService.LINK_LOSS_SERVICE_UUID)) {
b = bundle.getByteArray(BleAdapterService.PARCEL_VALUE);
Log.d(Constants.TAG, "New alert_level set to: " + b[0]);
PeripheralControlActivity.this.setAlertLevel((int) b[0]);
}
break;
}
}
};
public void onLow(View view) {
bluetooth_le_adapter.writeCharacteristic(BleAdapterService.LINK_LOSS_SERVICE_UUID, BleAdapterService.ALERT_LEVEL_CHARACTERISTIC, Constants.ALERT_LEVEL_LOW);
}
public void onMid(View view) {
bluetooth_le_adapter.writeCharacteristic(BleAdapterService.LINK_LOSS_SERVICE_UUID, BleAdapterService.ALERT_LEVEL_CHARACTERISTIC, Constants.ALERT_LEVEL_MID);
}
public void onHigh(View view) {
bluetooth_le_adapter.writeCharacteristic(BleAdapterService.LINK_LOSS_SERVICE_UUID, BleAdapterService.ALERT_LEVEL_CHARACTERISTIC, Constants.ALERT_LEVEL_HIGH);
}
public void onNoise(View view) {
byte[] al = new byte[1];
al[0] = (byte) alert_level;
bluetooth_le_adapter.writeCharacteristic(BleAdapterService.IMMEDIATE_ALERT_SERVICE_UUID, BleAdapterService.ALERT_LEVEL_CHARACTERISTIC, al);
}
public void onBackPressed() {
Log.d(Constants.TAG, "onBackPressed");
back_requested = true;
if (bluetooth_le_adapter.isConnected()) {
try {
bluetooth_le_adapter.disconnect();
} catch (Exception e) {
}
} else {
finish();
}
}
private void setAlertLevel(int alert_level) {
this.alert_level = alert_level;
((Button) this.findViewById(R.id.lowButton)).setTextColor(Color.parseColor("#000000"));
;
((Button) this.findViewById(R.id.midButton)).setTextColor(Color.parseColor("#000000"));
;
((Button) this.findViewById(R.id.highButton)).setTextColor(Color.parseColor("#000000"));
;
switch (alert_level) {
case 0:
((Button) this.findViewById(R.id.lowButton)).setTextColor(Color.parseColor("#FF0000"));
;
break;
case 1:
((Button) this.findViewById(R.id.midButton)).setTextColor(Color.parseColor("#FF0000"));
;
break;
case 2:
((Button) this.findViewById(R.id.highButton)).setTextColor(Color.parseColor("#FF0000"));
;
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_peripheral_control);
// read intent data
final Intent intent = getIntent();
device_name = intent.getStringExtra(EXTRA_NAME);
device_address = intent.getStringExtra(EXTRA_ID);
// show the device name
((TextView) this.findViewById(R.id.nameTextView)).setText("Device : " + device_name + " [" + device_address + "]");
// hide the coloured rectangle used to show green/amber/red rssi distance
((LinearLayout) this.findViewById(R.id.rectangle)).setVisibility(View.INVISIBLE);
// hide the coloured rectangle used to show green/amber/red rssi
// distance
((LinearLayout) this.findViewById(R.id.rectangle))
.setVisibility(View.INVISIBLE);
// disable the noise button
((Button) PeripheralControlActivity.this.findViewById(R.id.noiseButton))
.setEnabled(false);
// disable the LOW/MID/HIGH alert level selection buttons
((Button) this.findViewById(R.id.lowButton)).setEnabled(false);
((Button) this.findViewById(R.id.midButton)).setEnabled(false);
((Button) this.findViewById(R.id.highButton)).setEnabled(false);
share_switch = (Switch) this.findViewById(R.id.switch1);
share_switch.setEnabled(false);
share_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (bluetooth_le_adapter != null) {
share_with_server = isChecked;
if (!isChecked && bluetooth_le_adapter.isConnected()) {
showMsg("Switched off sharing proximity data");
// write 0,0 to cause Arduino to switch off all LEDs
if (bluetooth_le_adapter.writeCharacteristic(
BleAdapterService.PROXIMITY_MONITORING_SERVICE_UUID,
BleAdapterService.CLIENT_PROXIMITY_CHARACTERISTIC,
new byte[]{0, 0})) {
} else {
showMsg("Failed to inform Arduino sharing has been disabled");
}
}
}
}
});
// connect to the Bluetooth adapter service
Intent gattServiceIntent = new Intent(this, BleAdapterService.class);
bindService(gattServiceIntent, service_connection, BIND_AUTO_CREATE);
showMsg("READY");
}
#Override
protected void onDestroy() {
super.onDestroy();
stopTimer();
unbindService(service_connection);
bluetooth_le_adapter = null;
}
private void showMsg(final String msg) {
Log.i(Constants.TAG, msg);
runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView) findViewById(R.id.msgTextView)).setText(msg);
}
});
}
public void onConnect(View view) {
showMsg("onConnect");
if (bluetooth_le_adapter != null) {
if (bluetooth_le_adapter.connect(device_address)) {
((Button) PeripheralControlActivity.this
.findViewById(R.id.connectButton)).setEnabled(false);
} else {
showMsg("onConnect: failed to connect");
}
} else {
showMsg("onConnect: bluetooth_le_adapter=null");
}
}
private void startReadRssiTimer() {
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
bluetooth_le_adapter.readRemoteRssi();
}
}, 0, 2000);
}
private void stopTimer() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
private void updateRssi(int rssi) {
((TextView) findViewById(R.id.rssiTextView)).setText("RSSI = "
+ Integer.toString(rssi));
LinearLayout layout = ((LinearLayout) PeripheralControlActivity.this
.findViewById(R.id.rectangle));
byte proximity_band = 3;
if (rssi < -80) {
layout.setBackgroundColor(0xFFFF0000);
} else if (rssi < -50) {
layout.setBackgroundColor(0xFFFF8A01);
proximity_band = 2;
} else {
layout.setBackgroundColor(0xFF00FF00);
proximity_band = 1;
}
layout.invalidate();
if (share_with_server) {
if (bluetooth_le_adapter.writeCharacteristic(
BleAdapterService.PROXIMITY_MONITORING_SERVICE_UUID,
BleAdapterService.CLIENT_PROXIMITY_CHARACTERISTIC,
new byte[]{proximity_band, (byte) rssi})) {
showMsg("proximity data shared: proximity_band:" + proximity_band + ",rssi:" + rssi);
} else {
showMsg("Failed to share proximity data");
}
}
}
}
BleAdapterService.java
public class BleAdapterService extends Service {
private BluetoothAdapter bluetooth_adapter;
private BluetoothGatt bluetooth_gatt;
private BluetoothManager bluetooth_manager;
private Handler activity_handler = null;
private BluetoothDevice device;
private BluetoothGattDescriptor descriptor;
private final IBinder binder = new LocalBinder();
public boolean isConnected() {
return connected;
}
private boolean connected = false;
// messages sent back to activity
public static final int GATT_CONNECTED = 1;
public static final int GATT_DISCONNECT = 2;
public static final int GATT_SERVICES_DISCOVERED = 3;
public static final int GATT_CHARACTERISTIC_READ = 4;
public static final int GATT_CHARACTERISTIC_WRITTEN = 5;
public static final int GATT_REMOTE_RSSI = 6;
public static final int MESSAGE = 7;
// message params
public static final String PARCEL_DESCRIPTOR_UUID = "DESCRIPTOR_UUID";
public static final String PARCEL_CHARACTERISTIC_UUID = "CHARACTERISTIC_UUID";
public static final String PARCEL_SERVICE_UUID = "SERVICE_UUID";
public static final String PARCEL_VALUE = "VALUE";
public static final String PARCEL_RSSI = "RSSI";
public static final String PARCEL_TEXT = "TEXT";
// service uuids
public static String IMMEDIATE_ALERT_SERVICE_UUID = "00001802-0000-1000-8000-00805F9B34FB";
public static String LINK_LOSS_SERVICE_UUID = "00001803-0000-1000-8000-00805F9B34FB";
public static String TX_POWER_SERVICE_UUID = "00001804-0000-1000-8000-00805F9B34FB";
public static String PROXIMITY_MONITORING_SERVICE_UUID = "3E099910-293F-11E4-93BD-AFD0FE6D1DFD";
// service characteristics
public static String ALERT_LEVEL_CHARACTERISTIC = "00002A06-0000-1000-8000-00805F9B34FB";
public static String CLIENT_PROXIMITY_CHARACTERISTIC = "3E099911-293F-11E4-93BD-AFD0FE6D1DFD";
public class LocalBinder extends Binder {
public BleAdapterService getService() {
return BleAdapterService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
// set activity the will receive the messages
public void setActivityHandler(Handler handler) {
activity_handler = handler;
}
private void sendConsoleMessage(String text) {
Message msg = Message.obtain(activity_handler, MESSAGE);
Bundle data = new Bundle();
data.putString(PARCEL_TEXT, text);
msg.setData(data);
msg.sendToTarget();
}
#Override
public void onCreate() {
if (bluetooth_manager == null) {
bluetooth_manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetooth_manager == null) {
return;
}
}
bluetooth_adapter = bluetooth_manager.getAdapter();
if (bluetooth_adapter == null) {
return;
}
}
// connect to the device
public boolean connect(final String address) {
if (bluetooth_adapter == null || address == null) {
sendConsoleMessage("connect: bluetooth_adapter=null");
return false;
}
device = bluetooth_adapter.getRemoteDevice(address);
if (device == null) {
sendConsoleMessage("connect: device=null");
return false;
}
bluetooth_gatt = device.connectGatt(this, false, gatt_callback);
return true;
}
// disconnect from device
public void disconnect() {
sendConsoleMessage("disconnecting");
if (bluetooth_adapter == null || bluetooth_gatt == null) {
sendConsoleMessage("disconnect: bluetooth_adapter|bluetooth_gatt null");
return;
}
if (bluetooth_gatt != null) {
bluetooth_gatt.disconnect();
}
}
public void readRemoteRssi() {
if (bluetooth_adapter == null || bluetooth_gatt == null) {
return;
}
bluetooth_gatt.readRemoteRssi();
}
public void discoverServices() {
if (bluetooth_adapter == null || bluetooth_gatt == null) {
return;
}
Log.d(Constants.TAG,"Discovering GATT services");
bluetooth_gatt.discoverServices();
}
public List<BluetoothGattService> getSupportedGattServices() {
if (bluetooth_gatt == null)
return null;
return bluetooth_gatt.getServices();
}
public boolean readCharacteristic(String serviceUuid,
String characteristicUuid) {
Log.d(Constants.TAG,"readCharacteristic:"+characteristicUuid+" of " +serviceUuid);
if (bluetooth_adapter == null || bluetooth_gatt == null) {
sendConsoleMessage("readCharacteristic: bluetooth_adapter|bluetooth_gatt null");
return false;
}
BluetoothGattService gattService = bluetooth_gatt
.getService(java.util.UUID.fromString(serviceUuid));
if (gattService == null) {
sendConsoleMessage("readCharacteristic: gattService null");
return false;
}
BluetoothGattCharacteristic gattChar = gattService
.getCharacteristic(java.util.UUID.fromString(characteristicUuid));
if (gattChar == null) {
sendConsoleMessage("readCharacteristic: gattChar null");
return false;
}
return bluetooth_gatt.readCharacteristic(gattChar);
}
public boolean writeCharacteristic(String serviceUuid,
String characteristicUuid, byte[] value) {
Log.d(Constants.TAG,"writeCharacteristic:"+characteristicUuid+" of " +serviceUuid);
if (bluetooth_adapter == null || bluetooth_gatt == null) {
sendConsoleMessage("writeCharacteristic: bluetooth_adapter|bluetooth_gatt null");
return false;
}
BluetoothGattService gattService = bluetooth_gatt
.getService(java.util.UUID.fromString(serviceUuid));
if (gattService == null) {
sendConsoleMessage("writeCharacteristic: gattService null");
return false;
}
BluetoothGattCharacteristic gattChar = gattService
.getCharacteristic(java.util.UUID.fromString(characteristicUuid));
if (gattChar == null) {
sendConsoleMessage("writeCharacteristic: gattChar null");
return false;
}
gattChar.setValue(value);
return bluetooth_gatt.writeCharacteristic(gattChar);
}
private final BluetoothGattCallback gatt_callback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
Log.d(Constants.TAG, "onConnectionStateChange: status=" + status);
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.d(Constants.TAG, "onConnectionStateChange: CONNECTED");
connected = true;
Message msg = Message.obtain(activity_handler, GATT_CONNECTED);
msg.sendToTarget();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.d(Constants.TAG, "onConnectionStateChange: DISCONNECTED");
Message msg = Message.obtain(activity_handler, GATT_DISCONNECT);
msg.sendToTarget();
if (bluetooth_gatt != null) {
Log.d(Constants.TAG,"Closing and destroying BluetoothGatt object");
connected = false;
bluetooth_gatt.close();
bluetooth_gatt = null;
}
}
}
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
sendConsoleMessage("RSSI read OK");
Bundle bundle = new Bundle();
bundle.putInt(PARCEL_RSSI, rssi);
Message msg = Message
.obtain(activity_handler, GATT_REMOTE_RSSI);
msg.setData(bundle);
msg.sendToTarget();
} else {
sendConsoleMessage("RSSI read err:"+status);
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
sendConsoleMessage("Services Discovered");
Message msg = Message.obtain(activity_handler,
GATT_SERVICES_DISCOVERED);
msg.sendToTarget();
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Bundle bundle = new Bundle();
bundle.putString(PARCEL_CHARACTERISTIC_UUID, characteristic.getUuid()
.toString());
bundle.putString(PARCEL_SERVICE_UUID, characteristic.getService().getUuid().toString());
bundle.putByteArray(PARCEL_VALUE, characteristic.getValue());
Message msg = Message.obtain(activity_handler,
GATT_CHARACTERISTIC_READ);
msg.setData(bundle);
msg.sendToTarget();
} else {
Log.d(Constants.TAG, "failed to read characteristic:"+characteristic.getUuid().toString()+" of service "+characteristic.getService().getUuid().toString()+" : status="+status);
sendConsoleMessage("characteristic read err:"+status);
}
}
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
Log.d(Constants.TAG, "onCharacteristicWrite");
if (status == BluetoothGatt.GATT_SUCCESS) {
Bundle bundle = new Bundle();
bundle.putString(PARCEL_CHARACTERISTIC_UUID, characteristic.getUuid().toString());
bundle.putString(PARCEL_SERVICE_UUID, characteristic.getService().getUuid().toString());
bundle.putByteArray(PARCEL_VALUE, characteristic.getValue());
Message msg = Message.obtain(activity_handler, GATT_CHARACTERISTIC_WRITTEN);
msg.setData(bundle);
msg.sendToTarget();
} else {
sendConsoleMessage("characteristic write err:" + status);
}
}
};
}
I forgot to add the service in the Manifest as this:
<service
android:name=".bluetooth.BleAdapterService"
android:enabled="true" />
I'm working with fragments and flipview but I'm having some problems with this.
When my app opens the first screen show my feed with the FlipView. When I choose another tab of my fragments the fragment of the feed didn't hide or detach. I debugged many times and the code arrives in the detached line but didn't work.
Here is my code
MainActivity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FontManager.getInstance().initialize(this, R.xml.fonts);
setContentView(R.layout.activity_main);
mFBSession = new FBSessionsManager();
mActionBar = getActionBar();
fm = getFragmentManager();
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
TabHost.OnTabChangeListener mTabChangeListener = new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
FeedPrincipalList mFeedFragment = (FeedPrincipalList) fm.findFragmentByTag(TAB_TAG_FEED);
EverythingFragmentList mEverythingFragment = (EverythingFragmentList) fm.findFragmentByTag(TAB_TAG_ALL_EVERYTHING);
PaymentFragment mPaymentFragment = (PaymentFragment) fm.findFragmentByTag(TAB_TAG_PAYMENT);
ConsultFragmentList mConsultFragmentList = (ConsultFragmentList) fm.findFragmentByTag(TAB_TAG_M_CONSULT);
ProfileFragmentList mProfileFragmentList = (ProfileFragmentList) fm.findFragmentByTag(TAB_TAG_M_PROFILE);
if (mFeedFragment != null){
ft.detach(mFeedFragment);
// ft.commit();
}
if (mEverythingFragment != null)
ft.detach(mEverythingFragment);
if (mPaymentFragment != null)
ft.detach(mPaymentFragment);
if (mConsultFragmentList != null)
ft.detach(mConsultFragmentList);
if (mProfileFragmentList != null){
ft.detach(mProfileFragmentList);
// ft.commit();
}
if (tabId.equalsIgnoreCase(TAB_TAG_FEED)) {
manageContextualActions(true, false);
if (mFeedFragment == null) {
mFeedFragment = new FeedPrincipalList();
ft.add(R.id.realTabContent, mFeedFragment, TAB_TAG_FEED);
} else {
mFeedFragment = new FeedPrincipalList();
ft.attach(mFeedFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_ALL_EVERYTHING)) {
manageContextualActions(false, true);
if (mEverythingFragment == null) {
mEverythingFragment = new EverythingFragmentList();
ft.replace(R.id.realTabContent, mEverythingFragment, TAB_TAG_ALL_EVERYTHING);
} else {
ft.attach(mEverythingFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_PAYMENT)) {
manageContextualActions(false, true);
if (mPaymentFragment == null) {
mPaymentFragment = new PaymentFragment();
ft.replace(R.id.realTabContent, mPaymentFragment, TAB_TAG_PAYMENT);
} else {
ft.attach(mPaymentFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_CONSULT)) {
manageContextualActions(false, true);
if (mConsultFragmentList == null) {
mConsultFragmentList = new ConsultFragmentList();
ft.replace(R.id.realTabContent, mConsultFragmentList, TAB_TAG_M_CONSULT);
} else {
ft.attach(mConsultFragmentList);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_PROFILE)) {
manageContextualActions(false, false);
if (mProfileFragmentList == null) {
mProfileFragmentList = new ProfileFragmentList();
ft.replace(R.id.realTabContent, mProfileFragmentList, TAB_TAG_M_PROFILE);
} else {
mProfileFragmentList = new ProfileFragmentList();
ft.attach(mProfileFragmentList);
}
}
ft.commit();
}
};
mTabHost.setOnTabChangedListener(mTabChangeListener);
createAndConfigureTabs();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
public void setupActionBar(int stringTitleID) {
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayUseLogoEnabled(false);
final LayoutInflater inflater = LayoutInflater.from(this);
final View customTitle = inflater.inflate(R.layout.custom_title, null);
((TextView) customTitle.findViewById(R.id.customTitleActionbar)).setText(getResources().getString(stringTitleID));
mActionBar.setCustomView(customTitle);
}
private void createAndConfigureTabs() {
mTabFeed = mTabHost.newTabSpec(TAB_TAG_FEED);
mTabFeed.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_feed));
mTabFeed.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabFeed);
mTabAllEverything = mTabHost.newTabSpec(TAB_TAG_ALL_EVERYTHING);
mTabAllEverything.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_all_everything));
mTabAllEverything.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabAllEverything);
mTabCameraAndPayment = mTabHost.newTabSpec(TAB_TAG_PAYMENT);
mTabCameraAndPayment.setIndicator(null, getResources().getDrawable(R.drawable.btn_camera));
mTabCameraAndPayment.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabCameraAndPayment);
mTabConsult = mTabHost.newTabSpec(TAB_TAG_M_CONSULT);
mTabConsult.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_consult));
mTabConsult.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabConsult);
mTabMyProfile = mTabHost.newTabSpec(TAB_TAG_M_PROFILE);
mTabMyProfile.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_profile));
mTabMyProfile.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabMyProfile);
mTabWidget = mTabHost.getTabWidget();
for (int i = 0; i minor 5; i++) {
View v = mTabWidget.getChildAt(i);
v.setBackgroundResource(android.R.drawable.screen_background_light_transparent);
if (i == 4)
v.setPadding(0, 0, 0, 12);
}
}
private class TabContentCreator implements TabHost.TabContentFactory {
private Context mContext;
public TabContentCreator(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
return v;
}
}
FeedFragment class
public class FeedPrincipalList extends android.app.Fragment implements FlipView.OnFlipListener, FlipView.OnOverFlipListener, FlipView.OnClickListener {
private static int timelinePage = 1, mPageCount = 0;
private FlipView mFlipView;
private FeedPrincipalAdapter mAdapter;
private FBSessionsManager fbSessionsManager;
private List mList;
private Context context;
private int posicaoTela;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
View view = inflater.inflate(R.layout.feed_flipview, container);
((MainFragmentActivity) getActivity()).setupActionBar(R.string.title_fragment_feed);
mFlipView = (FlipView) view.findViewById(R.id.fv_feedFlipView_FlipView);
mFlipView.setOnFlipListener(this);
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(view.findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
mFlipView.setOnClickListener(this);
fbSessionsManager = new FBSessionsManager(getActivity());
if (mList == null)
new LoadFeedPrincipalData().execute();
return super.onCreateView(inflater,container,savedInstanceState);
}
#Override
public void onFlippedToPage(FlipView v, int position, long id) {
Log.i("pageflip", "Page: " + position);
posicaoTela = position;
if(position > mFlipView.getPageCount()-3 && mFlipView.getPageCount() {
private UtilWS ws;
private JSONObject toSend;
private JsonArray rsArray;
private JsonParser parser;
public LoadFeedPrincipalData() {
ws = new UtilWS();
toSend = new JSONObject();
parser = new JsonParser();
}
#Override
protected Void doInBackground(Void... params) {
try {
toSend.put("token", fbSessionsManager.getStoredPrivateSession()[0]);
toSend.put("userId", fbSessionsManager.getStoredPrivateSession()[1]);
toSend.put("page", timelinePage);
String[] jsonResult = ws.post(UtilWS.URL_TIMELINE, toSend.toString());
if (jsonResult[0].equals("200")) {
JsonObject temp = parser.parse(jsonResult[1]).getAsJsonObject();
Log.i("JSON",": "+temp.toString());
if (temp.get("success").getAsBoolean()) {
rsArray = temp.get("looks").getAsJsonArray();
if (mPageCount == 0)
mPageCount = temp.get("pageCount").getAsInt();
for (JsonElement el : rsArray) {
if (mList == null)
mList = new ArrayList();
temp = (JsonObject) el;
FeedPrincipalTO tempTudo = new FeedPrincipalTO(temp.get("lookId").getAsString(), temp.get("photoUrl1").getAsString(), temp.get("photoUrl2").getAsString(), temp.get("jaVotou").getAsBoolean(),temp.get("photoVoted").getAsInt() ,temp.get("photo1Total").getAsString(), temp.get("photo2Total").getAsString());
mList.add(tempTudo);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (mList != null) {
Log.i("mList","mLista");
mAdapter = new FeedPrincipalAdapter(context,mList);
mAdapter.setCallback(new FeedPrincipalAdapter.Callback() {
#Override
public void onPageRequested(int page) {
mFlipView.smoothFlipTo(page);
}
#Override
public void voteUp(int position) {
Log.i("TESTE","position = " + posicaoTela);
mAdapter.getView(position, null, null).postInvalidate();
// mAdapter.notifyDataSetChanged();
}
});
if (timelinePage == 1) {
mFlipView.setAdapter(mAdapter);
// initListenerList();
} else {
((FeedPrincipalAdapter) mFlipView.getAdapter()).updateList(mList);
((FeedPrincipalAdapter) mFlipView.getAdapter()).notifyDataSetChanged();
}
} else {
mFlipView.setAdapter(new FeedPrincipalAdapter(context,null));
}
}
// private void initListenerList() {
// getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
// #Override
// public void onScrollStateChanged(AbsListView view, int scrollState) {
//
// }
//
// #Override
// public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
// if (timelinePage minor mPageCount) {
// timelinePage++;
// new LoadFeedPrincipalData().execute();
// }
// }
// }
// });
// }
}
}
Please, help me with this!!!
I'm using the FlipView https://github.com/emilsjolander/android-FlipView
Thanks!!!
Finally I solved this problem.
First I changed my Main Class a little.
I changed this two ifs (this fragments uses FlipView) in the MainActivity class.
if (tabId.equalsIgnoreCase(TAB_TAG_FEED)) {
manageContextualActions(true, false);
if (mFeedFragment == null) {
mFeedFragment = new FeedPrincipalList();
ft.add(R.id.realTabContent, mFeedFragment, TAB_TAG_FEED);
} else {
// mFeedFragment = new FeedPrincipalList();
ft.attach(mFeedFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_PROFILE)) {
manageContextualActions(false, false);
if (mProfileFragmentList == null) {
mProfileFragmentList = new ProfileFragmentList();
ft.add(R.id.realTabContent, mProfileFragmentList, TAB_TAG_M_PROFILE);
} else {
// mProfileFragmentList = new ProfileFragmentList();
ft.attach(mProfileFragmentList);
}
}
Second I changed my method onCreateView of my FeedFragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
((MainFragmentActivity) getActivity()).setupActionBar(R.string.title_fragment_feed);
fbSessionsManager = new FBSessionsManager(getActivity());
if (mList == null){
view = inflater.inflate(R.layout.feed_flipview, container,true);
mFlipView = (FlipView) view.findViewById(R.id.fv_feedFlipView_FlipView);
mFlipView.setOnFlipListener(this);
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(view.findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
new LoadFeedPrincipalData().execute();
}
return super.onCreateView(inflater,container,savedInstanceState);
}
You can see the difference. I only inflate the view in the first time. After this my mList(it's a List of MyGetSetClass) it's not null anymore.
And to finish I Override this two methods on my FeedFragment class.
#Override
public void onDetach() {
super.onDetach();
// Log.i("onDetach", "FeedPrincipalList");
mList = null;
timelinePage = 1;
mPageCount = 0;
}
#Override
public void onStart() {
super.onStart();
// Log.i("onStart", "FeedPrincipalList");
this.mFlipView.setVisibility(View.VISIBLE);
}
#Override
public void onStop() {
super.onStop();
// Log.i("onStop","FeedPrincipalList");
this.mFlipView.setVisibility(View.INVISIBLE);
}
In the detach method I clean all my static variables that I will use when I start the app again.
The onStart and the onStop I use to change the Visibility of my FlipView.
That's it.
I hope this help everyone!!!
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;
}
}