How to Show ListView Items in Tabs - android

In Contacts Tab, trying to fetch list of all Facebook Friends
In Month Tab, trying to fetch list of Facebook Friends those Birthdays in Current Month
In Week Tab, trying to fetch list of Facebook Friends those Birthdays in Current Week
I have written code for all and i am not getting any error while build and run my program, but i am not getting list of friends in any of the Tab.
Please let me know, where i am doing silly mistake...where i am missing..
TabSample.Java :-
public class TabSample extends TabActivity {
String response;
private static JSONArray jsonArray;
public static TabHost mTabHost;
private MyFacebook fb = MyFacebook.getInstance();
public static MyLocalDB db = null;
private BcReceiver bcr = null;
private BcReceiverAlarm bcra = null;
private PendingIntent mAlarmSender;
private boolean isAlarmSet;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlarmSender = PendingIntent.getService(TabSample.this, 0, new Intent(
TabSample.this, BdRemService.class), 0);
setContentView(R.layout.main);
if (db == null) {
db = new MyLocalDB(this);
db.open();
}
if (!fb.isReady()) {
Log.v(TAG, "TabSample- initiating facebook");
fb.init(this);// after finishing, this will call loadContents itself
} else {
loadContents();
}
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Refreshing");
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
response = getIntent().getStringExtra("FRIENDS");
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
FacebookUtility.displayMessageBox(this,
this.getString(R.string.json_failed));
}
setTabs();
}
private void setTabs() {
addTab("Contacts", com.chr.tatu.sample.friendslist.ContactTab.class);
addTab("Month", com.chr.tatu.sample.friendslist.MonthTab.class);
addTab("Week", com.chr.tatu.sample.friendslist.WeekTab.class);
}
private void setupTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
}
private void setupTab(final View view, final String tag, Intent intent,
int id) {
View tabview = createTabView(mTabHost.getContext(), tag, id);
TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview)
.setContent(intent);
mTabHost.addTab(setContent);
}
private void addTab(String labelId, Class<?> c) {
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
intent.putExtra("FRIENDS", response);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}
private static View createTabView(final Context context, final String text,
final int id)
{
View view = LayoutInflater.from(context).inflate(
R.layout.tab_indicator, null);
return view;
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.BIRTHDAY_ALERT));
}
if (bcra == null) {
bcra = new BcReceiverAlarm();
registerReceiver(bcra, new IntentFilter(MyUtils.ALARM_RESET));
}
super.onResume();
}
public void loadContents() {
if (fb.getFriendsCount() > 0) {
return;
}
fb.setMyFriends(db.getAllFriends());
if (fb.getFriendsCount() > 0) {
notifyTabSample(Note.FRIENDLIST_CHANGED);
} else {
fb.reLoadAllFriends();
}
// 4. initiate alarm
if (!isAlarmSet) {
setAlarm(true);
}
}
private void setAlarm(boolean isON) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
if (isON) {
am.setRepeating(AlarmManager.RTC_WAKEUP, MyUtils
.getAlarmStartTimeAsLong(MyUtils.getAlarmHour(), MyUtils
.getAlarmMinute()), 24 * 60 * 60 * 1000,
mAlarmSender);
isAlarmSet = true;
Log.v(TAG, "TabSample- alarm set");
} else {
am.cancel(mAlarmSender);
isAlarmSet = true;
Log.v(TAG, "TabSample- alarm cancelled");
}
}
public void notifyTabSample(Note what) {
switch (what) {
case FRIENDLIST_RELOADED:
db.syncFriends(fb.getMyFriends());
sendBroadcast(new Intent(MyUtils.FRIENDLIST_CHANGED));
break;
case FRIENDLIST_CHANGED:
sendBroadcast(new Intent(MyUtils.FRIENDLIST_CHANGED));
// setup timer
break;
default:
break;
}
}
ContactTab.Java :-
public class ContactTab extends ListActivity {
private MyFacebook fb = MyFacebook.getInstance();
private BcReceiver bcr = null;
private MyAdapter adapter;
private List<MyFriend> list;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Refreshing");
}
private void refreshList() {
new Thread() {
public void run() {
list = fb.getAllFriends();
Log.v(TAG, "contactstab- refresh called. " + list.size());
adapter = new MyAdapter(ContactTab.this, list);
handler.sendEmptyMessage(0);
}
}.start();
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.FRIENDLIST_CHANGED));
}
refreshList();
super.onResume();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
MyFriend friend = (MyFriend) this.getListAdapter().getItem(position);
Intent intent = new Intent(ContactTab.this, PersonalGreeting.class);
intent.putExtra("fbID", friend.getFbID());
intent.putExtra("name", friend.getName());
intent.putExtra("pic", friend.getPic());
startActivity(intent);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.layout.menu, menu);
return (super.onPrepareOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.globalGreeting:
intent = new Intent(ContactTab.this, com.chr.tatu.sample.friendslist.GlobalGreeting.class);
startActivity(intent);
break;
case R.id.Settings:
intent = new Intent(ContactTab.this, com.chr.tatu.sample.friendslist.Settings.class);
startActivity(intent);
}
return (super.onOptionsItemSelected(item));
}
public class BcReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
public void run() {
refreshList();
}
});
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
setListAdapter(adapter);
//busyDialog.dismiss();
}
};
}
MonthTab.Java :-
public class MonthTab extends ListActivity {
private MyFacebook fb = MyFacebook.getInstance();
private BcReceiver bcr = null;
private MyAdapter adapter;
private List<MyFriend> list;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Please wait ...");
busyDialog.show();
refreshList();
}
private void refreshList() {
// list = fb.getFilteredFriends(Filter.MONTH);
list = fb.getFilteredFriends(Filter.MONTH);
adapter = new MyAdapter(MonthTab.this, list);
setListAdapter(adapter);
busyDialog.dismiss();
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.FRIENDLIST_CHANGED));
}
super.onResume();
}
#Override
#SuppressWarnings("unchecked")
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
MyFriend friend = (MyFriend) this.getListAdapter().getItem(position);
Intent intent = new Intent(MonthTab.this, PersonalGreeting.class);
intent.putExtra("fbID", friend.getFbID());
intent.putExtra("name", friend.getName());
startActivity(intent);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.layout.menu, menu);
return (super.onPrepareOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.globalGreeting:
intent = new Intent(MonthTab.this, GlobalGreeting.class);
startActivity(intent);
break;
case R.id.Settings:
intent = new Intent(MonthTab.this, Settings.class);
startActivity(intent);
}
return (super.onOptionsItemSelected(item));
}
public class BcReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
public void run() {
refreshList();
}
});
}
}
}

Related

Switch state using intent [duplicate]

