How to convert a Fragment to a Activity Android? - android

I have a working app using threads in fragments, the thing is I need to change the layout. It's not gonna be a Fragment anymore but a standard Activity.
My big problem is that I don't know exactly where to place what's in "onViewCreated" and "onCreateView" so it's crashing when I call "connect to device" which's placed on "onCreateView". Probably because it's too early or something.
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View view;
view = inflater.inflate(R.layout.fragment_home_2, container, false);
//Linking layout views
connectToDevice = view.findViewById(R.id.connect_to_device);
startRecording = view.findViewById(R.id.start_recording);
stopRecording = view.findViewById(R.id.stop_recording);
connectedToDevice = view.findViewById(R.id.connected_to_device);
mAdapter = new DeviceListAdapter(container.getContext(), activeDevices);
imgEkoDevice = view.findViewById(R.id.img_ekodevice);
//Enable bluetooth and start scanning thread
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter != null && !btAdapter.isEnabled()) {
btAdapter.enable();
}
//Layout setup
connectedToDevice.setText(getResources().getString(R.string.welcome_to_scopefy));
//Thread setup to search for device
scanningThread = new Thread(){
#Override
public void run(){
Log.i(AppConstants.TAG, "scanning...");
LibCore.getInstance(ConnectDeviceActivity.this).startScanningForDevices(new EkoDeviceScan() {
#Override
public void foundDevice(BLEDevice bleDevice) {
//Log.i(AppPreferences.log, "foundDevice: " + bleDevice.toString());
if(activeDevices.isEmpty()){
//Adding first device to list
activeDevices.add(bleDevice);
}
else{
int i = 0;
newDevice = true;
//Checks if its already on the list
while(i < activeDevices.size() && newDevice){
if(activeDevices.get(i).getAddress().equals(bleDevice.getAddress())){
newDevice = false;
}
i++;
}
if(newDevice){
activeDevices.add(bleDevice);
}
}
//Show list and dismiss search dialog
if(connect){
showDeviceListDialog();
if(emptyListDialog != null){
emptyListDialog.dismiss();
}
connect = false;
}
}
});
}
};
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).registerReceiver(mDeviceReceiver, new IntentFilter(Parameters.DEVICE_REFRESH_DATA));
//Starting scanning background to speed up
if(LibCore.getInstance(ConnectDeviceActivity.this).getCurrentConnectedDevice() == null){
scanningThread.start();
LibCore.getInstance(ConnectDeviceActivity.this).setFiltering(true);
connected = false;
} else {
mEkoDevice = LibCore.getInstance(ConnectDeviceActivity.this).getCurrentConnectedDevice();
connected = true;
}
//Broadcast receiver for patientId
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).registerReceiver(mPatientReceiver, new IntentFilter(Parameters.PATIENT_ID));
//Listeners and receivers for device connection
LibCore.getInstance(ConnectDeviceActivity.this).setBatteryListener(new EkoDeviceBatteryLevel() {
#Override
public void deviceUpdatedBatteryLevel(float v) {
Log.i("HUEBR123", "updateou bat");
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).sendBroadcast(new Intent(Parameters.DEVICE_REFRESH_DATA).putExtra(Parameters.DEVICE_UPDATED_BATTERY_LEVEL, v));
}
});
LibCore.getInstance(ConnectDeviceActivity.this).setVolumeListener(new EkoDeviceVolume() {
#Override
public void deviceUpdatedVolumeLevel(int i) {
Log.i("HUEBR123", "updateou vol");
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).sendBroadcast(new Intent(Parameters.DEVICE_REFRESH_DATA).putExtra(Parameters.DEVICE_UPDATED_VOLUME_LEVEL, i));
}
});
//Settings
userSettingsDAO = new UserSettingsDAO(ConnectDeviceActivity.this);
settings = userSettingsDAO.getUserSettings();
//Button's listeners
connectToDevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connect = true;
scanningThread.run();
showDeviceListEmptyDialog();
}
});
startRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(AppConstants.TAG, "starting recording...");
stopped = false;
startRecording();
//startPlayRecordThroughEko();
startRecording.setVisibility(View.GONE);
stopRecording.setVisibility(View.VISIBLE);
recording = true;
settings = userSettingsDAO.getUserSettings();
settings.getRecordingLength();
Timer timer = new Timer();
TimerTask task = new StopRecordingTask();
timer.schedule(task, settings.getRecordingLength() * 1000);
Log.i(AppConstants.TAG, "#timer starting for " + settings.getRecordingLength() + " seconds");
}
});
stopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
mEkoOutputAudioByteListener = null;
mAudioFileOutputStream.close();
writeWAVHeader(mCachedAudioRecordingFile, 4000);
//writeWAVHeader(mCachedECGRecordingFile, 500);
stopOutputtingAudioDataPoints();
} catch (Exception e) {
e.printStackTrace();
}
startRecording.setVisibility(View.VISIBLE);
stopRecording.setVisibility(View.GONE);
recording = false;
short[] output;
output = new short[outData.size() * 32];
for(int i=0; i<outData.size(); i++){
for(int j=0; j<32; j++){
output[i] = outData.get(i)[j];
}
}
Intent intent = new Intent(ConnectDeviceActivity.this, AuscultationActivity.class);
intent.putExtra("output", output);
intent.putExtra("patient-id", patientId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i(AppConstants.TAG, "OUPUTLEN: " + output.length);
if(!stopped) {
stopped = true;
startActivity(intent);
}
}
});
return view;
}
//This overridden method makes DynamicWaveformViews avoid crashing
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dynamicWaveformView = (DynamicWaveformView) view.findViewById(R.id.dynamic_waveform_view);
dynamicWaveformView.init();
mAudioThread = new HandlerThread("AudioThread");
mAudioThread.start();
mAudioHandler = new Handler(mAudioThread.getLooper());
//updateView again for consistency (mDeviceBroadcast may be too much but still works)
updateView(connected);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEkoDevice = new EkoDevice("DUMMY_DEVICE", "0");
buyNow = findViewById(R.id.buyNow);
back = findViewById(R.id.back_icon);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
buyNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
}
});
changeAudioAmplitudeScaleFactor(8);
mPlayerManager = new PlayerManager();
mPlayerManager.onCreate();
LibCore.getInstance(ConnectDeviceActivity.this).setFiltering(true);
}
trying to place at the bottom of "onCreate" it gives me the following error:
PopupWindow $BadTokenException: Unable to add window — token null is not valid

