Equalizer stops 10 seconds after exiting the fragment - java

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);
}
}

Related

Unable to play video in Wowza GoCoder's PlayerActivity

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

Splash Screen using AsyncTask

I have a splash screen using AsyncTask, it will download some data from database and store the data in ArrayList. This ArrayList will be used for RecyclerView in fragments of MainActivity.class.
The problem is when I run the app from Android Studio to my phone, everything works perfectly. But, when I destroy the app and run it manually from my phone it will display blank white screen and then it will crash. And if I run once again after it crashed, the app will work. So, this app will always work only if I run it from Android Studio or after it crashed.
The error says that it is caused by the empty list. If I'm not mistaken, I think the AsyncTask doesn't seem to work properly after the activity is destroyed. But I don't know how to fix it. Please help me to solve this problem.
SplashScreen.java
public class SplashScreenActivity extends AppCompatActivity {
public static Event event;
private static List<Feed> feedList;
private static List<Event> eventList;
private static List<Event> todayList;
private static List<Event> upcomingList;
private static List<Partner> partnerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
Config.TODAY_DATE = String.valueOf(today.monthDay) + "-" + String.valueOf(today.month) + "-" + String.valueOf(today.year);
new DownloadData().execute("");
}
class DownloadData extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
startActivity(new Intent(getBaseContext(), WelcomeActivity.class));
finish();
}
#Override
protected String doInBackground(String... params) {
RequestHandler rh = new RequestHandler();
String JSON_STRING = rh.sendGetRequest(Config.URL_GET_ALL_DATA);
JSONObject jsonObject;
eventList = new ArrayList<>();
todayList = new ArrayList<>();
upcomingList = new ArrayList<>();
partnerList = new ArrayList<>();
feedList = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray getEvent = jsonObject.getJSONArray(Config.TAG_JSON_EVENT);
for (int i = 0; i < getEvent.length(); i++) {
int id = getEvent.getJSONObject(i).getInt(Config.TAG_ID);
int eoId = getEvent.getJSONObject(i).getInt(Config.TAG_EO_ID);
String eoName = getEvent.getJSONObject(i).getString(Config.TAG_EO_NAME);
String title = getEvent.getJSONObject(i).getString(Config.TAG_TITLE);
String day = getEvent.getJSONObject(i).getString(Config.TAG_DAY);
String date = getEvent.getJSONObject(i).getString(Config.TAG_DATE);
int price = getEvent.getJSONObject(i).getInt(Config.TAG_PRICE);
event = new Event(id, eoId, eoName, title, day, date, price);
eventList.add(event);
if(Config.TODAY_DATE.equals(event.getDate())){
todayList.add(event);
} else {
upcomingList.add(event);
}
}
JSONArray getPartner = jsonObject.getJSONArray(Config.TAG_JSON_PARTNER);
for (int i = 0; i < getPartner.length(); i++) {
int pId = getPartner.getJSONObject(i).getInt(Config.TAG_ID);
String pName = getPartner.getJSONObject(i).getString(Config.TAG_NAME);
String pEmail = getPartner.getJSONObject(i).getString(Config.TAG_EMAIL);
String pPhone = getPartner.getJSONObject(i).getString(Config.TAG_PHONE);
String pPhoto = getPartner.getJSONObject(i).getString(Config.TAG_PHOTO_URL);
Partner partner = new Partner(pId, pName, pEmail, pPhone, pPhoto);
partnerList.add(partner);
}
JSONArray getArticle = jsonObject.getJSONArray(Config.TAG_JSON_ARTICLE);
for (int i = 0; i < getArticle.length(); i++) {
int feedId = getArticle.getJSONObject(i).getInt(Config.TAG_ID);
String feedAuthor = getArticle.getJSONObject(i).getString(Config.TAG_FEED_AUTHOR);
String feedTitle = getArticle.getJSONObject(i).getString(Config.TAG_FEED_TITLE);
String feedContent = getArticle.getJSONObject(i).getString(Config.TAG_FEED_CONTENT);
String feedDate = getArticle.getJSONObject(i).getString(Config.TAG_FEED_DATE);
String feedThumbnail = getArticle.getJSONObject(i).getString(Config.TAG_FEED_THUMBNAIL);
Feed feed = new Feed(feedId, feedAuthor, feedTitle, feedContent, feedDate, feedThumbnail);
feedList.add(feed);
}
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
}
public static List<Feed> getFeedList(){ return feedList;}
public static List<Event> getEventList() {return eventList;}
public static List<Event> getTodayList() { return todayList;}
public static List<Event> getUpcomingList() { return upcomingList;}
public static List<Partner> getPartnerList() {return partnerList;}
}
DiscoverFragment.java
public class DiscoverFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
protected View view;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
private List<Feed> feedList;
private List<Event> eventList;
private List<Partner> partnerList;
public DiscoverFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discover, container, false);
RecyclerView recyclerViewEvent = (RecyclerView) view.findViewById(R.id.discover_event_recycler_view);
RecyclerView recyclerViewPartner = (RecyclerView) view.findViewById(R.id.discover_partner_recycler_view);
ClickableViewPager intro_images = (ClickableViewPager) view.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) view.findViewById(R.id.viewPagerCountDots);
eventList = SplashScreenActivity.getEventList();
partnerList = SplashScreenActivity.getPartnerList();
feedList = SplashScreenActivity.getFeedList();
EventAdapter eventAdapter = new EventAdapter(getContext(), eventList);
DiscoverPartnerAdapter discoverPartnerAdapter = new DiscoverPartnerAdapter(getContext(), partnerList);
DiscoverFeedAdapter mAdapter = new DiscoverFeedAdapter(getContext(), feedList);
final LinearLayoutManager layoutManagerEvent = new LinearLayoutManager(getContext());
final LinearLayoutManager layoutManagerPartner = new LinearLayoutManager(getContext());
layoutManagerEvent.setOrientation(LinearLayoutManager.HORIZONTAL);
layoutManagerPartner.setOrientation(LinearLayoutManager.HORIZONTAL);
addBottomDots(0);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(0);
intro_images.addOnPageChangeListener(this);
intro_images.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Config.FEED_ID = position;
startActivity(new Intent(getContext(), ArticleActivity.class));
}
});
return view;
}
private void addBottomDots(int currentPage) {
dots = new ImageView[feedList.size()]; //the problem
pager_indicator.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
if (dots.length > 0)
dots[currentPage].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
LogCat
01-29 00:40:57.565 32535-32535/com.irmaelita.esodiaapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.irmaelita.esodiaapp, PID: 32535
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.addBottomDots(DiscoverFragment.java:181)
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.onCreateView(DiscoverFragment.java:158)
feedList is null. You create feedList instance when DownloadData task is executed. But you call feedList.size() in addBottomDots when fragment view should be created. So, most probably addBottomDots is called before DownloadData task is executed. You need to fix it.
The feedlist in your discover fragment is going empty while initializing. Please set a null check before doing so.It not about running from android studio.If I have understood it correctly you are trying to access a list from splasScreen activity after finishing it. ie in post execute you finish the current activity and the fragment is in main activity,so the list is going null.So if this is the case (and please correct me if not) then either download the data somewhere centrally or best way send it to main activity with intent and use it there. Also when running from android studio kill the app manually and run it again,while the phone is connected and see if it crashes in current scenario.
Send your data from doInBackground to MainActivity with sendBroadcast
Add broadcast method in DownloadData class
private void broadcast(SplashParcel parcel) {
Intent i = new Intent("splash_parcel");
i.putExtra("values", parcel);
sendBroadcast(i);
}
#Override
protected String doInBackground(String... params) {
// your code
// ..
try {
// your code
// ..
// send splashParcel to MainActivity
SplashParcel splashParcel = new SplashParcel(feedList, eventList, todayList, upcomingList, partnerList);
broadcast (splashParcel);
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
Add new class SplashParcel.java
public class SplashParcel implements Parcelable {
public static final Creator<SplashParcel> CREATOR = new Creator<SplashParcel>() {
#Override
public SplashParcel createFromParcel(Parcel in) {
return new SplashParcel(in);
}
#Override
public SplashParcel[] newArray(int size) {
return new SplashParcel[size];
}
};
private static List<Feed> _feedList;
private static List<Event> _eventList;
private static List<Event> _todayList;
private static List<Event> _upcomingList;
private static List<Partner> _partnerList;
protected SplashParcel(Parcel in) {
_feedList = new ArrayList<Feed>();
in.readList(_feedList, null);
_eventList = new ArrayList<Event>();
in.readList(_eventList, null);
_todayList = new ArrayList<Event>();
in.readList(_todayList, null);
_upcomingList = new ArrayList<Event>();
in.readList(_upcomingList, null);
_partnerList = new ArrayList<Partner>();
in.readList(_partnerList, null);
}
public SplashParcel(List<Feed> feedList, List<Event> eventList, List<Event> todayList, List<Event> upcomingList, List<Partner> partnerList) {
_feedList = feedList;
_eventList = eventList;
_todayList = todayList;
_upcomingList = upcomingList;
_partnerList = partnerList;
}
public SplashParcel() {
}
public List<Feed> getFeedList() {
return _feedList;
}
public void setFeedList(List<Feed> feedList) {
_feedList = feedList;
}
public List<Event> getEventList() {
return _eventList;
}
public void setEventList(List<Event> eventList) {
_eventList = eventList;
}
public List<Event> getTodayList() {
return _todayList;
}
public void setTodayList(List<Event> todayList) {
_todayList = todayList;
}
public List<Event> getUpcomingList() {
return _upcomingList;
}
public void setUpcomingList(List<Event> upcomingList) {
_upcomingList = upcomingList;
}
public List<Partner> getPartnerList() {
return _partnerList;
}
public void setPartnerList(List<Partner> partnerList) {
_partnerList = partnerList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(_feedList);
parcel.writeList(_eventList);
parcel.writeList(_todayList);
parcel.writeList(_upcomingList);
parcel.writeList(_partnerList);
}
}
MainActivity.java
// member variable
private BroadcastReceiver _splashReceiver;
private Bundle _bundle = new Bundle();
#Override
protected void onResume() {
super.onResume();
splashReceiver();
}
// receive splashParcel from SplashScreenActivity
private void splashReceiver() {
if (_splashReceiver == null) {
_splashReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SplashParcel splashParcel = intent.getParcelableExtra("values");
if (splashParcel != null) {
// save splashParcel into _budle
_bundle.putParcelable("splash_parcel", splashParcel);
}
}
};
registerReceiver(_splashReceiver, new IntentFilter("splash_parcel"));
}
}
//Send _bundle to DiscoverFragment
private void showDiscoverFragment(){
if(_bundle != null) {
// create instance of discoverFragment with passing _bundle as arguments
DiscoverFragment discoverFragment = new DiscoverFragment();
discoverFragment.setArguments(_bundle);
// replace activity_main.xml with discoverFragment
getSupportFragmentManager().beginTransaction().replace(R.id.main_container, discoverFragment).addBackStack(null).commit();
}
}
In onCreateView of DiscoverFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SplashParcel splashParcel = getArguments().getParcelable("splash_parcel");
if(splashParcel != null) {
// your splashParcel ready in here
List<Feed> feedList = splashParcel.getFeedList()
List<Event> eventList = splashParcel.getEventList()
List<Event> todayList = splashParcel.getTodayList();
List<Event> upcommingList = splashParcel.getUpcomingList();
List<Partner> partnerList = splashParcel.getPartnerList();
}
}