I was in trouble with logical error somewhere in my program, what happening is when I use time picker and Switch in my MainActivity then the time selected and Switch state getting changed in my another activity i.e: UtilMainActivity which is a subclass. But whereas, when I change the switch state and time in my UtilMainActivity it is not resulting in a change of switch state and alarm time in my MainActivity.What I actually need is when I change alarm time and switch in MainActivity does not lead to change of time and switch in my UtilMainActivity.......Hope You understand my problem. Here is My MainActivity.
UtilMainActivity
public class UtilMainActivity extends AppCompatActivity implements
TimePickerDialog.OnTimeSetListener {
SwitchCompat onOffSwitch;
TextView firstAlarmTextView;
TextView timeLeftTextView;
LinearLayout firstAlarmLayout;
UtilSharedPreferencesHelper sharPrefHelper;
UtilTimerManager utilTimerManager;
UtilAlarmParams utilAlarmParams;
BroadcastReceiver timeLeftReceiver;
private final String LOG_TAG = UtilMainActivity.class.getSimpleName();
final int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 45;
final float DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION = 2f; // number of alarms, first alarm, interval values text size is larger than text around them
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.utility_activity_main);
onOffSwitch = (SwitchCompat) findViewById(R.id.switch_main);
firstAlarmLayout = (LinearLayout) findViewById(R.id.layout_main_firstalarm);
firstAlarmTextView = (TextView) findViewById(R.id.textview_main_firstalarm_time);
timeLeftTextView = (TextView) findViewById(R.id.textview_main_timeleft);
sharPrefHelper = new UtilSharedPreferencesHelper(UtilMainActivity.this);
sharPrefHelper.printAll();
utilAlarmParams = sharPrefHelper.utilgetParams();
utilTimerManager = new UtilTimerManager(UtilMainActivity.this);
showFirstAlarmTime(utilAlarmParams.firstUtilAlarmTime.toString());
showTimeLeft(utilAlarmParams);
onOffSwitch.setChecked(sharPrefHelper.isAlarmTurnedOn());
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
utilAlarmParams.turnedOn = isChecked;
if (isChecked) {
checkNotificationPolicy();
checkOverlayPermission();
utilTimerManager.startSingleAlarmTimer(utilAlarmParams.firstUtilAlarmTime.toMillis());
showToast(getString(R.string.utility_main_alarm_turned_on_toast));
} else {
utilTimerManager.cancelTimer();
showToast(getString(R.string.utility_main_alarm_turned_off_toast));
}
showTimeLeft(utilAlarmParams);
sharPrefHelper.utilsetAlarmState(isChecked);
}
});
firstAlarmLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle timePickerBundle = new Bundle();
timePickerBundle.putInt(UtilTimePickerDialogFragment.BUNDLE_KEY_ALARM_HOUR, sharPrefHelper.utilgetHour());
timePickerBundle.putInt(UtilTimePickerDialogFragment.BUNDLE_KEY_ALARM_MINUTE, sharPrefHelper.utilgetMinute());
UtilTimePickerDialogFragment timePicker = new UtilTimePickerDialogFragment();
timePicker.setArguments(timePickerBundle);
timePicker.show(getFragmentManager(), UtilTimePickerDialogFragment.FRAGMENT_TAG);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onResume() {
super.onResume();
showTimeLeft(utilAlarmParams);
timeLeftReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) { //i.e. every minute
showTimeLeft(utilAlarmParams);
}
}
};
registerReceiver(timeLeftReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
protected void onPause() {
super.onPause();
if (timeLeftReceiver != null) {
unregisterReceiver(timeLeftReceiver);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
UtilAlarmTime utilAlarmTime = new UtilAlarmTime(hour, minute);
utilAlarmParams.firstUtilAlarmTime = utilAlarmTime;
showFirstAlarmTime(utilAlarmTime.toString());
showTimeLeft(utilAlarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.utilsetTime(utilAlarmTime);
}
private void showToast(String message) {
Toast.makeText(UtilMainActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void resetTimerIfTurnedOn() {
if (onOffSwitch.isChecked()) {
utilTimerManager.resetSingleAlarmTimer(utilAlarmParams.firstUtilAlarmTime.toMillis());
showToast(getString(R.string.utility_main_alarm_reset_toast));
}
}
private void showFirstAlarmTime(String firstAlarmTime) {
String wholeTitle = getString(R.string.utility_main_firstalarm_time, firstAlarmTime);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(firstAlarmTime) - 1,
wholeTitle.indexOf(firstAlarmTime) + firstAlarmTime.length(), 0);
firstAlarmTextView.setText(wholeTitleSpan);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void showTimeLeft(UtilAlarmParams utilAlarmParams) {
UtilAlarmTime utilAlarmTime = utilAlarmParams.firstUtilAlarmTime;
timeLeftTextView.setText(getString(R.string.utility_all_time_left, utilAlarmTime.getHoursLeft(), utilAlarmTime.getMinutesLeft()));
if (utilAlarmParams.turnedOn) {
timeLeftTextView.setTextColor(getColor(R.color.primary));
} else {
timeLeftTextView.setTextColor(getColor(R.color.main_disabled_textcolor));
}
Log.d(LOG_TAG, "Time left: "+ utilAlarmTime.getHoursLeft() + ":" + utilAlarmTime.getMinutesLeft());
}
private void checkNotificationPolicy() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
/**
* needed for Android Q: on some devices activity doesn't show from fullScreenNotification without
* permission SYSTEM_ALERT_WINDOW
*/
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkOverlayPermission() {
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.P) && (!Settings.canDrawOverlays(this))) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements
IntervalDialogFragment.IntervalDialogListener,
NumberOfAlarmsDialogFragment.NumberOfAlarmsDialogListener,
TimePickerDialog.OnTimeSetListener {
SwitchCompat onOffSwitch;
ListView alarmsListView;
TextView intervalBetweenAlarmsTextView;
TextView numberOfAlarmsTextView;
TextView firstAlarmTextView;
TextView timeLeftTextView;
LinearLayout firstAlarmLayout;
LinearLayout intervalLayout;
LinearLayout numberOfAlarmsLayout;
AlarmsListHelper alarmsListHelper;
SharedPreferencesHelper sharPrefHelper;
TimerManager timerManager;
AlarmParams alarmParams;
BroadcastReceiver timeLeftReceiver;
Button sleepTimer;
private final String LOG_TAG = MainActivity.class.getSimpleName();
final int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 45;
final float DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION = 2f; // number of alarms, first alarm, interval values text size is larger than text around them
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmsListView = (ListView) findViewById(R.id.listview_main_alarmslist);
onOffSwitch = (SwitchCompat) findViewById(R.id.util_switch_main);
intervalBetweenAlarmsTextView = (TextView) findViewById(R.id.textview_main_interval);
numberOfAlarmsTextView = (TextView) findViewById(R.id.textview_main_numberofalarms);
firstAlarmLayout = (LinearLayout) findViewById(R.id.layout_main_firstalarm);
firstAlarmTextView = (TextView) findViewById(R.id.util_textview_main_firstalarm_time);
timeLeftTextView = (TextView) findViewById(R.id.textview_main_timeleft);
intervalLayout = (LinearLayout) findViewById(R.id.layout_main_interval);
numberOfAlarmsLayout = (LinearLayout) findViewById(R.id.layout_main_numberofalarms);
sleepTimer = (Button) findViewById(R.id.sleepTimer);
sharPrefHelper = new SharedPreferencesHelper(MainActivity.this);
sharPrefHelper.printAll();
alarmParams = sharPrefHelper.getParams();
timerManager = new TimerManager(MainActivity.this);
alarmsListHelper = new AlarmsListHelper(MainActivity.this, alarmsListView);
showFirstAlarmTime(alarmParams.firstAlarmTime.toString());
showTimeLeft(alarmParams);
showInterval(sharPrefHelper.getIntervalStr());
showNumberOfAlarms(sharPrefHelper.getNumberOfAlarmsStr());
onOffSwitch.setChecked(sharPrefHelper.isAlarmTurnedOn());
alarmsListHelper.showList(alarmParams);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
alarmParams.turnedOn = isChecked;
if (isChecked) {
checkNotificationPolicy();
checkOverlayPermission();
timerManager.startSingleAlarmTimer(alarmParams.firstAlarmTime.toMillis());
showToast(getString(R.string.main_alarm_turned_on_toast));
sharPrefHelper.setNumberOfAlreadyRangAlarms(0);
} else {
timerManager.cancelTimer();
showToast(getString(R.string.main_alarm_turned_off_toast));
}
alarmsListHelper.showList(alarmParams);
showTimeLeft(alarmParams);
sharPrefHelper.setAlarmState(isChecked);
}
});
intervalLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntervalDialogFragment dialog = new IntervalDialogFragment();
Bundle intervalBundle = new Bundle();
intervalBundle.putString(IntervalDialogFragment.BUNDLE_KEY_INTERVAL, sharPrefHelper.getIntervalStr());
dialog.setArguments(intervalBundle);
dialog.show(getFragmentManager(), IntervalDialogFragment.FRAGMENT_TAG);
}
});
numberOfAlarmsLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NumberOfAlarmsDialogFragment dialog = new NumberOfAlarmsDialogFragment();
Bundle numberOfAlarmsBundle = new Bundle();
numberOfAlarmsBundle.putString(NumberOfAlarmsDialogFragment.BUNDLE_KEY_NUMBER_OF_ALARMS, sharPrefHelper.getNumberOfAlarmsStr());
dialog.setArguments(numberOfAlarmsBundle);
dialog.show(getFragmentManager(), NumberOfAlarmsDialogFragment.FRAGMENT_TAG);
}
});
firstAlarmLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle timePickerBundle = new Bundle();
timePickerBundle.putInt(TimePickerDialogFragment.BUNDLE_KEY_ALARM_HOUR, sharPrefHelper.getHour());
timePickerBundle.putInt(TimePickerDialogFragment.BUNDLE_KEY_ALARM_MINUTE, sharPrefHelper.getMinute());
TimePickerDialogFragment timePicker = new TimePickerDialogFragment();
timePicker.setArguments(timePickerBundle);
timePicker.show(getFragmentManager(), TimePickerDialogFragment.FRAGMENT_TAG);
}
});
sleepTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNewActivity();
}
});
}
public void openNewActivity(){
Intent intent = new Intent(this, SleepTimerActivity.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
showTimeLeft(alarmParams);
timeLeftReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) { //i.e. every minute
showTimeLeft(alarmParams);
}
}
};
registerReceiver(timeLeftReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
protected void onPause() {
super.onPause();
if (timeLeftReceiver != null) {
unregisterReceiver(timeLeftReceiver);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
new Handler().post(new Runnable() {
#Override
public void run() {
final View view = findViewById(R.id.scheduleactivity);
if (view != null) {
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do something...
Toast.makeText(getApplicationContext(), "Scheduled Utilities Stopper", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings: {
Intent intent = new Intent(this, PrefActivity.class);
startActivity(intent);
break;
}
case R.id.scheduleactivity: {
Intent intent = new Intent(this, UtilMainActivity.class);
startActivity(intent);
break;
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onIntervalChanged(String intervalStr) {
showInterval(intervalStr);
alarmParams.interval = Integer.parseInt(intervalStr);
alarmsListHelper.showList(alarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.setInterval(intervalStr);
}
#Override
public void onNumberOfAlarmsChanged(String numberOfAlarmsStr) {
showNumberOfAlarms(numberOfAlarmsStr);
alarmParams.numberOfAlarms = Integer.parseInt(numberOfAlarmsStr);
alarmsListHelper.showList(alarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.setNumberOfAlarms(numberOfAlarmsStr);
}
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
AlarmTime alarmTime = new AlarmTime(hour, minute);
alarmParams.firstAlarmTime = alarmTime;
showFirstAlarmTime(alarmTime.toString());
alarmsListHelper.showList(alarmParams);
showTimeLeft(alarmParams);
sharPrefHelper.setNumberOfAlreadyRangAlarms(0);
resetTimerIfTurnedOn();
sharPrefHelper.setTime(alarmTime);
}
private void showToast(String message) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void resetTimerIfTurnedOn() {
if (onOffSwitch.isChecked()) {
timerManager.resetSingleAlarmTimer(alarmParams.firstAlarmTime.toMillis());
showToast(getString(R.string.main_alarm_reset_toast));
}
}
private void showInterval(String interval) {
String wholeTitle = getString(R.string.main_interval, interval);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION), wholeTitle.indexOf(interval), interval.length() + 1, 0);
intervalBetweenAlarmsTextView.setText(wholeTitleSpan);
}
private void showNumberOfAlarms(String numberOfAlarms) {
int numberOfAlarmsInt = Integer.parseInt(numberOfAlarms);
String wholeTitle = this.getResources().getQuantityString(R.plurals.main_number_of_alarms, numberOfAlarmsInt, numberOfAlarmsInt);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(numberOfAlarms),
numberOfAlarms.length() + 1, 0);
numberOfAlarmsTextView.setText(wholeTitleSpan);
}
private void showFirstAlarmTime(String firstAlarmTime) {
String wholeTitle = getString(R.string.main_firstalarm_time, firstAlarmTime);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(firstAlarmTime) - 1,
wholeTitle.indexOf(firstAlarmTime) + firstAlarmTime.length(), 0);
firstAlarmTextView.setText(wholeTitleSpan);
}
private void showTimeLeft(AlarmParams alarmParams) {
AlarmTime alarmTime = alarmParams.firstAlarmTime;
timeLeftTextView.setText(getString(R.string.all_time_left, alarmTime.getHoursLeft(), alarmTime.getMinutesLeft()));
if (alarmParams.turnedOn) {
timeLeftTextView.setTextColor(getColor(R.color.primary));
} else {
timeLeftTextView.setTextColor(getColor(R.color.main_disabled_textcolor));
}
Log.d(LOG_TAG, "Time left: "+alarmTime.getHoursLeft() + ":" + alarmTime.getMinutesLeft());
}
private void checkNotificationPolicy() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
/**
* needed for Android Q: on some devices activity doesn't show from fullScreenNotification without
* permission SYSTEM_ALERT_WINDOW
*/
private void checkOverlayPermission() {
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.P) && (!Settings.canDrawOverlays(this))) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}
}
Your activity, won't get the new data, because it's receiver was already unregistered, to make this easier for you, I would advise, you start the activity with startActivityForResult that way when you are done, you can set the data and the previous activity will receive the data in a bundle on this callback onActivityResult(...)

Clear all list item on button click

I have created simple chatting application and it contains some ListView which handles all chat messages, but every ListView is defined in another class. I want to clear my list items from Clear Chat from an overflow menu, which is present in main activity. How can I achieve this?
Here is my main activity called WiFiServiceDiscoveryActivity:
public class WiFiServiceDiscoveryActivity extends AppCompatActivity implements
DeviceClickListener, Handler.Callback, MessageTarget,
ConnectionInfoListener {
public static final String TAG = "wifidirectdemo";
// TXT RECORD properties
public static final String TXTRECORD_PROP_AVAILABLE = "available";
public static final String SERVICE_INSTANCE = " ";
public static final String SERVICE_REG_TYPE = "_presence._tcp";
public static final int MESSAGE_READ = 0x400 + 1;
public static final int MY_HANDLE = 0x400 + 2;
private WifiP2pManager manager;
static final int SERVER_PORT = 4545;
private final IntentFilter intentFilter = new IntentFilter();
private Channel channel;
private BroadcastReceiver receiver = null;
private WifiP2pDnsSdServiceRequest serviceRequest;
private Handler handler = new Handler(this);
private WiFiChatFragment chatFragment;
private WiFiDirectServicesList servicesList;
private TextView statusTxtView;
Toolbar toolbar;
private String friend;
private WiFiP2pService service;
WiFiChatFragment listView;
WiFiChatFragment.ChatMessageAdapter a;
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toolbar=(Toolbar)findViewById(R.id.toolbar);
statusTxtView = (TextView) findViewById(R.id.status_text);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
startRegistrationAndDiscovery();
servicesList = new WiFiDirectServicesList();
getFragmentManager().beginTransaction()
.add(R.id.container_root, servicesList, "services").commit();
setSupportActionBar(toolbar);
}
#Override
protected void onRestart() {
Fragment frag = getFragmentManager().findFragmentByTag("services");
if (frag != null) {
getFragmentManager().beginTransaction().remove(frag).commit();
}
super.onRestart();
}
#Override
protected void onStop() {
if (manager != null && channel != null) {
manager.removeGroup(channel, new ActionListener() {
#Override
public void onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
#Override
public void onSuccess() {
}
});
}
super.onStop();
}
/**
* Registers a local service and then initiates a service discovery
*/
private void startRegistrationAndDiscovery() {
Map<String, String> record = new HashMap<String, String>();
record.put(TXTRECORD_PROP_AVAILABLE, "visible");
WifiP2pDnsSdServiceInfo service = WifiP2pDnsSdServiceInfo.newInstance(
SERVICE_INSTANCE, SERVICE_REG_TYPE, record);
manager.addLocalService(channel, service, new ActionListener() {
#Override
public void onSuccess() {
//appendStatus("Added Local Service");
}
#Override
public void onFailure(int error) {
// appendStatus("Failed to add a service");
}
});
discoverService();
}
private void discoverService() {
/*
* Register listeners for DNS-SD services. These are callbacks invoked
* by the system when a service is actually discovered.
*/
manager.setDnsSdResponseListeners(channel,
new DnsSdServiceResponseListener() {
#Override
public void onDnsSdServiceAvailable(String instanceName,
String registrationType, WifiP2pDevice srcDevice) {
// A service has been discovered. Is this our app?
if (instanceName.equalsIgnoreCase(SERVICE_INSTANCE)) {
// update the UI and add the item the discovered
// device.
WiFiDirectServicesList fragment = (WiFiDirectServicesList) getFragmentManager()
.findFragmentByTag("services");
if (fragment != null) {
WiFiDevicesAdapter adapter = ((WiFiDevicesAdapter) fragment
.getListAdapter());
service = new WiFiP2pService();
service.device = srcDevice;
service.instanceName = instanceName;
service.serviceRegistrationType = registrationType;
adapter.add(service);
adapter.notifyDataSetChanged();
Log.d(TAG, "onBonjourServiceAvailable "
+ instanceName);
}
}
}
}, new DnsSdTxtRecordListener() {
/**
* A new TXT record is available. Pick up the advertised
* buddy name.
*/
#Override
public void onDnsSdTxtRecordAvailable(
String fullDomainName, Map<String, String> record,
WifiP2pDevice device) {
Log.d(TAG,
device.deviceName + " is "
+ record.get(TXTRECORD_PROP_AVAILABLE));
}
});
// After attaching listeners, create a service request and initiate
// discovery.
serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
manager.addServiceRequest(channel, serviceRequest,
new ActionListener() {
#Override
public void onSuccess() {
// appendStatus("Added service discovery request");
}
#Override
public void onFailure(int arg0) {
appendStatus("Failed adding service discovery request");
}
});
manager.discoverServices(channel, new ActionListener() {
#Override
public void onSuccess() {
//appendStatus("Service discovery initiated");
}
#Override
public void onFailure(int arg0) {
appendStatus("Service discovery failed");
}
});
}
#Override
public void connectP2p(WiFiP2pService service) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = service.device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
if (serviceRequest != null)
manager.removeServiceRequest(channel, serviceRequest,
new ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int arg0) {
}
});
manager.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Connecting to service");
}
#Override
public void onFailure(int errorCode) {
appendStatus("Failed connecting to service");
}
});
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
(chatFragment).pushMessage("Friend :" + readMessage);
break;
case MY_HANDLE:
Object obj = msg.obj;
(chatFragment).setChatManager((ChatManager) obj);
}
return true;
}
#Override
public void onResume() {
super.onResume();
receiver = new HomeActivity(manager, channel, this);
registerReceiver(receiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo p2pInfo) {
Thread handler = null;
if (p2pInfo.isGroupOwner) {
Log.d(TAG, "Connected as group owner");
try {
handler = new GroupOwnerSocketHandler(
((MessageTarget) this).getHandler());
handler.start();
} catch (IOException e) {
Log.d(TAG,
"Failed to create a server thread - " + e.getMessage());
return;
}
} else {
Log.d(TAG, "Connected as peer");
handler = new ClientSocketHandler(
((MessageTarget) this).getHandler(),
p2pInfo.groupOwnerAddress);
handler.start();
}
chatFragment = new WiFiChatFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container_root, chatFragment).commit();
statusTxtView.setVisibility(View.GONE);
}
public void appendStatus(String status) {
String current = statusTxtView.getText().toString();
statusTxtView.setText(current + "\n" + status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
.show();
break;
case R.id.clean:
Toast.makeText(this, "Clear Chat", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
}
And another class which has the ListView called WiFiChatFragment:
public class WiFiChatFragment extends Fragment {
private View view;
private ChatManager chatManager;
private TextView chatLine;
private ListView listView;
ChatMessageAdapter adapter = null;
private List<String> items = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_chat, container, false);
chatLine = (TextView) view.findViewById(R.id.txtChatLine);
listView = (ListView) view.findViewById(android.R.id.list);
adapter = new ChatMessageAdapter(getActivity(), android.R.id.text1,
items);
listView.setAdapter(adapter);
view.findViewById(R.id.button1).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (chatManager != null) {
chatManager.write(chatLine.getText().toString()
.getBytes());
pushMessage("Me: " + chatLine.getText().toString());
chatLine.setText("");
chatLine.clearFocus();
}
}
});
return view;
}
public interface MessageTarget {
public Handler getHandler();
}
public void setChatManager(ChatManager obj) {
chatManager = obj;
}
public void pushMessage(String readMessage) {
adapter.add(readMessage);
adapter.notifyDataSetChanged();
}
/**
* ArrayAdapter to manage chat messages.
*/
public class ChatMessageAdapter extends ArrayAdapter<String> {
List<String> messages = null;
public ChatMessageAdapter(Context context, int textViewResourceId,
List<String> items) {
super(context, textViewResourceId, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(android.R.layout.simple_list_item_1, null);
}
String message = items.get(position);
if (message != null && !message.isEmpty()) {
TextView nameText = (TextView) v
.findViewById(android.R.id.text1);
if (nameText != null) {
nameText.setText(message);
if (message.startsWith("Me: ")) {
nameText.setBackgroundResource(R.drawable.bubble_b );
nameText.setTextAppearance(getActivity(),
R.style.normalText);
} else {
nameText.setBackgroundResource(R.drawable.bubble_a );
nameText.setTextAppearance(getActivity(),
R.style.boldText);
}
}
}
return v;
}
}
}
Hey Adesh you could do this when the overflow item is clicked:
Call setListAdapter() again. This time with an empty ArrayList.
Hope it helps !