Regarding you error
PopupWindow $BadTokenException: Unable to add window — token null is
not valid
Maybe add that code in the Activity onResume() lifecykle method instead of onCreate if it need to run more then one time
Move the scanningThread, BluetoothAdapter and LocalBroadcastManager LibCore everything to the 'onCreate()' . The 'onCreateView()' should only have the view = inflater.inflate(R.layout.fragment_home_2, container, false);
The onCreate() only initiate stuff hook up local variables views and set clicklisteners. Like all the one-time-stuff. Going from Fragment to Activity is basically almost the same since they have the same lifecykle methods
Check this nice explanation about the-android-lifecycle-cheat-sheet

Related

Issue with bundle value in onClickListener method

Im having some troubles with retrieving a bundle value in my onClickListener method or any other method in general. I have comments besides the code for better clarification. So what happens is i get a value from activityA put it in a bundle and pass the values to my fragment. I get the value from the bundle and set in my setter method the value i get from the bundle is not null if i toast the value it shows the correct one on the screen. Below im posting my whole onCreateMethod, im having this issue for the past couple of days so any help is greatly appreciated. What i think happens is that when i try to get the value from the bundle in my onClickListener method it resets itself to 0 for some reason.
Thanks for your help in advance
My onCreateView method in fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_todo_list, container, false);
FloatingActionButton floatingActionButton = view.findViewById(R.id.fab);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
bundle = this.getArguments();
if(bundle != null) {
fk_id = bundle.getLong("fk");
setId_2(fk_id); // i try to set the value
Toast.makeText(getContext(), "iz fragmenta" + getId_2(), Toast.LENGTH_SHORT).show(); // this prints the correct value
floatingActionButton.setOnClickListener(new View.OnClickListener() { //this button stops working if in the if statement
#Override
public void onClick(View v) {
LayoutInflater li = LayoutInflater.from(getActivity());
View popupView = li.inflate(R.layout.popup_layout, null);
final EditText editText = popupView.findViewById(R.id.userInput);
AlertDialog.Builder adb = new AlertDialog.Builder(getContext());
adb.setView(popupView);
adb.setCancelable(false)
.setPositiveButton("Dodaj", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String naziv = editText.getText().toString();
Aktivnost_ ak = new Aktivnost_(naziv, "15-jun", fk_id, "kajetan", "todo");
dodajAktivnost(ak);
array.add(ak);
Toast.makeText(getContext(), "dodano" + getId_2(), Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Prekliči", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
Toast.makeText(getContext(), "Preklical sem", Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mmAdapter = new ToDoRecyclerViewAdapter(listAktivnosti(getId_2()), getContext(), mListener);
mmAdapter.setOnItemClickListner(new ToDoRecyclerViewAdapter.onItemClickListner() {
#Override
public void onClick(long i) {
Intent intent = new Intent(getActivity(), PodrobnostiActivity.class);
intent.putExtra("key_id", i);
startActivity(intent);
Toast.makeText(getContext(), "" + i, Toast.LENGTH_SHORT).show();
}
});
mmAdapter.setOnLongClick(new ToDoRecyclerViewAdapter.OnLongClickListener_() {
#Override
public void onLongClick(long i, String item) {
if (item.equals("doing")) {
boolean update_1 = db.updateList(i, item);
if (update_1) {
//NAREDI SE LEPE ANIMACIJE
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(TodoFragment.this).attach(TodoFragment.this).commit();
Toast.makeText(getContext(), "Dodano v bazo.!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Prislo je do napake!", Toast.LENGTH_SHORT).show();
}
}
}
});
recyclerView.setAdapter(mmAdapter);
}
return view;
}
EDITED
private long fk_id;
public long getId_2() {
return fk_id;
}
public void setId_2(long fk_id) {
this.fk_id = fk_id;
}
EDIT_2
This part is in my activities onCreate
Intent intent = getIntent();
long id = intent.getLongExtra("intVariableName",0);
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, TodoFragment.newInstance(id), "a");
fragmentTransaction.commit();
And i made a newInstance method in my fragment.
public static TodoFragment newInstance(long id) {
TodoFragment fragment = new TodoFragment();
Bundle b = new Bundle();
b.putLong("fk",id);
fragment.setArguments(b);
return fragment;
}
Try the following:
Since you already have access to the data within your variable fk_id in your Fragment, you can mark it as final, and pass it to your Toast:
Toast.makeText(getContext(), "dodano" + fk_id, Toast.LENGTH_LONG).show();
OR
Try marking your getId_2 and setId_2 with synchronized as well as your onCreateView(), this way, the data shared between the two methods will be synchronized.

android custom list view is refreshing after deleting first item from list

I am developing an android application, in that i using displaying pull notifications. I am getting the list of notification from backend and displaying in the form of custom list view.The problem is i am providing a button to delete particular notification from list view when ever i tried to delete the notification at any index it is deleting but after scrolling the entire list view is getting refreshed. How can i handle this?
one more thing is i am not using notifysetdatachange() anywhere.
public class NotificationListViewHolder extends BaseListAdapter.ViewHolder {
//timeStamp, userName;
public final CircleImageView profilePicture;
public final TextView timeStamp;
public final ImageView deleteNotification;
public final ProgressBar progressBar;
public final RelativeLayout notificationListItem;
public TextView requirement;
public LinearLayout clickableArea;
NotificationListViewHolder viewHolder;
NotificationListAdapter listAdapter;
public NotificationListViewHolder(View view, BaseListAdapterListener listener, NotificationListAdapter listAdapter) {
super(view, listener);
requirement = view.findViewById(R.id.requirement);
profilePicture = view.findViewById(R.id.profile_picture);
notificationListItem = view.findViewById(R.id.notification_list_item);
deleteNotification = view.findViewById(R.id.delete_notification);
progressBar = view.findViewById(R.id.progressBar);
clickableArea = view.findViewById(R.id.clickable_area);
timeStamp = view.findViewById(R.id.time_stamp);
this.listAdapter = listAdapter;
}
public void bind(final Notification entry, NotificationListViewHolder holder) {
try {
if (holder.notificationListItem.getTag() == null) {
holder.notificationListItem.setTag(holder);
} else {
viewHolder = (NotificationListViewHolder) holder.notificationListItem.getTag();
}
viewHolder.progressBar.setVisibility(entry.isSelected()
? View.VISIBLE : View.GONE);
viewHolder.deleteNotification.setVisibility(entry.isSelected()
? View.GONE : View.VISIBLE);
viewHolder.requirement.setText(entry.getRequirement());
if (entry.getRoleName().equals("")) {
viewHolder.timeStamp.setText(TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
} else {
viewHolder.timeStamp.setText(entry.getRoleName() + " - " + TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
}
if (viewHolder.profilePicture != null && !entry.getProfileUrl().equalsIgnoreCase("")) {
Picasso.with(D4E.getContext()).load(D4E.getContext().getResources().getString(R.string.liferay_server) + entry.getProfileUrl()).placeholder(R.drawable.default_profile_pic)
.error(R.drawable.default_profile_pic).into(viewHolder.profilePicture);
}
if (entry.getType() == 1) { // light grey , my post notifications || other post notification
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#C8FAD2"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
} else if (entry.getType() == 2) {
// the posts by others
/* viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#DCDCDC"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));*/
} else if (entry.getType() == 0) { // dark grey , admin
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#FAFAC8"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
}
viewHolder.clickableArea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
entry.setSelected(true);
deleteNotification();
viewHolder.progressBar.setVisibility(View.VISIBLE);
viewHolder.deleteNotification.setVisibility(View.GONE);
}
private void deleteNotification() {
Session session = SessionContext.createSessionFromCurrentSession();
session.setCallback(new Callback() {
#Override
public void inBackground(Response response) {
((Activity) D4E.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
try {
viewHolder.progressBar.setVisibility(View.GONE);
AnimatorUtil.animate(viewHolder/*, true*/);
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(listAdapter.getEntries().size());
/* listAdapter.notifyDataSetChanged();
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
listAdapter.notifyItemRangeChanged(viewHolder.getLayoutPosition(), listAdapter.getEntries().size());
listAdapter.notifyDataSetChanged();
UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(listAdapter.getEntries().size());*/
/*if (listAdapter.getEntries().size() == 0)
(() D4E.getContext()).onNoListItem();*/
} catch (Exception e) {
Log.e("Ex:Noti_List_Adp", "" + e.toString());
}
}
});
}
#Override
public void doFailure(Exception exception) {
viewHolder.progressBar.setVisibility(View.GONE);
viewHolder.deleteNotification.setVisibility(View.VISIBLE);
entry.setSelected(false);
}
});
try {
new DeccategoryService(session).DeleteNotification(Long.parseLong(entry.getNotificationId()));
} catch (Exception e) {
e.printStackTrace();
}
}
});
/* if (holder.notificationListItem.getTag() == null) {
holder.notificationListItem.setTag(holder);
} else {
viewHolder = (NotificationListViewHolder) holder.notificationListItem.getTag();
}*/
/* viewHolder.clickableArea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
entry.setSelected(true);
// adapter.removeItem(entry,getAdapterPosition());
openDeleteNotification();
viewHolder.progressBar.setVisibility(View.VISIBLE);
viewHolder.deleteNotification.setVisibility(View.GONE);
}
private void openDeleteNotification() {
Session session = SessionContext.createSessionFromCurrentSession();
session.setCallback(new Callback() {
#Override
public void inBackground(Response response) {
((Activity) D4E.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
viewHolder.progressBar.setVisibility(View.GONE);
adapter.removeItem(entry, getAdapterPosition());
}
});
}
#Override
public void doFailure(Exception exception) {
viewHolder.progressBar.setVisibility(View.GONE);
viewHolder.deleteNotification.setVisibility(View.VISIBLE);
entry.setSelected(false);
}
});
try {
new DeccategoryService(session).DeleteNotification(Long.parseLong(entry.getNotificationId()));
} catch (Exception e) {
e.printStackTrace();
}
}
});*/
viewHolder.progressBar.setVisibility(entry.isSelected()
? View.VISIBLE : View.GONE);
viewHolder.deleteNotification.setVisibility(entry.isSelected()
? View.GONE : View.VISIBLE);
viewHolder.requirement.setText(entry.getRequirement());
if (entry.getRoleName().equals("")) {
viewHolder.timeStamp.setText(TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
} else {
viewHolder.timeStamp.setText(entry.getRoleName() + " - " + TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
}
if (viewHolder.profilePicture != null && !entry.getProfileUrl().equalsIgnoreCase("")) {
Picasso.with(D4E.getContext()).load(D4E.getContext().getResources().getString(R.string.liferay_server) + entry.getProfileUrl()).placeholder(R.drawable.default_profile_pic)
.error(R.drawable.default_profile_pic).into(viewHolder.profilePicture);
}
if (entry.getType() == 1) {
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#F2F2F2"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
} else if (entry.getType() == 2) {
/* viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#DCDCDC"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));*/
} else {
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#FFFFFF"));//admin post color
}
// FontStyle.getInstance().FontStyleByGroupOfIds(view.getContext(), new int[]{R.id.notification_list_item}, view);
} catch (Exception e) {
Log.e("Exception", e.toString());
}
}
public void createDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(D4E.getContext());
builder.setTitle("Alert!");
builder.setMessage("Message from Admin");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
}
public class Notifications extends Scheduler implements ScreenletListListener, SearchView.OnQueryTextListener, NoListListener, UpdateLogout {
public static boolean isInSettingsPage;
public static long notificationId;
public static String notificationSearchKeyword = "";
public static boolean notificationSearchActivated = false;
public static boolean navigatedFromPush = false;
ArrayList<digital.engineers.club.models.Notifications> notificationsModel;
BottomSheetDialog dialog;
View dialogView;
Menu menu;
GenericScreenlet screenlet;
SearchView searchView;
MenuItem searchMenuItem;
LinearLayout container;
View screenletView, noIntimationView;
private boolean shudRefreshOnResume = false;
//Push test
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
setContext(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
container = findViewById(R.id.ns);
D4E.setContext(this);
FontStyle.getInstance().setContext(this);
getSupportActionBar().setTitle(FontStyle.getInstance()
.getSpannableString(getSupportActionBar().getTitle().toString()));
container = findViewById(R.id.container);
noIntimationView = View.inflate(this, R.layout.no_list_intimation, null);
refreshNotifications();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notification_menu, menu);
this.menu = menu;
final MenuItem menuItem = menu.findItem(R.id.nsettings);
BitmapDrawable icon = (BitmapDrawable) menuItem.getIcon();
Drawable drawable = DrawableCompat.wrap(icon);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.white));
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(this);
searchView.setSubmitButtonEnabled(false);
searchView.setIconifiedByDefault(true);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (isInSettingsPage) {
resetNotificationPage();
isInSettingsPage = false;
} else {
if (navigatedFromPush) {
startActivity(new Intent(this, HomeScreen.class));
navigatedFromPush = false;
} else
finish();
}
} else if (item.getItemId() == R.id.search) {
} else if (item.getItemId() == R.id.nsettings) {
isInSettingsPage = true;
loadSettings();
}
return super.onOptionsItemSelected(item);
}
public void loadSettings() {
FontStyle.getInstance().setContext(this);
getSupportActionBar().setTitle(FontStyle.getInstance().getSpannableString("Notification Settings"));
container.removeAllViews();
if (searchMenuItem.isActionViewExpanded())
searchMenuItem.collapseActionView();
menu.getItem(0).setVisible(false);
menu.getItem(1).setVisible(false);
getFragmentManager().beginTransaction().replace(R.id.container, new NotificationSettingsFragment()).commit();
}
private void openbootomsheet() {
dialog = new BottomSheetDialog(Notifications.this);
dialogView = View.inflate(Notifications.this, R.layout.search_posts, null);
dialogView.findViewById(R.id.search_by_time_layout);
dialog.setContentView(dialogView);
((Spinner) dialogView.findViewById(R.id.posted_time)).setAdapter(new ArrayAdapter<String>(Notifications.this, android.R.layout.simple_list_item_1,
android.R.id.text1,
getResources().getStringArray(R.array.day_search)));
((Spinner) dialogView.findViewById(R.id.role)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
android.R.id.text1,
getResources().getStringArray(R.array.roles)));
dialog.show();
dialogView.findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialogView.findViewById(R.id.search_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#Override
public void onListPageReceived(int startRow, int endRow, List<Object> entries, int rowCount) {
// Toast.makeText(this,"Success",Toast.LENGTH_LONG).show();
//UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(0);
UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(entries.size());
if (entries.size() == 0) {
showNoNotificationIntimation();
}
/*screenlet.setVisibility(entries.size() > 0 ? View.VISIBLE : View.GONE);
((LinearLayout) findViewById(R.id.no_list_layout)).setVisibility(entries.size() > 0 ? View.GONE : View.VISIBLE);*/
}
#Override
public void onListItemSelected(Object element, View view) {
Notification notification = (Notification) element;
if (notification != null) {
if (((Notification) element).getType() != 0) {
notificationId = Long.parseLong(notification.getNotificationId());
NewPost.postType = (SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId())) ?
getResources().getString(R.string.post_type_my_post) :
getResources().getString(R.string.post_type_relevant_post);
Map<String, Object> postMap = new HashMap<>();
postMap.put("threadId", notification.getThreadId());
postMap.put("profileUrl", SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId()) ?
UserInfoController.initializeUserInfoController().getUserInfo().getProfileUrl() :
notification.getProfileUrl());
postMap.put("firstName", notification.getFirstName());
postMap.put("lastName", notification.getLastName());
postMap.put("categoryId", notification.getCategoryId());
postMap.put("timestamp", notification.getTimestamp());
postMap.put("subject", notification.getSubject());
postMap.put("threadStatus", notification.getThreadStatus());
postMap.put("userId", String.valueOf(SessionContext.getUserId()));
postMap.put("postedUserId", notification.getPostedUserId());
postMap.put("userName", notification.getUserName());
postMap.put("roleName", notification.getRoleName());
// postMap.put("attachment",notification.getAttachment());
ViewThread.post = new Post(postMap);
ViewThread.post.setAttachment(notification.getAttachment());
NewPost.currentPostId = ViewThread.post.getThreadId();
NewPost.currentPosition = (SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId())) ?
0 : 1; // View Pager position
NewPost.postedUserId = Long.parseLong(ViewThread.post.getPostedUserId());
HomeScreen.categoryId = Long.parseLong(ViewThread.post.getCategoryId());
Intent intent = new Intent(Notifications.this, ViewThread.class);
intent.putExtra("THREAD", ViewThread.post);
startActivity(intent);
} else {
createDialog(notification.getRequirement());
}
}
}
#Override
public void error(Exception e, String userAction) {
// Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onListPageFailed(int startRow, Exception e) {
// Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void interactorCalled() {
}
#Override
protected void onResume() {
super.onResume();
if (isScreenOn(this) && hasTimedOut) {
initializeTimer();
resetTimeOut();
startSessionTimeCountDown();
}
if (shudRefreshOnResume) {
if (!isInSettingsPage) {
refreshNotifications();
shudRefreshOnResume = false;
} else {
loadSettings();
}
}
}
#Override
protected void onPause() {
super.onPause();
shudRefreshOnResume = true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 3) {
notificationSearchKeyword = newText;
notificationSearchActivated = true;
refreshNotifications();
} else if (newText.length() == 0) {
notificationSearchKeyword = "";
notificationSearchActivated = false;
refreshNotifications();
}
return true;
}
public void refreshNotifications() {
container.removeAllViews();
View notificationScreenlet = View.inflate(this, R.layout.notification_list_screenlet, null);
screenlet = notificationScreenlet.findViewById(R.id.notification_list_screenlet);
screenlet.setPagination();
screenlet.setListener(this);
container.addView(notificationScreenlet);
}
public void resetNotificationPage() {
FontStyle.getInstance().setContext(this);
getSupportActionBar().setTitle(FontStyle.getInstance().getSpannableString("Notifications"));
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
refreshNotifications();
notificationSearchActivated = false;
}
private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
for (int i = 0; i < menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item != exception) item.setVisible(visible);
}
}
#Override
public void onBackPressed() {
notificationSearchActivated = false;
if (isInSettingsPage) {
resetNotificationPage();
isInSettingsPage = false;
} else {
if (navigatedFromPush) {
startActivity(new Intent(this, HomeScreen.class));
navigatedFromPush = false;
} else
finish();
}
}
public void createDialog(String message) {
final AlertDialog.Builder builder = new AlertDialog.Builder(D4E.getContext());
builder.setTitle("Message from Admin");
builder.setMessage(message);
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
public void showNoNotificationIntimation() {
container.removeAllViews();
noIntimationView.findViewById(R.id.no_list_layout).setLayoutParams(new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
container.addView(noIntimationView);
}
#Override
public void onNoListItem() {
showNoNotificationIntimation();
}
#Override
public void onUpdatedLogoutToServer() {
//if (SessionHelper.initializeSessionHelper().logout()) {
DisplayDialog.display(this);
/*} else {
Log.e("LogoutErr", "Homescreen: Unable to Logout");
}*/
}
#Override
public void onError(Exception e) {
Toast.makeText(getApplicationContext(), "Unable to logout from scheduler", Toast.LENGTH_SHORT).show();
}
when you delete item form list that time remove that item form list and notify adapter.
like below code ... when i am delete any item form recycler view ..
yourlist.remove(yourlist.get(yourlist.indexOf(data))); // common data that pass in list.if List<String> that pass string data if object them pass that object data.
youradapter.notifyDataSetChanged();
As per documentation you should not use this method with viewholder. you should use getAdapterposition() to get position of row.
getLayoutPosition added in version 22.1.0
int getLayoutPosition ()
Returns the position of the ViewHolder in terms of the latest layout
pass.
This position is mostly used by RecyclerView components to be
consistent while RecyclerView lazily processes adapter updates.
For performance and animation reasons, RecyclerView batches all
adapter updates until the next layout pass. This may cause mismatches
between the Adapter position of the item and the position it had in
the latest layout calculations.
LayoutManagers should always call this method while doing calculations
based on item positions. All methods in RecyclerView.LayoutManager,
RecyclerView.State, RecyclerView.Recycler that receive a position
expect it to be the layout position of the item.
If LayoutManager needs to call an external method that requires the
adapter position of the item, it can use getAdapterPosition() or
convertPreLayoutPositionToPostLayout(int).
In your use case, since your data is related to your adapter contents (and I assume that data is changed at the same time with adapter changes), you should be using adapterPosition.
Replace this lines
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
with
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getAdapterPosition()));
listAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());