java.lang.IllegalStateException:The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged

I have a sliding image that extends pageradapter. At first it was working. But when i open new activity then press the back button the app is crashing and i've got this error :
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 10, found: 0 Pager id: malate.denise.chelsie.igphthesisbfinal:id/pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class malate.denise.chelsie.igphthesisbfinal.SlidingImage_Adapter
Here's my SlidingImage_Adapter.class
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Pictures> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context,ArrayList<Pictures> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.slidingimage_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
new DownloadImageTask(imageView).execute(IMAGES.get(position).getPhotopath());
// imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
notifyDataSetChanged();
}
#Override
public Parcelable saveState() {
return null;
}
and my AttractionInfo.class
public class AttractionInfo extends ActionBarActivity implements View.OnClickListener {
TextToSpeech tts;
TextView nameofplace,location,exact_address,operatinghours,info;
String nameofplace_s,location_s,exact_address_s,operatinghours_s,info_s,latlang_s,path_s,category_s;
ImageView play,rate,addtoplan,map;
ArrayList<Pictures> records;
private static ViewPager mPager;
private static int currentPage = 0;
String line=null;
private static int NUM_PAGES = 0;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_info);
map = (ImageView)findViewById(R.id.map);
map.setOnClickListener(this);
records=new ArrayList<Pictures>();
nameofplace = (TextView) findViewById(R.id.nameofplace);
info = (TextView) findViewById(R.id.info);
exact_address = (TextView) findViewById(R.id.exact_address);
location = (TextView)findViewById(R.id.location);
operatinghours=(TextView)findViewById(R.id.operatinghours);
play = (ImageView) findViewById(R.id.play);
rate = (ImageView) findViewById(R.id.rate);
addtoplan = (ImageView)findViewById(R.id.addtoplan);
addtoplan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
play.setOnClickListener(this);
rate.setOnClickListener(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayShowTitleEnabled(false);
tts = new TextToSpeech(AttractionInfo.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
if (extras != null) {
nameofplace_s = extras.getString("name");
nameofplace.setText(nameofplace_s);
info_s = extras.getString("description");
info.setText(info_s);
exact_address_s = extras.getString("exactaddress");
exact_address.setText(exact_address_s);
location_s = extras.getString("location");
location.setText(location_s);
operatinghours_s=extras.getString("operatinghours");
operatinghours.setText(operatinghours_s);
latlang_s = extras.getString("latlang");
path_s=extras.getString("path");
category_s = extras.getString("category");
}
}
public void onStart() {
super.onStart();
fetchphoto bt = new fetchphoto();
bt.execute();
}
#Override
protected void onPause() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
if (v == play) {
String speech1 = nameofplace.getText().toString();
String speech2 = info.getText().toString();
String speech = speech1 + "." + speech2;
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
} else if (v==rate){
Intent myIntent = new Intent(this, ListOfReviews.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if(v==addtoplan){
Intent myIntent = new Intent(this, AddPlan.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if (v == map){
Intent myIntent = new Intent(this, Map.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
myIntent.putExtra("latlang",latlang_s);
myIntent.putExtra("address",exact_address_s);
myIntent.putExtra("path",path_s);
startActivity(myIntent);
}
}
private void init() {
SlidingImage_Adapter adapter = new SlidingImage_Adapter(this,records);
for(int i=0;i<records.size();i++){
Pictures pics = records.get(i);
String pic = pics.getPhotopath();
adapter.notifyDataSetChanged();
}
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
CirclePageIndicator indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES =records.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},5000, 5000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
private class fetchphoto extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("cityname", nameofplace_s));
try
{
records.clear();
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getphoto.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pictures p = new Pictures();
p.setPhotoname(json_data.getString("photo_name"));
p.setPlacename(json_data.getString("place_name"));
p.setCategory(json_data.getString("category"));
p.setPhotopath(json_data.getString("path"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
init();
}
}
}
I've red some similar problems and learned that adding notifychanged may solved the problem but i dont where to place it. Hope you can help m . thanks

Detach isn't working (Two Fragments with FlipView)

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!!!

Error with xml HttpGet

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;
}
}

Categories

Resources