Quickblox Android how to get the first message from incoming chat?

I'm using quickblox android sdk for my chat application. I know that when opponent user starts the conversation QBPrivateChatManagerListener -> chatCreated() event get fired. Below is my code. When chatCreated is fired I load the chat Fragment. In the chat fragment I have implemented the QBMessageListenerImpl interface. Problem here is that I don't get the first message from processMessage(). But I get the second message. So my question is how can I read the very first message that opponent user is sending ?
#Override
public void chatCreated(final QBPrivateChat qbPrivateChat, boolean b) {
ShowMessage("Incoming chat!!");
if(!b)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
CreateNewChatForIncoming(qbPrivateChat);
}
});
}
}
public void CreateNewChatForIncoming(QBPrivateChat qbPrivateChat) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
PrivateChatFragment privateChatFragment = new PrivateChatFragment();
privateChatFragment.setOpponentuser(null);
privateChatFragment.setIncomingChat(qbPrivateChat);
HashMap<Integer, QBUser> allusers = applicationSingleton.getAllusers();
String title = allusers.get(qbPrivateChat.getParticipant()).getFullName();
if (title != null)
this.setTitle(title);
ft.replace(R.id.content_frame, privateChatFragment);
ft.commit();
}
/*---------------Private chat Fragment-------------------------*/
public class PrivateChatFragment extends SherlockFragment {
TextView txtmsg;
MessageAdaptor messageAdaptor;
ListView listView;
boolean ismode = true;
PrivateChat privateChat;
private QBUser opponentuser;
private QBPrivateChat incomingChat;
int opponentuserid;
ApplicationSingleton applicationSingleton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chattabfragment, container, false);
txtmsg = (TextView) view.findViewById(R.id.txtmsg);
SetFont(txtmsg);
applicationSingleton = (ApplicationSingleton)getSherlockActivity().getApplication();
messageAdaptor = new MessageAdaptor(this.getActivity().getApplicationContext(), R.layout.msg_list_item_inbound);
if (opponentuser != null) {
opponentuserid = opponentuser.getId();
HashMap<Integer, PrivateChat> allpvtchats = applicationSingleton.getAllpvtchats();
if(allpvtchats.containsKey(opponentuserid)) {
privateChat = applicationSingleton.getAllpvtchats().get(opponentuserid);
}
else {
privateChat = new PrivateChat(this, opponentuserid);
applicationSingleton.getAllpvtchats().put(opponentuserid,privateChat);
}
List<ChatMessage> allmsgs = GetMessageHistory(opponentuser);
if (allmsgs != null) {
ShowMessage("setting history");
messageAdaptor.LoadNewItems(allmsgs);
messageAdaptor.notifyDataSetChanged();
messageAdaptor.notifyDataSetInvalidated();
}
} else if (incomingChat != null) {
opponentuserid = incomingChat.getParticipant();
privateChat = new PrivateChat(this, incomingChat);
}
listView = (ListView) view.findViewById(R.id.listview_msg);
listView.setAdapter(messageAdaptor);
txtmsg.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
ChatMessage msg = new ChatMessage();
msg.setOutbound(true);
msg.setImg(R.drawable.boy1);
msg.setTime("10:30am");
msg.setMessage(txtmsg.getText().toString());
messageAdaptor.add(msg);
txtmsg.setText("");
scrolToBottom();
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(msg.getMessage());
//chatMessage.setProperty("name", opponentuser.getFullName());
chatMessage.setSaveToHistory(true);
chatMessage.setMarkable(true);
try {
privateChat.sendMessage(chatMessage);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
return true;
}
return false;
}
});
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
ApplicationSingleton applicationSingleton = (ApplicationSingleton) this.getActivity().getApplication();
HashMap<Integer, List<ChatMessage>> allchats = applicationSingleton.getAllchats();
allchats.put(opponentuserid, messageAdaptor.GetAllMessages());
applicationSingleton.setAllchats(allchats);
}
private List<ChatMessage> GetMessageHistory(QBUser opnnentuser) {
ApplicationSingleton applicationSingleton = (ApplicationSingleton) this.getActivity().getApplication();
HashMap<Integer, List<ChatMessage>> allchats = applicationSingleton.getAllchats();
if (allchats.containsKey(opnnentuser.getId())) {
return allchats.get(opnnentuser.getId());
} else {
return null;
}
}
void SetFont(TextView view) {
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/LatoRegular.ttf");
view.setTypeface(font);
}
public void scrolToBottom() {
listView.post(new Runnable() {
#Override
public void run() {
listView.setSelection(messageAdaptor.getCount() - 1);
}
});
}
public void UpdateAdaptor(final ChatMessage chatMessage) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (messageAdaptor != null) {
messageAdaptor.add(chatMessage);
messageAdaptor.notifyDataSetChanged();
scrolToBottom();
}
}
});
}
public void setOpponentuser(QBUser opponentuser) {
this.opponentuser = opponentuser;
}
public void setIncomingChat(QBPrivateChat incomingChat) {
this.incomingChat = incomingChat;
}
public void SendNotification(String title, String message) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getSherlockActivity())
.setSmallIcon(R.drawable.boy6_small)
.setContentTitle(title)
.setContentText(message);
int mId = GetNotificationid();
Intent resultIntent = new Intent(getSherlockActivity(), SideMenuActivity.class);
resultIntent.putExtra(GlobalData.OP_ID, opponentuser.getId());
resultIntent.putExtra(GlobalData.NOTIFY_MODE, true);
resultIntent.putExtra(GlobalData.NOTIFY_ID, mId);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getSherlockActivity());
stackBuilder.addParentStack(SideMenuActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSherlockActivity().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
}
private void ShowMessage(final String msg) {
Runnable mrunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
};
getActivity().runOnUiThread(mrunnable);
}
private int GetNotificationid()
{
Calendar c = Calendar.getInstance();
int milsec = c.get(Calendar.MILLISECOND);
return milsec;
}
}
/* --------------------Privatechat class------------------- */
public class PrivateChat extends QBMessageListenerImpl<QBPrivateChat>{
private QBPrivateChatManager privateChatManager;
private QBPrivateChat privateChat;
private PrivateChatFragment currentContext;
private ApplicationSingleton applicationSingleton;
public PrivateChat(PrivateChatFragment context,Integer opponentID) {
currentContext = context;
applicationSingleton = (ApplicationSingleton)currentContext.getSherlockActivity().getApplication();
privateChatManager = applicationSingleton.getChatService().getPrivateChatManager();
// init private chat
//
privateChat = privateChatManager.getChat(opponentID);
if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentID, this);
}else{
privateChat.addMessageListener(this);
}
}
public PrivateChat(PrivateChatFragment context,QBPrivateChat incomingChat) {
privateChat = incomingChat;
privateChat.addMessageListener(this);
currentContext = context;
}
public void sendMessage(QBChatMessage message) throws XMPPException, SmackException.NotConnectedException {
privateChat.sendMessage(message);
}
public void release() {
privateChat.removeMessageListener(this);
}
#Override
public void processMessage(QBPrivateChat chat, QBChatMessage message) {
Log.e("Anuradha-message",message.getBody());
ChatMessage msg = new ChatMessage();
msg.setOutbound(false);
msg.setImg(R.drawable.boy2);
msg.setTime("10:30am");
msg.setMessage(message.getBody());
currentContext.UpdateAdaptor(msg);
if(applicationSingleton.isAppBackground()) {
HashMap<Integer,QBUser> allusers = applicationSingleton.getAllusers();
QBUser user = allusers.get(message.getSenderId());
currentContext.SendNotification(user.getFullName().toString(),"says "+message.getBody());
}
}
#Override
public void processError(QBPrivateChat chat, QBChatException error, QBChatMessage originChatMessage){
}
#Override
public void processMessageDelivered(QBPrivateChat privateChat, String messageID){
}
#Override
public void processMessageRead(QBPrivateChat privateChat, String messageID){
ShowMessage("msg read : "+messageID);
}
private void ShowMessage(final String msg) {
Runnable mrunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(currentContext.getActivity(), msg, Toast.LENGTH_LONG).show();
}
};
currentContext.getActivity().runOnUiThread(mrunnable);
}
}
Try to change
privateChat = privateChatManager.getChat(opponentID);`enter code here` if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentID, this);
}else{
privateChat.addMessageListener(this);
}