Android: How can I make a listview wait for a variable to fill before setting?

So I have a movie trivia game that I am building. The problem I am running into is on the main user profile page I set 3 listviews. One for games where it is your turn, one for games that are waiting for your opponent, and one for completed games. These list views make calls to Parse.com to fetch the game object. In Order to fetch this info from Parse I need to provide my query with a Facebook user id. My code calls Facebook to get the ID, but the listview adapters run about 5 milliseconds before the call to Facebook returns the ID. When the user refreshes the page, the lists load properly, but when first running the app they are blank. Here is the user profile activity code:
public class UserProfileActivity extends AppCompatActivity {
ParseLogic mPl;
private WfoAdapter wfoAdapter;
private WoyAdapter woyAdapter;
private CompletedGameAdapter completedGameAdapter;
private TicketSystem mTicketsSytem;
String mMyFbId;
String mMyFbName;
int mTickets;
ListView mWfoListView;
ListView mWoyListView;
ListView mCompletedGameListView;
TextView mmTicketNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTicketsSytem = new TicketSystem();
mTickets = mTicketsSytem.getTickets();
setContentView(R.layout.activity_user_profile);
new getFbDeets().execute(); //This is where the async task is called
mPl = new ParseLogic();
mWoyListView = (ListView)findViewById(R.id.waitingForYouListView);
mWfoListView = (ListView)findViewById(R.id.waitingForOpponentListView);
mCompletedGameListView = (ListView)findViewById(R.id.completedGameListView);
mmTicketNumber = (TextView)findViewById(R.id.numberOfTickets);
mmTicketNumber.setText(String.valueOf(mTickets));
FaceBookFriends.getFaceBookFriends();
//Testing start game remove when building rest of page
Button button = (Button)findViewById(R.id.startNewGame);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UserProfileActivity.this, GameStart.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
mTickets = mTicketsSytem.getTickets();
mmTicketNumber.setText(String.valueOf(mTickets));
populateWoyListView();
populateWfoListView();
populateCompleteListView();
}
#Override
public void onBackPressed(){}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//create the logout button in action bar
switch (item.getItemId()){
case R.id.logoutButton:
ParseUser.logOut();
ParseUser currentUser = ParseUser.getCurrentUser(); // this will now be null
Intent intent = new Intent(UserProfileActivity.this, WelcomeActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void populateUI() {
populateWoyListView();
populateWfoListView();
populateCompleteListView();
mWoyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String goTV = ((TextView) view.findViewById(R.id.gameObjectHiddenTextView)).getText().toString();
String score = ((TextView) view.findViewById(R.id.woyScoreNumber)).getText().toString();
Log.v("Clicked Object Id ", goTV);
Intent intent = new Intent(UserProfileActivity.this, AreYouReady.class);
intent.putExtra("Score", score);
intent.putExtra("Object Id", goTV);
startActivity(intent);
}
});
}
private void populateWoyListView() {
//mMfbId is the variable set by the facebook call
woyAdapter = new WoyAdapter(this ,mMyFbId);
woyAdapter.loadObjects();
mWoyListView.setAdapter(woyAdapter);
}
private void populateWfoListView() {
wfoAdapter = new WfoAdapter(this);
wfoAdapter.loadObjects();
mWfoListView.setAdapter(wfoAdapter);
}
private void populateCompleteListView() {
completedGameAdapter = new CompletedGameAdapter(this, mMyFbId);
completedGameAdapter.loadObjects();
mCompletedGameListView.setAdapter(completedGameAdapter);
}
protected class getFbDeets extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
mMyFbId = FaceBookFriends.getMyFbId();
mMyFbName = FaceBookFriends.getMyFbName();
Log.v("getFbDeets() ", "Is Running");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
populateUI();
}
}
}
This is the completed gave adapter:
/**
* Created by Tom Schinler on 9/23/2015.
*/
public class CompletedGameAdapter extends ParseQueryAdapter<Game> {
String mWinnerScore;
String mWinnerName;
String mLoserScore;
String mLoserName;
String mFbName;
public CompletedGameAdapter(Context context, final String myFbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
ParseQuery<Game> queryCreatedBy = new ParseQuery<Game>("Game");
queryCreatedBy.whereEqualTo("Created_By", ParseUser.getCurrentUser());
ParseQuery<Game> queryOppOf = new ParseQuery<Game>("Game");
queryOppOf.whereEqualTo("Opponent_Id", myFbId);
ParseQuery<Game> query = ParseQuery.or(Arrays.asList(queryCreatedBy, queryOppOf));
query.whereNotEqualTo("Creator_Score", "");
query.whereNotEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.completed_game_layout, null);
}
super.getItemView(game, view, parent);
mFbName = FaceBookFriends.getMyFbName();
TextView winOrLose = (TextView)view.findViewById(R.id.winOrLose);
int oppScore = Integer.parseInt(game.getOpponentScore());
int creatScore = Integer.parseInt(game.getCreatorScore());
if(oppScore > creatScore){
mWinnerScore = String.valueOf(oppScore);
mWinnerName = game.getOpponentName();
mLoserScore = String.valueOf(creatScore);
mLoserName = game.getCreatorFbName();
}
else {
mWinnerScore = String.valueOf(creatScore);
mWinnerName = game.getCreatorFbName();
mLoserScore = String.valueOf(oppScore);
mLoserName = game.getOpponentName();
}
TextView winnerName = (TextView)view.findViewById(R.id.winnerName);
winnerName.setText(mWinnerName);
TextView winnerScore = (TextView)view.findViewById(R.id.winnerScore);
winnerScore.setText(mWinnerScore);
TextView loserName = (TextView)view.findViewById(R.id.loserName);
loserName.setText(mLoserName);
TextView loserScore = (TextView)view.findViewById(R.id.loserScore);
loserScore.setText(mLoserScore);
if(mWinnerName.equals(mFbName)){
view.setBackgroundColor(Color.GREEN);
winOrLose.setText("WIN!!");
}
else {
view.setBackgroundColor(Color.RED);
winOrLose.setText("LOSER!!");
}
return view;
}
}
and here is the adapter that sets the listview for games waiting on the user:
/**
* Created by Tom Schinler on 9/22/2015.
*/
public class WoyAdapter extends ParseQueryAdapter<Game>{
public WoyAdapter(Context context, final String fbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
//Log.v("var fbid is ", fbId);
ParseQuery query = new ParseQuery("Game");
query.whereEqualTo("Opponent_Id", fbId);
query.whereEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.waiting_on_you_layout, null);
Log.v("WOY is this", "running");
}
super.getItemView(game, view, parent);
ProfilePictureView friendPic = (ProfilePictureView) view.findViewById(R.id.woyFbPic);
String friendId = game.getCreatorId();
if(friendId != null){
friendPic.setProfileId(friendId);
}
TextView oppName = (TextView)view.findViewById(R.id.woyNameText);
oppName.setText(game.getCreatorFbName());
TextView oppScore = (TextView)view.findViewById(R.id.woyScoreNumber);
oppScore.setText(game.getCreatorScore());
TextView GOTV = (TextView)view.findViewById(R.id.gameObjectHiddenTextView);
GOTV.setText(game.getObjectId());
return view;
}
}
I set mMyFbId with a Facebook method like this:
mMyFbId = FaceBookFriends.getMyFbId();
but it return about 1 second after the code runs to build the lists views, since they do not have the variable, they populate nothing. Please help.

Android radial menu increase radial redius

I want to implement a radial menu widget and i have used radial-menu-v4 jar. My code is as follows...
public class RadialMenuActivity extends Activity {
private RadialMenuWidget pieMenu;
public Activity activity = this;
RelativeLayout l1;
public RadialMenuItem menuItem1,menuItem2,menuItem3,menuItem4,menuItem5,menuItem6,menuItem7,menuItem8,menuItem9,menuItem10, menuCloseItem, menuExpandItem;
public RadialMenuItem firstChildItem, secondChildItem, thirdChildItem;
private List<RadialMenuItem> children = new ArrayList<RadialMenuItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radial);
pieMenu = new RadialMenuWidget(this);
l1 = (RelativeLayout)findViewById(R.id.reltv1);
l1.addView(pieMenu);
menuCloseItem = new RadialMenuItem("Close", "Menu");
//menuCloseItem.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem1 = new RadialMenuItem("1","j");
menuItem1.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
/*firstChildItem = new RadialMenuItem("First","First");
firstChildItem.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
#Override
public void execute() {
startActivity(new Intent(RadialMenuActivity.this, TestActivity.class));
pieMenu.dismiss();
}
});
secondChildItem = new RadialMenuItem("Second",null);
secondChildItem.setDisplayIcon(R.drawable.ic_launcher);
secondChildItem.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
#Override
public void execute() {
Toast.makeText(RadialMenuActivity.this, "Second inner menu selected.", Toast.LENGTH_LONG).show();
}
});
thirdChildItem = new RadialMenuItem("Third","Third");
thirdChildItem.setDisplayIcon(R.drawable.ic_launcher);
thirdChildItem.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
#Override
public void execute() {
Toast.makeText(RadialMenuActivity.this, "Third inner menu selected.", Toast.LENGTH_LONG).show();
}
});*/
menuItem2 = new RadialMenuItem("2", "a");
menuItem2.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem3 = new RadialMenuItem("3", "i");
menuItem3.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem4 = new RadialMenuItem("4", "b");
menuItem4.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem5 = new RadialMenuItem("5", "c");
menuItem5.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem6 = new RadialMenuItem("6", "d");
menuItem6.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem7 = new RadialMenuItem("7", "e");
menuItem7.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem8 = new RadialMenuItem("8", "f");
menuItem8.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem9 = new RadialMenuItem("9", "g");
menuItem9.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
menuItem10 = new RadialMenuItem("10", "h");
menuItem10.setDisplayIcon(android.R.drawable.ic_menu_close_clear_cancel);
/*children.add(firstChildItem);
children.add(secondChildItem);
children.add(thirdChildItem);*/
//menuExpandItem.setMenuChildren(children);
menuCloseItem.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
#Override
public void execute() {
//menuLayout.removeAllViews();
pieMenu.dismiss();
}
});
menuItem1.setOnMenuItemPressed(new RadialMenuItem.RadialMenuItemClickListener() {
#Override
public void execute() {
startActivity(new Intent(RadialMenuActivity.this, TestActivity.class));
pieMenu.dismiss();
}
});
//pieMenu.setDismissOnOutsideClick(true, menuLayout);
int xLayoutSize = l1.getWidth();
int yLayoutSize = l1.getHeight();
pieMenu.setAnimationSpeed(0L);
//pieMenu.setSourceLocation(200, 200);
pieMenu.setSourceLocation(1000,1000);
pieMenu.setIconSize(10, 20);
pieMenu.setTextSize(10);
pieMenu.setOutlineColor(Color.WHITE, 225);
//pieMenu.setInnerRingColor(0xAA66CC, 10000000);
//pieMenu.setOuterRingColor(0x0099CC, 10000000);
//pieMenu.setCenterCircleRadius(40);
pieMenu.setOuterRingRadius(600, 600);
//pieMenu.setInnerRingRadius(100,100);
//pieMenu.setHeader("Test Menu", 20);
pieMenu.setCenterCircle(menuCloseItem);
pieMenu.addMenuEntry(new ArrayList<RadialMenuItem>() {{
add(menuItem1);
add(menuItem2);
add(menuItem3);
add(menuItem4);
add(menuItem5);
add(menuItem6);
add(menuItem7);
add(menuItem8);
add(menuItem9);
add(menuItem10);
}});
//pieMenu.addMenuEntry(menuItem);
//pieMenu.addMenuEntry(menuExpandItem);
/*Button testButton = (Button) this.findViewById(R.id.radial_menu_btn);
testButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//menuLayout.addView(pieMenu);
pieMenu.show(v);
}
});*/
}
But I cant increase outer radius of the circle. I am using min sdk version 8. Please help me with this. Thank you in advance.