to
if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentID, this);
}
privateChat.addMessageListener(this);

If Progressdialog is not showing (android)

I have a ProgressDialog, and I want to do something when the dialog dissappears (but I do not want put my action after the progressdialog.dismiss).
Is it possible to:
----> if No ---> Do something
Check if dialog is showing
----> if Yes
/|\ |
| \|/
--------------------- Wait
Don't think to difficult, I just want to perform an action, but only if there is no dialog, and if there is one, to perform the action when the dialog is done.
Thank you!
EDIT: My activity:
import verymuchimportshere..
public class ScroidWallpaperGallery extends Activity {
private WallpaperGalleryAdapter wallpaperGalleryAdapter;
private final WallpaperManager wallpaperManager;
private final ICommunicationDAO communicationDAO;
private final IFavouriteDAO favouriteDAO;
private final List<Integer> preloadedList;
private Wallpaper selectedWallpaper;
private static final int PICK_CONTACT = 0;
private static final int DIALOG_ABOUT = 0;
public ScroidWallpaperGallery() {
super();
if (!DependencyInjector.isInitialized()) {
DependencyInjector.init(this);
}
this.wallpaperManager = DependencyInjector.getInstance(WallpaperManager.class);
this.communicationDAO = DependencyInjector.getInstance(ICommunicationDAO.class);
this.favouriteDAO = DependencyInjector.getInstance(IFavouriteDAO.class);
this.preloadedList = new ArrayList<Integer>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.initGallery();
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(this.getString(R.string.loadingText));
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
else {
SharedPreferences settings = getSharedPreferences("firstrun", MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
new AlertDialog.Builder(this).setTitle("How to").setMessage("Long press item to add/remove from favorites.").setNeutralButton("Ok", null).show();
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
if (this.wallpaperGalleryAdapter != null) {
this.updateGalleryAdapter();
return;
}
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
new FillGalleryTask(progressDialog, this).start();
}
private void updateGalleryAdapter() {
this.updateGalleryAdapter(this.wallpaperManager.getWallpapers());
}
private synchronized void updateGalleryAdapter(Wallpaper[] wallpapers) {
this.wallpaperGalleryAdapter = new WallpaperGalleryAdapter(this, wallpapers, this.wallpaperManager);
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setAdapter(this.wallpaperGalleryAdapter);
}
private void initGallery() {
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Wallpaper wallpaper = (Wallpaper)parent.getItemAtPosition(position);
showPreviewActivity(wallpaper);
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
selectedWallpaper = (Wallpaper)wallpaperGalleryAdapter.getItem(position);
new Thread(new Runnable() {
#Override
public void run() {
preloadThumbs(wallpaperGalleryAdapter.getWallpapers(), (position + 1), 3);
}
}).start();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedWallpaper = null;
}
});
this.registerForContextMenu(gallery);
}
private void showPreviewActivity(Wallpaper wallpaper) {
WallpaperPreviewActivity.showPreviewActivity(this, wallpaper);
}
private void preloadThumbs(Wallpaper[] wallpapers, int index, int maxCount) {
for (int i = index; (i < (index + maxCount)) && (i < wallpapers.length); i++) {
if (this.preloadedList.contains(i)) {
continue;
}
try {
this.wallpaperManager.getThumbImage(wallpapers[i]);
this.preloadedList.add(i);
}
catch (ClientProtocolException ex) {
// nothing to do - image will be loaded on select
}
catch (IOException ex) {
// nothing to do - image will be loaded on select
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (this.selectedWallpaper == null
|| !(v instanceof Gallery)) {
return;
}
MenuInflater menuInflater = new MenuInflater(this);
menuInflater.inflate(R.menu.gallery_context_menu, menu);
if (this.favouriteDAO.isFavourite(this.selectedWallpaper.getId())) {
menu.findItem(R.id.galleryRemoveFavouriteMenuItem).setVisible(true);
}
else {
menu.findItem(R.id.galleryAddFavouriteMenuItem).setVisible(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (this.selectedWallpaper == null) {
return false;
}
switch (item.getItemId()) {
case R.id.galleryAddFavouriteMenuItem:
this.favouriteDAO.add(this.selectedWallpaper.getId());
return true;
case R.id.galleryRemoveFavouriteMenuItem:
this.favouriteDAO.remove(this.selectedWallpaper.getId());
return true;
}
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aboutMenuItem:
this.showDialog(DIALOG_ABOUT);
return true;
case R.id.settingsMenuItem:
this.startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.recommendMenuItem:
this.recommendWallpaper();
return true;
case R.id.favouritesMenuItem:
FavouriteListActivity.showFavouriteListActivity(this);
return true;
case R.id.closeMenuItem:
this.finish();
return true;
}
return false;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ABOUT:
return new AboutDialog(this);
default:
return null;
}
}
private void recommendWallpaper() {
if (this.selectedWallpaper == null) {
return;
}
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
this.startActivityForResult(intent, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_CONTACT:
this.onPickContactActivityResult(resultCode, data);
break;
}
}
private void onPickContactActivityResult(int resultCode, Intent data) {
if (resultCode == 0) {
return;
}
Communication[] communications = this.communicationDAO.getCommunications(data.getData());
if (communications.length < 1) {
AlertDialogFactory.showInfoMessage(this, R.string.infoText, R.string.noCommunicationFoundInfoText);
return;
}
CommunicationChooseDialog dialog = new CommunicationChooseDialog(this, communications, new CommunicationChosenListener() {
#Override
public void onCommunicationChosen(Communication communication) {
handleOnCommunicationChosen(communication);
}
});
dialog.show();
}
private void handleOnCommunicationChosen(Communication communication) {
Wallpaper wallpaper = this.selectedWallpaper;
if (communication.getType().equals(Communication.Type.Email)) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { communication.getValue() });
intent.putExtra(Intent.EXTRA_SUBJECT, getBaseContext().getString(R.string.applicationName));
intent.putExtra(Intent.EXTRA_TEXT, String.format(getBaseContext().getString(R.string.recommendEmailPattern),
wallpaper.getWallpaperUrl()));
intent.setType("message/rfc822");
this.startActivity(intent);
}
else if (communication.getType().equals(Communication.Type.Mobile)) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", communication.getValue());
intent.putExtra("sms_body", String.format(getBaseContext().getString(R.string.recommendSmsPattern),
wallpaper.getWallpaperUrl()));
intent.setType("vnd.android-dir/mms-sms");
this.startActivity(intent);
}
}
private class FillGalleryTask extends LongTimeRunningOperation<Wallpaper[]> {
private final Context context;
public FillGalleryTask(Dialog progressDialog, Context context) {
super(progressDialog);
this.context = context;
}
#Override
public void afterOperationSuccessfullyCompleted(Wallpaper[] result) {
updateGalleryAdapter(result);
}
#Override
public void handleUncaughtException(Throwable ex) {
if (ex instanceof WallpaperListReceivingException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
ex.getMessage(),
new ShutDownAlertDialogOnClickListener());
}
else if (ex instanceof IOException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
R.string.downloadException,
new ShutDownAlertDialogOnClickListener());
}
else {
throw new RuntimeException(ex);
}
}
#Override
public Wallpaper[] onRun() throws Exception {
// retrieving available wallpapers from server
wallpaperManager.loadAvailableWallpapers(getBaseContext());
Wallpaper[] wallpapers = wallpaperManager.getWallpapers();
// preloading first 3 thumbs
preloadThumbs(wallpapers, 0, 3);
return wallpapers;
}
}
private class ShutDownAlertDialogOnClickListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}
}
Try this,
private void doSomethingWhenProgressNotShown() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doSomethingWhenProgressNotShown();
}
}, 500);
}
//isnt running- do something here
}
I think you can use this code:
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
}
//isnt running
Or you can set listeners:
mProgressDialog.setOnCancelListener(listener);
mProgressDialog.setOnDismissListener(listener);