Keep a view alive while switching activity

I created a game, where I rotate through multiple activitys. Each activity stays just for a few seconds. Now I should add ads to the game. Since it doesn't make sense if the ad refreshes after just a few seconds I have to create a view which stays alive the whole time even if I start a new activity.
Since a view is bind to an activity (?) it might not be possible. So I wonder wether there is another solution to keep the adView alive while the content views are rotating.
Thanks in advance.
Edit:
Here is a simple Activity which is part of the activity cycle:
public class Punish extends ActivityWithSound implements OnClickListener {
#SuppressWarnings("unused")
private final String TAG = "Punish";
private RelativeLayout buttonContainer;
private ImageView bgImg;
private TextView nameTxt;
private TextView questTxt;
private Button mainMenuBtn;
private Button okBtn;
private Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
bundle = getIntent().getExtras();
if(bundle == null)
bundle = StbApp.getTempBundle();
setContentView(R.layout.quest);
setupView();
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
soundtrack.startFX(R.raw.fx_execution);
super.onResume();
}
#Override
protected void onPause() {
StbApp.getTempBundle().putInt(Victim.VICTIM, bundle.getInt(Victim.VICTIM));
soundtrack.stopAllFX();
super.onPause();
}
#Override
public void onClick(View view) {
if (view == mainMenuBtn){
//TODO Continue Function
Intent intent = new Intent(this, TitleScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
StbApp.setContinueBtn(true);
StbApp.getLastActivity().setClass(this, Punish.class);
startActivity(intent);
}
if (view == okBtn){
if (StbApp.getPenalty() == PenaltyType.LEAVE){
StbApp.getPlayer().remove(bundle.getInt(Victim.VICTIM));
StbApp.setNumberOfPlayer(StbApp.getNumberOfPlayer()-1);
}
if (StbApp.getNumberOfPlayer() == 2 && StbApp.getPenalty() == PenaltyType.LEAVE)
startActivity(new Intent(this, GameOver.class));
else {
startActivity(new Intent(this, Round.class));
}
}
}
#Override
public void onBackPressed() {
return;
}
private void setupView() {
float textSize = (float) getResources().getDimension(R.dimen.standard_text_size)/getResources().getDisplayMetrics().scaledDensity;
buttonContainer = (RelativeLayout) findViewById(R.id.container_button);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) findViewById(R.id.container_button).getLayoutParams();
params.setMargins(0, 0, 0, (int) (StbApp.AdHeight*1.3));
buttonContainer.setLayoutParams(params);
bgImg = (ImageView) findViewById(R.id.imgv_girl);
Log.d(TAG, "PlayerSize " + StbApp.getPlayer().size());
nameTxt = (TextView) findViewById(R.id.text_victim_name);
Log.d(TAG, "PlayerSize " + StbApp.getPlayer().size());
Log.d(TAG, "PlayerIndex bundle.getInt(Victim.VICTIM) " + bundle.getInt(Victim.VICTIM));
nameTxt.setText(StbApp.getPlayer().get(bundle.getInt(Victim.VICTIM)).getName());
nameTxt.setTextSize(textSize);
questTxt = (TextView) findViewById(R.id.text_quest);
switch (StbApp.getPenalty()) {
case LEAVE:
questTxt.setText(getResources().getString(R.string.punish_leave));
break;
case DRNK:
questTxt.setText(getResources().getString(R.string.punish_drink));
break;
case UNDRESS:
questTxt.setText(getResources().getString(R.string.punish_undress));
break;
}
questTxt.setTextSize(textSize);
mainMenuBtn = (Button) findViewById(R.id.button_mainmenu);
mainMenuBtn.setOnClickListener(this);
okBtn = (Button) findViewById(R.id.button_ok);
okBtn.setOnClickListener(this);
}
#Override
protected void onDestroy() {
if (bgImg.getDrawable() != null){
bgImg.getDrawable().setCallback(null);
bgImg.setImageDrawable(null);
}
super.onDestroy();
}
What I need would be an alternative for onDestroy, onPause and onResume.
A solution could be using a ViewFlipper/ViewSwitcher instead of jumping activities and then placing the adsView over or under the ViewFlipper/ViewSwitcher - It will however probably require quite a large re-write of your app.

Categories

Resources