Android: Execute http requests via Service

I have a trouble with getting Activity(Nullpointerexception) after that I have rotate screen and received callback from AsyncTask to update my views of the fragment. If I wont change orientation then everything is OK(but not all the time, sometimes this bug appears)
My main activity:
public class MainActivity extends SherlockFragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pager_layout);
fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(this);
session = new SessionManager(getApplicationContext());
if (session.isAuthorizated()) {
disableTabs();
FragmentTransaction ft = fm.beginTransaction();
if (session.termsAndConditions()) {
ft.replace(android.R.id.content, new TermsAndConditionsFragment(), "terms-and-conditions").commit();
}
}
} else {
enableTabs();
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(actionBar.newTab().setText("Log in"), LoginFragment.class, null);
mTabsAdapter.addTab(actionBar.newTab().setText("Calculator"), CalculatorFragment.class, null);
}
}
That`s my fragment:
public class TermsAndConditionsFragment extends SherlockFragment implements OnClickListener, OnTouchListener, OnEditorActionListener, ValueSelectedListener, AsyncUpdateViewsListener {
private static final String TAG = "TermsAndConditionsFragment";
private TermsAndConditionsManager termsAndConditionsM;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prepareData();
}
public void prepareData() {
if (getSherlockActivity() == null)
Log.d(TAG, "Activity is null");
termsAndConditionsM = new TermsAndConditionsManager(getSherlockActivity().getApplicationContext());
termsAndConditions = termsAndConditionsM.getTermsAndConditions();
...
// some stuff
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = init(inflater, container);
return rootView;
}
private View init(LayoutInflater inflater, ViewGroup container) {
rootView = inflater.inflate(R.layout.fragment_terms_and_conditions, container, false);
//bla bla bla
return rootView;
}
public void updateTermsAndConditionsView() {
//update views here
}
#Override
public void onClick(View v) {
ft = fm.beginTransaction();
switch (v.getId()) {
case R.id.etHowMuch:
d = NumberPaymentsPickerFragment.newInstance(getSherlockActivity(), Integer.valueOf(howMuch.replace("£", "")), 0);
d.setValueSelectedListener(this);
d.show(getFragmentManager(), Const.HOW_MUCH);
break;
}
}
#Override
public void onValueSelected() {
Bundle args = new Bundle();
...
ExecuteServerTaskBackground task = new ExecuteServerTaskBackground(getSherlockActivity());
task.setAsyncUpdateViewsListener(this);
task.action = ServerAPI.GET_TERMS_AND_CONDITIONS;
task.args = args;
task.execute();
}
#Override
public void onUpdateViews() {
prepareData();
updateTermsAndConditionsView();
}
}
My AsyncTask with callback:
public class ExecuteServerTaskBackground extends AsyncTask<Void, Void, Void> {
private static final String TAG = "ExecuteServerTaskBackground";
Activity mActivity;
Context mContext;
private AsyncUpdateViewsListener callback;
public ExecuteServerTaskBackground(Activity activity) {
this.mActivity = activity;
this.mContext = activity.getApplicationContext();
}
public void setAsyncUpdateViewsListener(AsyncUpdateViewsListener listener) {
callback = listener;
}
#Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(mContext);
if (!args.isEmpty())
msg = server.serverRequest(action, args);
else
msg = server.serverRequest(action, null);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
callback.onUpdateViews();
}
}
Why does it behave so? How can I get activity correctly if I change orientation.
EDIT:
As I understand correctly nullpointer appears after orientation changed and asynctask executed due to wrong reference between asyctask and Activity. Recreated activity doesnt have this reference thats why when I receive callback I use wrong activity reference which isn`t exist anymore. But how can I save current activity reference?
EDIT:
I have decided to try realize my task throughout Service and that`s what I have done.
Activity:
public class MainFragment extends Fragment implements ServiceExecutorListener, OnClickListener {
private static final String TAG = MainFragment.class.getName();
Button btnSend, btnCheck;
TextView serviceStatus;
Intent intent;
Boolean bound = false;
ServiceConnection sConn;
RESTService service;
ProgressDialog pd = new ProgressDialog();
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
intent = new Intent(getActivity(), RESTService.class);
getActivity().startService(intent);
sConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(TAG, "MainFragment onServiceConnected");
service = ((RESTService.MyBinder) binder).getService();
service.registerListener(MainFragment.this);
if (service.taskIsDone())
serviceStatus.setText(service.getResult());
bound = true;
}
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "MainFragment onServiceDisconnected");
bound = false;
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
serviceStatus = (TextView) rootView.findViewById(R.id.tvServiceStatusValue);
btnSend = (Button) rootView.findViewById(R.id.btnSend);
btnCheck = (Button) rootView.findViewById(R.id.btnCheck);
btnSend.setOnClickListener(this);
btnCheck.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSend:
pd.show(getFragmentManager(), "ProgressDialog");
service.run(7);
service.run(2);
service.run(4);
break;
case R.id.btnCheck:
if (service != null)
serviceStatus.setText(String.valueOf(service.taskIsDone()) + service.getTasksCount());
break;
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "Bind service");
getActivity().bindService(intent, sConn, 0);
}
#Override
public void onPause() {
super.onDestroy();
Log.d(TAG, "onDestroy: Unbind service");
if (!bound)
return;
getActivity().unbindService(sConn);
service.unregisterListener(this);
bound = false;
}
#Override
public void onComplete(String result) {
Log.d(TAG, "Task Completed");
pd.dismiss();
serviceStatus.setText(result);
}
}
Dialog:
public class ProgressDialog extends DialogFragment implements OnClickListener {
final String TAG = ProgressDialog.class.getName();
public Dialog onCreateDialog(Bundle savedInstanceState) {
setRetainInstance(true);
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity())
.setTitle("Title!")
.setPositiveButton(R.string.yes, this)
.setNegativeButton(R.string.no, this)
.setNeutralButton(R.string.maybe, this)
.setCancelable(false)
.setMessage(R.string.message_text)
.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return true;
}
});
return adb.create();
}
public void onClick(DialogInterface dialog, int which) {
int i = 0;
switch (which) {
case Dialog.BUTTON_POSITIVE:
i = R.string.yes;
break;
case Dialog.BUTTON_NEGATIVE:
i = R.string.no;
break;
case Dialog.BUTTON_NEUTRAL:
i = R.string.maybe;
break;
}
if (i > 0)
Log.d(TAG, "Dialog 2: " + getResources().getString(i));
}
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "Dialog 2: onDismiss");
// Fix to avoid simple dialog dismiss in orientation change
if ((getDialog() != null) && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
Log.d(TAG, "Dialog 2: onCancel");
}
}
Service:
public class RESTService extends Service {
final String TAG = RESTService.class.getName();
MyBinder binder = new MyBinder();
ArrayList<ServiceExecutorListener> listeners = new ArrayList<ServiceExecutorListener>();
Handler h = new Handler();
RequestManager mRequest;
ExecutorService es;
Object obj;
int time;
StringBuilder builder;
String result = null;
public void onCreate() {
super.onCreate();
Log.d(TAG, "RESTService onCreate");
es = Executors.newFixedThreadPool(1);
obj = new Object();
builder = new StringBuilder();
}
public void run(int time) {
RunRequest rr = new RunRequest(time);
es.execute(rr);
}
class RunRequest implements Runnable {
int time;
public RunRequest(int time) {
this.time = time;
Log.d(TAG, "RunRequest create");
}
public void run() {
Log.d(TAG, "RunRequest start, time = " + time);
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Log.d(TAG, "RunRequest obj = " + obj.getClass());
} catch (NullPointerException e) {
Log.d(TAG, "RunRequest error, null pointer");
}
builder.append("result " + time + ", ");
result = builder.toString();
sendCallback();
}
}
private void sendCallback() {
h.post(new Runnable() {
#Override
public void run() {
for (ServiceExecutorListener listener : listeners)
listener.onComplete();
}
});
}
public boolean taskIsDone() {
if (result != null)
return true;
return false;
}
public String getResult() {
return result;
}
public void registerListener(ServiceExecutorListener listener) {
listeners.add(listener);
}
public void unregisterListener(ServiceExecutorListener listener) {
listeners.remove(listener);
}
public IBinder onBind(Intent intent) {
Log.d(TAG, "RESTService onBind");
return binder;
}
public boolean onUnbind(Intent intent) {
Log.d(TAG, "RESTService onUnbind");
return true;
}
public class MyBinder extends Binder {
public RESTService getService() {
return RESTService.this;
}
}
}
As you mention in your edit, the current Activity is destroyed and recreated on orientation change.
But how can I save current activity reference?
You shouldn't. The previous Activity is no longer valid. This will not only cause NPEs but also memory leaks because the AsyncTask might hold the reference to old Activity, maybe forever.
Solution is to use Loaders.

Categories

Resources