Recyclerview OnScroll down, layout getting hide which opened on button click - android

I am using recyclerview, in my list item I have button. On that button click I am hiding and showing imageview, now if user click on list item and open imageview and then scrolldown and scrollup, the item in which user opened imageview is getting closed. This is my adapter code:
public class NotiDetailsListAdapter extends RecyclerView.Adapter<NotiDetailsListAdapter.ViewHolder> {
Context context;
private List<NotificationListData> adaBankDetailsList;
String bnkName = "", bnkAccNum = "", userName = "", bankIfscCode = "", bankType = "";
private int selectedPosition = -1;
boolean flag = true;
private NotiDetailsListAdapter(Context conytext, List<NotificationListData> bankDetails) {
this.context = conytext;
this.adaBankDetailsList = bankDetails;
}
#NonNull
#Override
public NotiDetailsListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
view = inflator.inflate(R.layout.notification_list_item_layout, parent, false);
return new NotiDetailsListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final NotiDetailsListAdapter.ViewHolder holder, int pos) {
bnkResponse = adaBankDetailsList.get(pos);
try {
holder.notification_main_text.setText(bnkResponse.getNotificationTitle());
holder.notification_sub_text.setText(bnkResponse.getNotificationMessage());
String mydates=bnkResponse.getNotificationSendTime();
String[] str_array1 = mydates.split("-");
if(str_array1[0] != null && str_array1[0].length() > 0 && str_array1[1] != null && str_array1[1].length() > 0) {
stringa1 = str_array1[0];
stringb1 = str_array1[1];
}
else
{
stringa1 = str_array1[0];
stringb1 = "";
}
String[] timearray = stringb1.split(":");
if(timearray[0] != null && timearray[0].length() > 0 && timearray[1] != null && timearray[1].length() > 0) {
stringt1 = timearray[0];
stringt2 = timearray[1];
}
else
{
stringt1 = timearray[0];
stringt2 = "";
}
if(mydates.contains("PM"))
{
stringampm="PM";
}
else if(mydates.contains("AM"))
{
stringampm="AM";
}
System.out.println("Dates "+stringampm+" "+stringt2);
holder.notification_date.setText(stringa1);
holder.notification_time.setText(stringt1+":"+stringt2+" "+stringampm);
holder.notification_iv.setVisibility(View.GONE);
holder.notification_main_text.setSingleLine(false);
holder.notification_main_text.setEllipsize(TextUtils.TruncateAt.END);
int n1 = 1; // the exact number of lines you want to display
holder.notification_main_text.setLines(n1);
holder.notification_main_text.setMaxEms(12);
holder.notification_sub_text.setSingleLine(false);
holder.notification_sub_text.setEllipsize(TextUtils.TruncateAt.END);
int n = 1; // the exact number of lines you want to display
holder.notification_sub_text.setLines(n);
holder.iv_arrow.setImageResource(R.mipmap.down);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return adaBankDetailsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView notification_main_text, notification_sub_text, notification_date, notification_time;
ImageView iv_arrow,notification_iv;
RelativeLayout parentRL,notification_rl;
LinearLayout arrow_click;
public ViewHolder(View itemView) {
super(itemView);
notification_main_text = itemView.findViewById(R.id.notification_main_text);
notification_sub_text = itemView.findViewById(R.id.notification_sub_text);
notification_date = itemView.findViewById(R.id.notification_date);
notification_time = itemView.findViewById(R.id.notification_time);
iv_arrow = itemView.findViewById(R.id.iv_arrow);
notification_iv = itemView.findViewById(R.id.notification_iv);
parentRL = itemView.findViewById(R.id.parentRL);
notification_rl = itemView.findViewById(R.id.notification_rl);
arrow_click = itemView.findViewById(R.id.arrow_click);
// Store the context
// Attach a click listener to the entire row view
parentRL.setOnClickListener(this);
iv_arrow.setOnClickListener(this);
/* itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});*/
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
switch (view.getId()){
case R.id.parentRL:
try {
if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("promotion")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, InviteEarnWebViewActivity.class);
notificationIntent.putExtra("notificationClick","true");
//notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("searchQuery", adaBankDetailsList.get(position).getCustomPageUrl());
notificationIntent.putExtra("headerName", adaBankDetailsList.get(position).getCustomPageTitle());
notificationIntent.putExtra("showShareEarn","N");
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("update")) {
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse("market://details?id=com.milmila.android.milmila_home"));
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("home")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
//notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("invite")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, InviteEarnWebViewActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("searchQuery", Constants.BASE_URL+"customerInvite/inviteEarn.html?customerId=#sharedPreferenceUserId#");
notificationIntent.putExtra("headerName","Invite & Earn");
notificationIntent.putExtra("showShareEarn","Y");
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("share_earn")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, InviteEarnWebViewActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("searchQuery",Constants.BASE_URL+"double-dhamaka.html?customerId=#sharedPreferenceUserId#");
notificationIntent.putExtra("headerName","Gift your friend 100");
notificationIntent.putExtra("showShareEarn","Y");
startActivity(notificationIntent);
} else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("product")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, ProductDetailsActivity.class);
notificationIntent.putExtra("notificationClick","true");
notificationIntent.putExtra(STRING_IMAGE_PRODUCTID,(adaBankDetailsList.get(position).getLevelId()));
// notificationIntent.putExtra(STRING_IMAGE_PRODUCTID, levelId);
// notificationIntent.putExtra(STRING_IMAGE_PRODUCT_URL, "");
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("Earnings")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("mmcash", "Y");
startActivity(notificationIntent);
} else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("group")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, GroupProductListActivity.class);
notificationIntent.putExtra("notificationClick","true");
notificationIntent.putExtra("categoryID",(adaBankDetailsList.get(position).getLevelId()));
// notificationIntent.putExtra("categoryID", levelId);
notificationIntent.putExtra("categoryName", adaBankDetailsList.get(position).getGroupName());
notificationIntent.putExtra("limit", 10);
// notificationIntent.putExtra("headerImage", promotionUrl);
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("reseller")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("resell", "Y");
startActivity(notificationIntent);
} else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("normal")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, MyOrdersActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
startActivity(notificationIntent);
} else {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
startActivity(notificationIntent);
}
} catch (Exception e) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
startActivity(notificationIntent);
}
break;
case R.id.iv_arrow:
Glide.with(getApplicationContext())
.load(adaBankDetailsList.get(position).getNotificationImage())
.apply(new RequestOptions()
.placeholder(R.drawable.no_image))
.into(notification_iv);
if(flag==true)
{
notification_main_text.setSingleLine(true);
notification_main_text.setEllipsize(TextUtils.TruncateAt.END);
int n1 = 1; // the exact number of lines you want to display
notification_main_text.setLines(n1);
notification_main_text.setMaxEms(12);
iv_arrow.setImageResource(R.mipmap.down);
notification_iv.setVisibility(View.GONE);
notification_sub_text.setSingleLine(true);
notification_sub_text.setEllipsize(TextUtils.TruncateAt.END);
int n = 1; // the exact number of lines you want to display
notification_sub_text.setLines(n);
flag = false;
}
else if(flag==false)
{
notification_main_text.setSingleLine(false);
int n1 = 2; // the exact number of lines you want to display
notification_main_text.setLines(n1);
notification_main_text.setMaxEms(10);
notification_main_text.setVisibility(View.VISIBLE);
iv_arrow.setImageResource(R.mipmap.up);
notification_sub_text.setVisibility(View.VISIBLE);
if(adaBankDetailsList.get(position).getNotificationImage().equals("null"))
{
notification_iv.setVisibility(View.GONE);
}
else
{
notification_iv.setVisibility(View.VISIBLE);
}
notification_sub_text.setSingleLine(false);
int n = 2; // the exact number of lines you want to display
notification_sub_text.setLines(n);
flag = true;
}
break;
}
}
}
}

Sometime Adapter might cause position issue while scrolling the Recyclerview. You can achieve the same by tag your ImageView into the Button.
holder.your_button.setTag(holder.your_imageview);
holder.your_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ImageView selImageView = (ImageView) v.getTag();
if(selImageView.getVisibility() == View.VISIBLE) {
selImageView.setVisibility(View.INVISIBLE)
} else {
selImageView.setVisibility(View.VISIBLE)
}
}
});
Above will only trigger your view of the same position. Because we have set that ImageView to your Buttons tag and targeting only that view.

Related

Closing application undoes last action

I have an alarm clock application, and I've just added code to exit the program when using the Back button from the main activity. However, when I do so, the last action the user took is undone. For example, if the user creates three alarms, then presses the back button, only two alarms will show up.
This is the Back button code, from Main Activity:
#Override
public void onBackPressed() {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
And just in case, here's all the code from both activities I'm testing:
MainActivity.java (The only activity that has this Back button functionality, deliberately)
public class MainActivity extends AppCompatActivity {
ListView alarmListView;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
AlarmAdapter alarmAdapter;
String filename = "alarmList";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmListView = findViewById(R.id.alarmListView);
// Credit to Mitch Woodbright for helping with this section, and other try/catch blocks.
try
{
ArrayList<Alarm> alarm = (ArrayList<Alarm>) getIntent().getSerializableExtra("alarmList");
for(Alarm elements : alarm){
alarmList.add(elements);
}
writeAlarmList(alarmList);
}
catch (NullPointerException e){
System.out.println("AlarmList is empty.");
}
try {
alarmList = readAlarmList();
}
catch (NullPointerException e) {
}
alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList){
#Override
public void onUpdateClick(int position, ArrayList<Alarm> alarmList) {
super.onUpdateClick(position, alarmList);
Intent updateAlarmIntent = new Intent(MainActivity.this,
CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
};
alarmListView.setAdapter(alarmAdapter);
alarmAdapter.notifyDataSetChanged();
alarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent updateAlarmIntent = new Intent(MainActivity.this, CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
});
// writeAlarmList(alarmList);
}
protected void onStart() {
super.onStart();
alarmList = readAlarmList();
}
protected void onResume() {
super.onResume();
alarmList = readAlarmList();
}
protected void onPause() {
super.onPause();
writeAlarmList(alarmList);
}
protected void onStop() {
super.onStop();
writeAlarmList(alarmList);
}
#Override
public void onBackPressed() {
// Thanks to Mitch for this line.
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
// Create alarm when user presses FAB on activity_main.xml.
public void createNewAlarm(View view) {
Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
createAlarmIntent.putExtra("alarmList", alarmList);
startActivity(createAlarmIntent);
}
public void testAlarmActivated(View view){
//Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
//startActivity(activateAlarmIntent);
while(alarmList.size() > 0){
alarmList.remove(0);
}
Intent deleteEverythingIntent = new Intent(MainActivity.this, MainActivity.class);
deleteEverythingIntent.putExtra("alarmList", alarmList);
startActivity(deleteEverythingIntent);
}
public void writeAlarmList(ArrayList<Alarm> alarmList){
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(alarmList);
oos.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Alarm> readAlarmList(){
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Alarm> alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
return alarmList;
}
catch (FileNotFoundException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("File not found. Making empty list.");
return alarmList;
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (NullPointerException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("Null pointer exception. Making empty list.");
return alarmList;
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
return alarmList;
}
}
CreateAlarmActivity.java (The activity which does the creating/updating/deleting of alarms)
public class CreateAlarmActivity extends AppCompatActivity {
// If the alarm is being created, position = -1.
int position = -1;
int alarmHour;
int alarmMinute;
boolean isPm;
int snoozeTimer;
int[] daysActive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
try {
// If we're updating an alarm, return the position of the alarm to update.
position = (int)getIntent().getSerializableExtra("position");
}
// Else, keep going.
catch (NullPointerException e){
}
Button hourButton = findViewById(R.id.buttonHours);
Button minuteButton = findViewById(R.id.buttonMinutes);
Button isPmButton = findViewById(R.id.buttonAmPm);
Button snoozeTimerButton = findViewById(R.id.buttonSnoozeTimer);
Button sundayButton = findViewById(R.id.buttonSunday);
Button mondayButton = findViewById(R.id.buttonMonday);
Button tuesdayButton = findViewById(R.id.buttonTuesday);
Button wednesdayButton = findViewById(R.id.buttonWednesday);
Button thursdayButton = findViewById(R.id.buttonThursday);
Button fridayButton = findViewById(R.id.buttonFriday);
Button saturdayButton = findViewById(R.id.buttonSaturday);
// If creating a new alarm, initialise data as default.
if (position == -1){
alarmHour = 6;
alarmMinute = 0;
isPm = false;
snoozeTimer = 10;
daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
}
// If updating an alarm, grab the defaults we already had.
else {
Alarm tempAlarm = alarmList.get(position);
alarmHour = tempAlarm.hour;
alarmMinute = tempAlarm.minute;
isPm = tempAlarm.isPm;
snoozeTimer = tempAlarm.snoozeTimer;
daysActive = tempAlarm.daysActive;
}
// Set buttons to what they should be.
hourButton.setText(Integer.toString(alarmHour));
snoozeTimerButton.setText(Integer.toString(snoozeTimer));
if (alarmMinute < 10){
minuteButton.setText("0" + Integer.toString(alarmMinute));
}
else {
minuteButton.setText(Integer.toString(alarmMinute));
}
if (!isPm){
isPmButton.setText("am");
}
else {
isPmButton.setText("pm");
}
setDayColor(sundayButton, daysActive[0]);
setDayColor(mondayButton, daysActive[1]);
setDayColor(tuesdayButton, daysActive[2]);
setDayColor(wednesdayButton, daysActive[3]);
setDayColor(thursdayButton, daysActive[4]);
setDayColor(fridayButton, daysActive[5]);
setDayColor(saturdayButton, daysActive[6]);
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
// Add one to the hour of the alarm.
public void changeHour(View view) {
Button btn = findViewById(R.id.buttonHours);
if (alarmHour == 12){
alarmHour = 0;
}
else {
alarmHour++;
}
btn.setText(Integer.toString(alarmHour));
}
// Add one to the minute of the alarm.
public void changeMinute(View view) {
Button btn = findViewById(R.id.buttonMinutes);
if (alarmMinute == 59) {
alarmMinute = 0;
}
else {
alarmMinute++;
}
if (alarmMinute < 10) {
// Ensure minute 1 becomes 01, e.g, 6:01 am.
btn.setText("0" + Integer.toString(alarmMinute));
}
else {
btn.setText(Integer.toString(alarmMinute));
}
}
public void changeAmPm(View view) {
Button btn = findViewById(R.id.buttonAmPm);
if (isPm == true) {
isPm = false;
btn.setText("am");
}
else {
isPm = true;
btn.setText("pm");
}
}
public void changeSnoozeTimer(View view) {
Button btn = findViewById(R.id.buttonSnoozeTimer);
if (snoozeTimer == 15){
snoozeTimer = 1;
}
else {
snoozeTimer++;
}
btn.setText(Integer.toString(snoozeTimer));
}
public void finishAlarm(View view){
EditText alarmName = findViewById(R.id.alarmName);
String name = alarmName.getText().toString();
Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
// If we're creating an alarm.
if (position == -1) {
try {
alarmList.add(alarm);
} catch (Exception e) {
}
}
// Else, we're updating one.
else {
try {
// Set the alarm we're updating to the new alarm.
alarmList.set(position, alarm);
} catch (Exception e) {
}
}
Intent finishAlarmIntent = new Intent(this, MainActivity.class);
finishAlarmIntent.putExtra("alarmList", alarmList);
startActivity(finishAlarmIntent);
}
public void cancelAlarm(View view){
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
public void deleteAlarm(View view) {
// If creating a new alarm, deleting is the same as cancelling.
if (position == -1) {
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
else {
// Remove the alarm.
alarmList.remove(position);
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
}
public void changeSunday(View view) {
Button btn = findViewById(R.id.buttonSunday);
daysActive[0] = switchDay(daysActive[0]);
setDayColor(btn, daysActive[0]);
}
public void changeMonday(View view) {
Button btn = findViewById(R.id.buttonMonday);
daysActive[1] = switchDay(daysActive[1]);
setDayColor(btn, daysActive[1]);
}
public void changeTuesday(View view) {
Button btn = findViewById(R.id.buttonTuesday);
daysActive[2] = switchDay(daysActive[2]);
setDayColor(btn, daysActive[2]);
}
public void changeWednesday(View view) {
Button btn = findViewById(R.id.buttonWednesday);
daysActive[3] = switchDay(daysActive[3]);
setDayColor(btn, daysActive[3]);
}
public void changeThursday(View view) {
Button btn = findViewById(R.id.buttonThursday);
daysActive[4] = switchDay(daysActive[4]);
setDayColor(btn, daysActive[4]);
}
public void changeFriday(View view) {
Button btn = findViewById(R.id.buttonFriday);
daysActive[5] = switchDay(daysActive[5]);
setDayColor(btn, daysActive[5]);
}
public void changeSaturday(View view) {
Button btn = findViewById(R.id.buttonSaturday);
daysActive[6] = switchDay(daysActive[6]);
setDayColor(btn, daysActive[6]);
}
// Helper method to switch the daysActive from 0 to 1 or from 1 to 0.
public int switchDay(int day) {
if (day == 0){
return 1;
}
return 0;
}
// Helper method to set the color of a daysActive button when updating the alarm.
public void setDayColor(Button btn, int day) {
if (day == 1) {
// Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
// Credit goes to EddieB for the below line.
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
} else {
// Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
// Credit goes to Ivo for the below line.
btn.getBackground().clearColorFilter();
}
}
}
For people from the future:
I ended up solving this by using the following:
#Override
public void onBackPressed() {
this.finishAffinity();
}
Source: How to quit android application programmatically

How to get context in service outside of onStartCommand() method?

When I use Intent outside of onStartCommand() of service, to show notification on a specific event, it shows getApplicationContext on the null object reference.
Service only allow to use getApplcationContext/this/context inside the onStartCommand() method.
How can I use it outside of onStartCommand() method?
Below is my Service. Can someone help me out with this?
public class ForegroundService extends Service {
#Nullable
private static TransferUtility transferUtility;
private static ArrayList<HashMap<String, Object>> transferRecordMaps;
private static ArrayList<HashMap<String, Object>> transferRecordMaps1;
private Utils utils = new Utils();
private static final int INDEX_NOT_CHECKED = -1;
public static int totalcount, totalAssetCount;
private int checkedIndex;
private static List<TransferObserver> observers;
private static int REQUEST_CAMERA = 0, navigate = 0,counter=0,failedcounter=0;
private static final String LOG_TAG = "ForegroundService";
UploadMediaToAssetFragment uploadMediaToAssetFragment;
private int progress;
Context context;
private long currentbyte, totalbyte;
private Notification notification;
#Override
public void onCreate() {
super.onCreate();
transferUtility = Util.getTransferUtility(getApplicationContext());
checkedIndex = INDEX_NOT_CHECKED;
transferRecordMaps = new ArrayList<HashMap<String, Object>>();
transferRecordMaps1 = new ArrayList<HashMap<String, Object>>();
uploadMediaToAssetFragment = new UploadMediaToAssetFragment();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Intent notificationIntent = new Intent(this, UploadMediaToAssetFragment.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
Log.d(LOG_TAG,"bytes"+UploadMediaToAssetFragment.totalAssetCount+ " total"+UploadMediaToAssetFragment.totalcount);
uploadAsset();
initData();
updateList();
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Test dialog");
// builder.setIcon(R.drawable.icon);
// builder.setMessage("Content");
//
// AlertDialog alert = builder.create();
// alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alert.show();
// startActivity(notificationIntent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, ForegroundService.class);
previousIntent.setAction(Constants.ACTION.PREV_ACTION);
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, ForegroundService.class);
playIntent.setAction(Constants.ACTION.PLAY_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Intent nextIntent = new Intent(this, ForegroundService.class);
nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
PendingIntent pnextIntent = PendingIntent.getService(this, 0,
nextIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);
notification = new NotificationCompat.Builder(this)
.setContentTitle("Visibly")
.setTicker("asset uplaoding")
.setContentText("uploading")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(
Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.setProgress(100,progress,false)
.addAction(android.R.drawable.ic_menu_close_clear_cancel,
"cancel", ppreviousIntent).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
// if(UploadMediaToAssetFragment.totalAssetCount>=UploadMediaToAssetFragment.totalcount)
// {
// onDestroy();
// stopForeground(true);
// stopSelf();
// }
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
Log.i(LOG_TAG, "Clicked Previous");
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
Log.i(LOG_TAG, "Clicked Play");
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
Log.i(LOG_TAG, "Clicked Next");
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Stop Foreground Intent");
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
public IBinder onBind(Intent intent) {
return null;
}
public class ForegroundServiceBInder extends Binder {
ForegroundService getService() {
// Return this instance of LocalService so clients can call public methods
return ForegroundService.this;
}
}
public void uploadAsset()
{
Log.d("upload asset service","method called");
for(int i=0;i<AddMediaAssetActivity.galleryDTOArrayList1.size();i++)
{
Handler handler1 = new Handler();
try {
if(AddMediaAssetActivity.galleryDTOArrayList1.get(i)!=null)
{
String path;
Uri uri = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getMediaName()));
path = Utility.getPath(uri, getApplicationContext());
Uri uriThumb = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getThumbnail()));
String pathThum = null;
if (uriThumb != null)
pathThum = Utility.getPath(uriThumb, getApplicationContext());
path = Utility.getPath(uri, getApplicationContext());
if(GlobalVariables.isNetworkAvailable(getApplicationContext())) {
beginUpload1(pathThum, pathThum);
beginUpload(path, AddMediaAssetActivity.galleryDTOArrayList1.get(i).getDescription(), pathThum,AddMediaAssetActivity.galleryDTOArrayList1.get(i).getCreateTagPostDTOList());
}else
{
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getApplicationContext(),android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getApplicationContext());
}
builder.setMessage(getResources().getString(R.string.network_connectivity))
.setTitle("");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
//getApplicationContext().finish();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.clear_blue));
}
}
}catch (Exception e)
{
}
}
}
/*
* Begins to upload the file specified by the file path.
*/
private void beginUpload(String filePath, String title, String pathThum, List<TagDTO> createTagPostDTOList)
{
Log.d("beginUpload","method called "+filePath+" title "+title+" pathnum "+pathThum+" list tagdto"+createTagPostDTOList);
if (filePath == null) {
Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
Toast.LENGTH_LONG).show();
return;
}
File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
file, CannedAccessControlList.PublicRead);
File file1 = new File(pathThum);
AssetMediaDTO assetMediaDTO=new AssetMediaDTO();
if(GlobalVariables.isCampaignAsset)
{
if (GlobalVariables.campaignFeedDTO.getCampaign_category() != null && GlobalVariables.campaignFeedDTO.getCampaign_category().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_category().equalsIgnoreCase("null"))) {
assetMediaDTO.setCategory_id(GlobalVariables.campaignFeedDTO.getCampaign_category());
} else {
assetMediaDTO.setCategory_id("rpPDp");
}
if (GlobalVariables.campaignFeedDTO.getCampaign_folder() != null && GlobalVariables.campaignFeedDTO.getCampaign_folder().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("null"))) {
if(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("General"))
{
assetMediaDTO.setFolder_id("");
}else
{
assetMediaDTO.setFolder_id(GlobalVariables.campaignFeedDTO.getCampaign_folder());
}
} else
{
assetMediaDTO.setFolder_id("");
}
}else
{
if (AssetFolderActivity.folderDTO.getCategoryID() != null && AssetFolderActivity.folderDTO.getCategoryID().length() > 0 && !(AssetFolderActivity.folderDTO.getCategoryID().equalsIgnoreCase("null"))) {
assetMediaDTO.setCategory_id(AssetFolderActivity.folderDTO.getCategoryID());
} else {
assetMediaDTO.setCategory_id("rpPDp");
}
if (AssetFolderActivity.folderDTO.getFolderIdentity() != null && AssetFolderActivity.folderDTO.getFolderIdentity().length() > 0 && !(AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("null"))) {
if(AssetFolderActivity.folderDTO.getFoldername()!=null&&AssetFolderActivity.folderDTO.getFoldername().equalsIgnoreCase("general"))
{
assetMediaDTO.setFolder_id("");
}else {
assetMediaDTO.setFolder_id(AssetFolderActivity.folderDTO.getFolderIdentity());
}
} else {
assetMediaDTO.setFolder_id("");
}
}
assetMediaDTO.setMedia_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file.getName());
assetMediaDTO.setThumbnail_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file1.getName());
try {
assetMediaDTO.setMediaSize(""+file.length());
}catch (Exception e)
{
}
assetMediaDTO.setDetail(title);
String result = file.getName().substring(0, file.getName().lastIndexOf("."));
assetMediaDTO.setTitle(result);
assetMediaDTO.setTagDTOList(createTagPostDTOList);
GlobalVariables.assetMediaDTOList.add(assetMediaDTO);
}
/*
* Begins to upload the file specified by the file path.
*/
private void beginUpload1(String filePath, String pathThum) {
Log.d("beginUpload1","method called");
if (filePath == null) {
Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
Toast.LENGTH_LONG).show();
return;
}
File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
file,CannedAccessControlList.PublicRead);
// temp1=file.getName();
}
//To delete assets from list
public void deleteMediaUpload(final int position)
{
final int position1=position+1;
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(GlobalVariables.mActivity, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(GlobalVariables.mActivity);
}
builder.setMessage("Do you want to delete this media?")
.setTitle("");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
if (position >= 0 && position1 < observers.size())
{
try {
transferUtility.deleteTransferRecord(observers.get(position).getId());
transferUtility.deleteTransferRecord(observers.get(position1).getId());
observers.remove(position1);
transferRecordMaps.remove(position1);
observers.remove(position);
transferRecordMaps.remove(position);
AddMediaAssetActivity.galleryDTOArrayList1.remove(position);
}catch (Exception e)
{
}
updateList();
try {
GlobalVariables.assetMediaDTOList.remove(position);
}catch (Exception e)
{
}
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
}
// /**
// * Gets all relevant transfers from the Transfer Service for populating the
// * UI
// */
// private void initData() {
// counter=0;
// failedcounter=0;
// navigate=0;
// transferRecordMaps.clear();
// transferRecordMaps1.clear();
// // Use TransferUtility to get all upload transfers.
// observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
// TransferListener listener = new UploadMediaToAssetFragment.UploadListener();
// for (TransferObserver observer : observers) {
//
// // For each transfer we will will create an entry in
// // transferRecordMaps which will display
// // as a single row in the UI
// HashMap<String, Object> map = new HashMap<String, Object>();
// Util.fillMap(map, observer, false);
//
// transferRecordMaps.add(map);
//
// // Sets listeners to in progress transfers
// if (TransferState.WAITING.equals(observer.getState())
// || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
// || TransferState.IN_PROGRESS.equals(observer.getState())) {
// observer.setTransferListener(listener);
// }
// }
// transferRecordMaps1.clear();
// for(int i=0;i<transferRecordMaps.size();i++)
// {
// File file = new File((String) transferRecordMaps.get(i).get("fileName"));
// if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
// {
// }
// else
// {
// transferRecordMaps1.add(transferRecordMaps.get(i));
//
// }
//
// }
// assetListAdapter.notifyDataSetChanged();
// }
/*
* A TransferListener class that can listen to a upload task and be notified
* when the status changes.
*/
public class UploadListener implements TransferListener {
// Simply updates the UI list when notified.
#Override
public void onError(int id, Exception e)
{
failedcounter++;
updateList();
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
updateList();
currentbyte =bytesCurrent;
totalbyte =bytesTotal;
Log.d("onprogresschnaged","method bytes"+bytesCurrent+" bytestotoal"+bytesTotal);
}
#Override
public void onStateChanged(int id, TransferState newState)
{
if (newState.equals(TransferState.COMPLETED))
{
counter++;
updateList();
} else if (newState.equals(TransferState.FAILED))
{
failedcounter++;
updateList();
}
}
}
/*
* Updates the ListView according to the observers.
*/
/*
* Updates the ListView according to the observers.
*/
public void updateList()
{
if(transferRecordMaps!=null&&transferRecordMaps.size()>0)
{
TransferObserver observer = null;
HashMap<String, Object> map = null;
for (int i = 0; i < observers.size(); i++) {
observer = observers.get(i);
map = transferRecordMaps.get(i);
progress = (int) ((double) observer.getBytesTransferred() * 100 / observer
.getBytesTotal());
Log.d("progressuploadingData"," map"+progress);
Util.fillMap(map, observer, i == checkedIndex);
Log.d("uploadingData"," map"+map+" observer"+observer);
}
transferRecordMaps1.clear();
for (int i = 0; i < transferRecordMaps.size(); i++)
{
File file = new File((String) transferRecordMaps.get(i).get("fileName"));
if (file.getName().substring(0, 2).equalsIgnoreCase("0!")) {
} else
{
transferRecordMaps1.add(transferRecordMaps.get(i));
}
totalcount=transferRecordMaps.size();
totalAssetCount=counter+failedcounter;
Log.d("totalcount","count"+totalcount+"toatlassetcount"+totalAssetCount);
if(counter>1&&totalAssetCount>=totalcount&&GlobalVariables.assetMediaDTOList.size()>0)
{
Log.d("myservice asset","complete");
navigate=1;
Intent intent = new Intent(this, DialogeActivity.class);
context.getApplicationContext().startActivity(intent);
// Toast.makeText(this,"Your asset uploaded successfully",Toast.LENGTH_LONG).show();
// Intent notificationIntent = new Intent(this, DialogeActivity.class);
// notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
// notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(notificationIntent);
// Notification notification = new NotificationCompat.Builder(this)
// .setContentTitle("Visibly")
// .setTicker("asset uploaded")
// .setContentText("asset uploaded successfully")
// .setSmallIcon(R.drawable.ic_launcher)
// .build();
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Test dialog");
// builder.setIcon(R.drawable.icon);
// builder.setMessage("Content");
// builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// //Do something
// dialog.dismiss();
// });
//
// AlertDialog alert = builder.create();
// alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alert.show();
// AlertDialog alertDialog = new AlertDialog.Builder(this)
// .setTitle("Title")
// .setMessage("Are you sure?")
// .create();
//
// alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alertDialog.show();
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Done");
// button_Done.setEnabled(true);
// button_Done.setClickable(true);
}else if(failedcounter>=totalcount)
{
navigate=0;
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Back");
// button_Done.setEnabled(true);
// button_Done.setClickable(true);
}else
{
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Please wait.");
// button_Done.setEnabled(false);
// button_Done.setClickable(false);
}
}
// assetListAdapter.notifyDataSetChanged();
}else
{
// Intent intent=null;
// if( AssetFolderActivity.folderDTO!=null&&AssetFolderActivity.folderDTO.getFolderIdentity()!=null&& AssetFolderActivity.folderDTO.getFolderIdentity().length()>0&&!AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("")) {
// intent = new Intent(activity, AssetFolderActivity.class);
// }else
// {
// intent = new Intent(activity, DashboardActivity.class);
// }
// intent.putExtra("folderDTO", AssetFolderActivity.folderDTO);
// activity.startActivity(intent);
// activity.finish();
}
}
private void initData() {
counter=0;
failedcounter=0;
navigate=0;
transferRecordMaps.clear();
transferRecordMaps1.clear();
// Use TransferUtility to get all upload transfers.
observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
TransferListener listener = new ForegroundService().new UploadListener();
for (TransferObserver observer : observers) {
// For each transfer we will will create an entry in
// transferRecordMaps which will display
// as a single row in the UI
HashMap<String, Object> map = new HashMap<String, Object>();
Util.fillMap(map, observer, false);
transferRecordMaps.add(map);
// Sets listeners to in progress transfers
if (TransferState.WAITING.equals(observer.getState())
|| TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
|| TransferState.IN_PROGRESS.equals(observer.getState())) {
observer.setTransferListener(listener);
}
}
transferRecordMaps1.clear();
for(int i=0;i<transferRecordMaps.size();i++)
{
File file = new File((String) transferRecordMaps.get(i).get("fileName"));
if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
{
}
else
{
transferRecordMaps1.add(transferRecordMaps.get(i));
}
}
// assetListAdapter.notifyDataSetChanged();
}
}
Service only allow to use getApplcationContext/this/context inside the onStartCommand() method
There is no such restriction. You can use it from other methods on your Service, so long as onCreate() has already been called on that Service.
So, to show a Notification from some background thread that your Service forks from onStartCommand(), for example, use this.
Service is child of Context class, that would provide you context when you need. It behaves like an activity (child of context too.)
So same like Activity, you can call this or yourService.this(in anonymus class) keyword as a context.
In updateList() you do this:
context.getApplicationContext().startActivity(intent);
context is a member variable of your Service. However, you never initialize this variable to anything. Therefore it is null, which will cause the error you describe.
Sevices has his own context. There is easy way to have an globl context.
private Context context;
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
context = this;
}
That's all. Should work, if not let search an problem in other place.
#Edit
For clarity, your problem causes this line, because your context is not assigned, and it's null.
context.getApplicationContext().startActivity(intent);

Activity Memory Leak reported by LeakCanary - WindowManagerGlobal

There is a memory leak reported by LeakCanary in my Android App. I have Googled and studied for days and cannot find any solution. The leaked object is an instance of Activity called "MakeFire". It seems to be related to android.view.WindowManagerGlobal. Can anyone point out how the leak happened, and how to fix it?
Here is the LeakCanary ScreenCap
Here is the source code of the MakeFire Activity
public class MakeFire extends SharedMethod implements StatusBarFragment.OnFragmentInteractionListener,
DayTimeFragment.OnFragmentInteractionListener, BackButtonFragment.OnFragmentInteractionListener {
private Button firePlough;
private Button bowDrill;
private TextView makeFireWithBowDrillTime;
private TextView requirementTextview;
private Button performButton;
private String selectedButton;
private boolean firePloughOn;
private boolean bowDrillOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_fire);
firePlough = (Button) findViewById(R.id.firePlough);
bowDrill = (Button) findViewById(R.id.bowDrill);
makeFireWithBowDrillTime = (TextView) findViewById(R.id.makeFireWithBowDrillTime);
requirementTextview = (TextView) findViewById(R.id.requirementTextview);
performButton = (Button) findViewById(R.id.performButton);
}
#Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
#Override
public void onBackPressed() {
Bundle extra = new Bundle();
extra.putString("classToGoBack", getClass().getName());
Intent intent = new Intent(this, InGameMenu.class);
intent.putExtras(extra);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
GameData.useImmersiveModeSticky(this);
}
#Override
public void onStop() {
super.onStop();
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGame", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
//TODO - delete it before uploading the app
GameData.GDI.showPlainMsg("sharedMethodProblem!", this);
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
GameData.GDI.showPlainMsg(sw.getBuffer().toString(), this);
}
boolean savedGameIsFine;
try {
FileInputStream latestSavedGame = openFileInput("latestSavedGame");
ObjectInputStream latestGameData = new ObjectInputStream(latestSavedGame);
savedGameIsFine = (latestGameData.readObject() != null);
latestSavedGame.close();
} catch (Exception e) {
savedGameIsFine = false;
}
if (savedGameIsFine) {
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGameBackup", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
}
} else {
}
}
#Override
protected void onStart() {
super.onStart();
updateAllViews();
requirementTextview.setVisibility(View.INVISIBLE);
performButton.setVisibility(View.INVISIBLE);
}
//method for updating all amendable views in the page
private void updateAllViews() {
//visibility of fire plough button
if (GameData.GDI.anyThisInventoryAvailable(GameData.FIRE_PLOUGH) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
firePloughOn = true;
}
else {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f_o,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
firePloughOn = false;
}
//visibility of bow drill button
if (GameData.GDI.bowDrillUnlocked) {
bowDrill.setVisibility(View.VISIBLE);
makeFireWithBowDrillTime.setVisibility(View.VISIBLE);
if (GameData.GDI.anyThisInventoryAvailable(GameData.BOW_DRILL) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
bowDrillOn = true;
}
else {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f_o,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
bowDrillOn = false;
}
}
updateStatusBarFragment();
updateDayTimeFragment();
}
public void makeFireWithFirePlough(View view) {
if (firePloughOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithFirePloughRqm);
selectedButton = "fire plough";
}
public void makeFireWithBowDrill(View view) {
if (bowDrillOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithBowDrillRqm);
selectedButton = "bow drill";
}
public void perform(View view){
if (!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock){
switch (selectedButton){
case "fire plough":
String msgToShow = "";
String extraInfo = "";
String[] timePassMsg;
Bundle extras = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg = GameData.GDI.timePass(30, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.firePloughDurability = GameData.GDI.updateInventoryDurability(GameData.FIRE_PLOUGH, GameData.GDI.firePloughDurability, GameData.FIRE_PLOUGH_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.firePloughDurability == GameData.FIRE_PLOUGH_MAX_DURABILITY) {
extraInfo += getString(R.string.firePloughBreakMsg) + "\n\n";
}
GameData.GDI.bowDrillUnlockCounter += 1;
if (Math.random() < 0.75) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow += getString(R.string.success) + "\n";
extras.putString("className", "Fire");
}
else {
msgToShow += getString(R.string.fail) + "\n";
if (!GameData.GDI.bowDrillUnlocked) {
if (GameData.GDI.bowDrillUnlockCounter >= 3) {
extraInfo += getString(R.string.bowDrillUnlockMsg) + "\n\n";
GameData.GDI.bowDrillUnlocked = true;
GameData.GDI.setCraftingAlertIcon(3);
}
}
extras.putString("className", "Make Fire");
}
Intent intent = new Intent(this, LoadingPage.class);
extras.putString("actionName", getString(R.string.makingFireWithFirePlough));
extras.putInt("timeNeeded", 30);
extras.putString("msgToShow", msgToShow);
extras.putString("extraInfo", extraInfo);
extras.putString("timePassMsg", timePassMsg[0]);
extras.putString("deathReason", timePassMsg[1]);
intent.putExtras(extras);
startActivity(intent);
break;
case "bow drill":
String msgToShow1 = "";
String extraInfo1 = "";
String[] timePassMsg1;
Bundle extras1 = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg1 = GameData.GDI.timePass(10, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras1.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.bowDrillDurability = GameData.GDI.updateInventoryDurability(GameData.BOW_DRILL, GameData.GDI.bowDrillDurability, GameData.BOW_DRILL_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.bowDrillDurability == GameData.BOW_DRILL_MAX_DURABILITY) {
extraInfo1 += getString(R.string.bowDrillBreakMsg) + "\n\n";
}
if (Math.random() < 0.95) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow1 += getString(R.string.success) + "\n";
extras1.putString("className", "Fire");
}
else {
msgToShow1 += getString(R.string.fail) + "\n";
extras1.putString("className", "Make Fire");
}
Intent intent1 = new Intent(this, LoadingPage.class);
extras1.putString("actionName", getString(R.string.makingFireWithBowDrill));
extras1.putString("className", "Fire");
extras1.putInt("timeNeeded", 10);
extras1.putString("msgToShow", msgToShow1);
extras1.putString("extraInfo", extraInfo1);
extras1.putString("timePassMsg", timePassMsg1[0]);
extras1.putString("deathReason", timePassMsg1[1]);
intent1.putExtras(extras1);
startActivity(intent1);
break;
}
}
else {
GameData.GDI.showPlainMsg(getString(R.string.cannotMakeFireInStormMsg), this);
}
}
//fragment method
public void updateStatusBarFragment() {
StatusBarFragment statusBarFragment = (StatusBarFragment)getSupportFragmentManager().findFragmentById(R.id.statusBarFragment);
statusBarFragment.updateStatusBar();
}
public void updateDayTimeFragment() {
DayTimeFragment dayTimeFragment = (DayTimeFragment)getSupportFragmentManager().findFragmentById(R.id.dayTimeFragment);
dayTimeFragment.updateDayTimeView();
}
public void backButton(View view){
Intent intent = new Intent(this, Fire.class);
startActivity(intent);
}
}

Call Function from android service

Hi Hello to everyone i am developing one app where i am using service to upload multipal images to server for uploading multipal images even if app is closed from background.
But i want to call one function but i am unable to call that function please help me.
UploadPhotos.java
public class UploadPhotos extends AppCompatActivity {
UploadService mBoundService;
boolean mServiceBound = false;
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type,album_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
ProgressBar pb;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
OrderId orderidsession;
AlertDialog dialog;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
NotificationManager manager;
Notification.Builder builder;
ArrayList<CustomGallery> dataT;
Notification myNotication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photos);
context = this;
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
labSession = new SelectLab(getApplicationContext());
paperSession = new SelectPaper(getApplicationContext());
orderidsession=new OrderId(getApplicationContext());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
user_mail = user.get(SessionManager.KEY_EMAIL);
noImage = (TextView)findViewById(R.id.noImage);
final String symbol = getResources().getString(R.string.rupee_symbol);
HashMap<String, String> paper = paperSession.getPaperDetails();
strSize = paper.get(SelectPaper.KEY_SIZE);
strType = paper.get(SelectPaper.KEY_TYPE);
strdel_type=paper.get(SelectPaper.DEL_TYPE);
HashMap<String, String> lab = labSession.getLabDetails();
strMRP = lab.get(SelectLab.KEY_MRP);
strPrice = lab.get(SelectLab.KEY_PRICE);
strlab = lab.get(SelectLab.KEY_LAB);
strcity = lab.get(SelectLab.KEY_CITY);
str_username=lab.get(SelectLab.KEY_USERNAME);
ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
mrp = (MaterialEditText) findViewById(R.id.MRP);
disPrice = (MaterialEditText) findViewById(R.id.discount_price);
ppr_size.setText(strSize);
ppr_type.setText(strType);
mrp.setText(symbol + " " + strMRP);
disPrice.setText(symbol + " " + strPrice);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
UploadGallery = (GridView) findViewById(R.id.uploadGallery);
UploadGallery.setFastScrollEnabled(true);
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
UploadGallery.setAdapter(selectedAdapter);
btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
btnUpload = (Button) findViewById(R.id.btn_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listOfPhotos = selectedAdapter.getAll();
if (listOfPhotos != null && listOfPhotos.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
abc = sdf.format(new Date());
Log.d("Orderid Session", ""+abc);
abc="EPP"+abc;
orderidsession.CreateOrderId(abc);
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();
//progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
//AlertDialog dialog;;
dialog = new SpotsDialog(UploadPhotos.this);
dialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
Intent in = new Intent(UploadPhotos.this, UploadService.class);
in.putExtra("listof",dataT);
in.putExtra("strsize",strSize);
in.putExtra("strtype",strType);
in.putExtra("user_mail",user_mail);
in.putExtra("strmrp",strMRP);
in.putExtra("strprice",strPrice);
in.putExtra("strlab",strlab);
in.putExtra("strcity",strcity);
in.putExtra("strdel_type",strdel_type);
in.putExtra("strusername",str_username);
in.putExtra("foldername",abc);
startService(in);
bindService(in, mServiceConnection, Context.BIND_AUTO_CREATE);
// doFileUpload();
runOnUiThread(new Runnable() {
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
totalprice=0;
}
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
selectedAdapter.getItem(position);
// selectedAdapter.Pbbar(view );
Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
//selectedAdapter.changeSelection(view, position);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
noImage.setVisibility(View.GONE);
UploadGallery.setVisibility(View.VISIBLE);
dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
Log.d("DATAt",dataT.toString());
selectedAdapter.addAll(dataT);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_upload_photos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mServiceBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
UploadService.MyBinder myBinder = (UploadService.MyBinder) service;
mBoundService = myBinder.getService();
mServiceBound = true;
}
};
}
SelectedAdapter_Test.java
public class SelectedAdapter_Test extends BaseAdapter{
private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
mContext = c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageLoader = imageLoader;
// clearCache();
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgEdit;
EditText qty;
Button ok;
ProgressBar pb;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
} else {
data.get(position).isSeleted = true;
((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
}
}
public void Pbbar(View v) {
((ViewHolder)v.getTag()).pb.setVisibility(View.VISIBLE);
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.pb=(ProgressBar)convertView.findViewById(R.id.pb_image_upload);
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty = 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public ArrayList getAll(){
return data;
}
}
and here is the service
public class UploadService extends Service {
private static String LOG_TAG = "BoundService";
private IBinder mBinder = new MyBinder();
ArrayList<CustomGallery> listOfPhotos;
int i=0;
ImageLoader imageLoader;
NotificationManager manager;
Notification myNotication;
String response_str=null;
long totalprice=0;
Notification.Builder builder;
SelectedAdapter_Test selectedAdapter;
String strsize,strtype,usermail,total,strmrp,strprice,strlab,strcity,abc,strdel_type,struname,imageName;
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
#Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
Toast.makeText(UploadService.this, "Service Started ", Toast.LENGTH_SHORT).show();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
listOfPhotos = (ArrayList<CustomGallery>) intent.getSerializableExtra("listof");
strsize = intent.getStringExtra("strsize");
strtype = intent.getStringExtra("strtype");
usermail = intent.getStringExtra("user_mail");
strmrp = intent.getStringExtra("strmrp");
strprice = intent.getStringExtra("strprice");
strlab = intent.getStringExtra("strlab");
strcity = intent.getStringExtra("strcity");
struname = intent.getStringExtra("strusername");
strdel_type = intent.getStringExtra("strdel_type");
abc = intent.getStringExtra("foldername");
// selectedAdapter.Pbbar(view);
Intent intn = new Intent("com.dhruva.eprintpost.digitalPrinting");
PendingIntent pendingIntent = PendingIntent.getActivity(UploadService.this, 1, intn, 0);
builder = new Notification.Builder(UploadService.this);
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setContentTitle("Uploading Photos");
builder.setContentText("Uploading PhotoPrinting Images");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
for( i = 0 ; i<listOfPhotos.size();i++) {
try {
File f = new File(listOfPhotos.get(i).sdcardPath.toString());
//Toast.makeText(UploadService.this, "aa "+listOfPhotos.get(i).sdcardPath, Toast.LENGTH_SHORT).show();
int j=i+1;
builder.setSubText("Uploading " + j + " of " + listOfPhotos.size() + " image"); //API level 16
j++;
Toast.makeText(UploadService.this, "i is = "+i, Toast.LENGTH_SHORT).show();
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
imageName = f.getName();
totalprice = totalprice + Long.parseLong(strprice);
total = String.valueOf(totalprice);
Log.v("Abhijit", "" + totalprice);
String responseString = null;
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("http://abcdefg.com/abcd/UploadFile?foldername=" + abc); //TODO - to hit URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
Toast.makeText(UploadService.this, "aa "+sourceFile.getName(), Toast.LENGTH_SHORT).show();
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strsize));
entity.addPart("type",
new StringBody(strtype));
entity.addPart("username",
new StringBody(usermail));
entity.addPart("total",
new StringBody(total));
entity.addPart("mrp",
new StringBody(strmrp));
entity.addPart("price",
new StringBody(strprice));
entity.addPart("lab",
new StringBody(strlab));
Toast.makeText(UploadService.this, "aa Ky Ho raha hai bhai", Toast.LENGTH_SHORT).show();
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
String initflag = String.valueOf(i + 1);
entity.addPart("initflag",
new StringBody(initflag));
entity.addPart("lab_username",
new StringBody(struname));
// totalSize = entity.getContentLength();
httppost.setEntity(entity);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
response_str = EntityUtils.toString(r_entity);
if (r_entity != null) {
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
responseString = e.toString();
Toast.makeText(UploadService.this, "Exception Occured2 ", Toast.LENGTH_SHORT).show();
}catch(Exception e)
{
Toast.makeText(UploadService.this, "Exception Occured 3", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return Service.START_NOT_STICKY;
}
public class MyBinder extends Binder {
UploadService getService() {
return UploadService.this;
}
}
}
Here i want to call pbbar function from adapter class but i am unable to send view parameter to function from server.
Please help me i am new to android
another problem is that the value in notification is not changing it take last value of i throughout the execuation.
i want to update the value of i according to the successful upload image

Android Progress Bar stops working in the middle

I am working with ASYNTask. And I have used a custom progressbar. It stops working after sometime of spinning, and after that a blank(black colored) screen comes for 2 secs and then my UI for the next screen loads on.
public class LoginActivity extends Activity {
/** Variable define here. */
private EditText metLoginUserName, metLoginPassword;
private Button mbtnLogin;
private ImageView ivRegister;
private String Host, username, password;
private int Port;
private UserChatActivity xmppClient;
public static ArrayList<String> all_user = new ArrayList<String>();
public static CustomProgressDialog mCustomProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginlayout);
metLoginUserName = (EditText) this.findViewById(R.id.etLoginUserName);
metLoginPassword = (EditText) this.findViewById(R.id.etLoginPassword);
mbtnLogin = (Button) findViewById(R.id.btnLogin);
ivRegister = (ImageView) findViewById(R.id.ivRegister);
/** Set the hint in username and password edittext */
metLoginUserName = CCMStaticMethod.setHintEditText(metLoginUserName,
getString(R.string.hint_username), true);
metLoginPassword = CCMStaticMethod.setHintEditText(metLoginPassword,
getString(R.string.hint_password), true);
/** Click on login button */
mbtnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/** Login Activity */
username = metLoginUserName.getText().toString();
password = metLoginPassword.getText().toString();
CCMStaticVariable.musername = username;
CCMStaticVariable.musername = password;
if(CCMStaticMethod.isInternetAvailable(LoginActivity.this)){
LoginUserTask loginUserTask = new LoginUserTask(v.getContext());
loginUserTask.execute();
}
}
});
/** Click on forgot button */
this.findViewById(R.id.ivForgot).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,
ForgotPassActivity.class));
}
});
/** Click on register button */
ivRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,
RegisterActivity.class));
}
});
}
public class LoginUserTask extends AsyncTask<Void, Void, XMPPConnection> {
public LoginUserTask(Context context) {
super();
this.context = context;
}
private Context context;
#Override
protected void onPostExecute(XMPPConnection result) {
if (result != null) {
/**Start services*/
startService(new Intent(LoginActivity.this, UpdaterService.class));
/**Call usermenu activity*/
finish();
startActivity(new Intent(LoginActivity.this,UserMenuActivity.class));
} else {
DialogInterface.OnClickListener LoginUnSuccessOkAlertListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
CCMStaticMethod.showAlert(context, "Login",
"Invalid Username or Password. Try Again !", R.drawable.unsuccess,
true, true, "Ok", LoginUnSuccessOkAlertListener, null,
null);
}
mCustomProgressDialog.dismiss();
}
#Override
protected void onPreExecute() {
mCustomProgressDialog = CustomProgressDialog.createDialog(
LoginActivity.this, "", "");
mCustomProgressDialog.show();
}
#Override
protected XMPPConnection doInBackground(Void... params) {
CCMStaticVariable.CommonConnection = XMPPConn.checkXMPPConnection(username,
password);
return CCMStaticVariable.CommonConnection;
}
}
}
UserMenuActivity
public class UserMenuActivity extends ExpandableListActivity {
private XMPPConnection connection;
String name,availability,subscriptionStatus;
TextView tv_Status;
public static final String ACTION_UPDATE = "ACTION_UPDATE";
/** Variable Define here */
private String[] data = { "View my profile", "New Multiperson Chat",
"New Broad Cast Message", "New Contact Category", "New Group",
"Invite to CCM", "Search", "Expand All", "Settings", "Help",
"Close" };
private String[] data_Contact = { "Rename Category","Move Contact to Category", "View my profile",
"New Multiperson Chat", "New Broad Cast Message",
"New Contact Category", "New Group", "Invite to CCM", "Search",
"Expand All", "Settings", "Help", "Close" };
private String[] data_child_contact = { "Open chat", "Delete Contact","View my profile",
"New Multiperson Chat", "New Broad Cast Message",
"New Contact Category", "New Group", "Invite to CCM", "Search",
"Expand All", "Settings", "Help", "Close" };
private String[] menuItem = { "Chats", "Contacts", "CGM Groups", "Pending","Request" };
private List<String> menuItemList = Arrays.asList(menuItem);
private int commonGroupPosition = 0;
private String etAlertVal;
private DatabaseHelper dbHelper;
private int categoryID, listPos;
/** New Code here.. */
private ArrayList<String> groupNames;
private ArrayList<ArrayList<ChildItems>> childs;
private UserMenuAdapter adapter;
private Object object;
private CustomProgressDialog mCustomProgressDialog;
private String[] data2 = { "PIN Michelle", "IP Call" };
private ListView mlist2;
private ImageButton mimBtnMenu;
private LinearLayout mllpopmenu;
private View popupView;
private PopupWindow popupWindow;
private AlertDialog.Builder alert;
private EditText input;
private TextView mtvUserName, mtvUserTagLine;
private ExpandableListView mExpandableListView;
public static List<CategoryDataClass> categoryList;
public static ArrayList<String> chatUser;
private boolean menuType = false;
private String childValContact="";
public static Context context;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.usermenulayout);
dbHelper = new DatabaseHelper(UserMenuActivity.this);
XMPPConn.getContactList();
connection = CCMStaticVariable.CommonConnection;
registerReceiver(UpdateList, new IntentFilter(ACTION_UPDATE));
}
#Override
public void onBackPressed() {
if (mllpopmenu.getVisibility() == View.VISIBLE) {
mllpopmenu.setVisibility(View.INVISIBLE);
} else {
if (CCMStaticVariable.CommonConnection.isConnected()) {
CCMStaticVariable.CommonConnection.disconnect();
}
super.onBackPressed();
}
}
#SuppressWarnings("unchecked")
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (mllpopmenu.getVisibility() == View.VISIBLE) {
mllpopmenu.setVisibility(View.INVISIBLE);
} else {
if (commonGroupPosition >= 4 && menuType == true) {
if(childValContact == ""){
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText,
data_Contact));
}else{
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText,
data_child_contact));
}
} else if (commonGroupPosition == 0) {
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText, data));
}
}
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onResume() {
super.onResume();
mCustomProgressDialog = CustomProgressDialog.createDialog(
UserMenuActivity.this, "", "");
mCustomProgressDialog.show();
new Thread(){
public void run() {
XMPPConn.getContactList();
expendableHandle.sendEmptyMessage(0);
};
}.start();
super.onResume();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(UpdateList);
}
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if(groupPosition == 0){
Intent intent = new Intent(UserMenuActivity.this,UserChatActivity.class);
intent.putExtra("userNameVal",chatUser.get(childPosition));
intent.putExtra("message","");
startActivity(intent);
}else if (groupPosition == 1 && childPosition == 0) {
startActivity(new Intent(UserMenuActivity.this,
InvitetoCCMActivity.class));
} else if (groupPosition == 1 && childPosition != 0) {
Intent intent = new Intent(UserMenuActivity.this,
UserChatActivity.class);
intent.putExtra("userNameVal",
XMPPConn.mfriendList.get(childPosition - 1).friendName);
intent.putExtra("message","");
startActivity(intent);
} else if (groupPosition == 2 && childPosition == 0) {
startActivity(new Intent(UserMenuActivity.this,
CreateGroupActivity.class));
} else if (groupPosition == 2 && childPosition != 0) {
String GROUP_NAME = childs.get(groupPosition).get(childPosition)
.getName().toString();
int end = GROUP_NAME.indexOf("(");
CCMStaticVariable.groupName = GROUP_NAME.substring(0, end).trim();
startActivity(new Intent(UserMenuActivity.this,
GroupsActivity.class));
} else if (groupPosition >= 4) {
childValContact = childs.get(groupPosition).get(childPosition).getName().trim();
showToast("user==>"+childValContact, 0);
}
return false;
}
private void setExpandableListView() {
/***###############GROUP ARRAY ############################*/
final ArrayList<String> groupNames = new ArrayList<String>();
chatUser = dbHelper.getChatUser();
groupNames.add("Chats ("+chatUser.size()+")");
groupNames.add("Contacts (" + XMPPConn.mfriendList.size() + ")");
groupNames.add("CGM Groups (" + XMPPConn.mGroupList.size() + ")");
groupNames.add("Pending (1)");
XMPPConn.getGroup();
categoryList = dbHelper.getAllCategory();
/**Group From Sever*/
if (XMPPConn.mGroupList.size() > 0) {
for (int g = 0; g < XMPPConn.mGroupList.size(); g++) {
XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName);
groupNames.add(XMPPConn.mGroupList.get(g).groupName + "("
+ XMPPConn.mGroupContactList.size()+ ")");
}
}
if(categoryList.size() > 0){
for (int cat = 0; cat < categoryList.size(); cat++) {
groupNames.add(categoryList.get(cat).getCategoryName()+ "(0)");
}
}
this.groupNames = groupNames;
/*** ###########CHILD ARRAY * #################*/
ArrayList<ArrayList<ChildItems>> childs = new ArrayList<ArrayList<ChildItems>>();
ArrayList<ChildItems> child = new ArrayList<ChildItems>();
if(chatUser.size() > 0){
for(int i = 0; i < chatUser.size(); i++){
child.add(new ChildItems(userName(chatUser.get(i)), "",0,null));
}
}else{
child.add(new ChildItems("--No History--", "",0,null));
}
childs.add(child);
child = new ArrayList<ChildItems>();
child.add(new ChildItems("", "",0,null));
if (XMPPConn.mfriendList.size() > 0) {
for (int n = 0; n < XMPPConn.mfriendList.size(); n++) {
child.add(new ChildItems(XMPPConn.mfriendList.get(n).friendNickName,
XMPPConn.mfriendList.get(n).friendStatus,
XMPPConn.mfriendList.get(n).friendState,
XMPPConn.mfriendList.get(n).friendPic));
}
}
childs.add(child);
/************** CGM Group Child here *********************/
child = new ArrayList<ChildItems>();
child.add(new ChildItems("", "",0,null));
if (XMPPConn.mGroupList.size() > 0) {
for (int grop = 0; grop < XMPPConn.mGroupList.size(); grop++) {
child.add(new ChildItems(
XMPPConn.mGroupList.get(grop).groupName + " ("
+ XMPPConn.mGroupList.get(grop).groupUserCount
+ ")", "",0,null));
}
}
childs.add(child);
child = new ArrayList<ChildItems>();
child.add(new ChildItems("Shuchi",
"Pending (Waiting for Authorization)",0,null));
childs.add(child);
/************************ Group Contact List *************************/
if (XMPPConn.mGroupList.size() > 0) {
for (int g = 0; g < XMPPConn.mGroupList.size(); g++) {
/** Contact List */
XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName);
child = new ArrayList<ChildItems>();
for (int con = 0; con < XMPPConn.mGroupContactList.size(); con++) {
child.add(new ChildItems(
XMPPConn.mGroupContactList.get(con).friendName,
XMPPConn.mGroupContactList.get(con).friendStatus,0,null));
}
childs.add(child);
}
}
if(categoryList.size() > 0){
for (int cat = 0; cat < categoryList.size(); cat++) {
child = new ArrayList<ChildItems>();
child.add(new ChildItems("-none-", "",0,null));
childs.add(child);
}
}
this.childs = childs;
/** Set Adapter here */
adapter = new UserMenuAdapter(this, groupNames, childs);
setListAdapter(adapter);
object = this;
mlist2 = (ListView) findViewById(R.id.list2);
mimBtnMenu = (ImageButton) findViewById(R.id.imBtnMenu);
mllpopmenu = (LinearLayout) findViewById(R.id.llpopmenu);
mtvUserName = (TextView) findViewById(R.id.tvUserName);
mtvUserTagLine = (TextView) findViewById(R.id.tvUserTagLine);
//Set User name..
System.out.println("CCMStaticVariable.loginUserName==="
+ CCMStaticVariable.loginUserName);
if (!CCMStaticVariable.loginUserName.equalsIgnoreCase("")) {
mtvUserName.setText("" + CCMStaticVariable.loginUserName);
}
/** Expandable List set here.. */
mExpandableListView = (ExpandableListView) this
.findViewById(android.R.id.list);
mExpandableListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
if (parent.isGroupExpanded(groupPosition)) {
commonGroupPosition = 0;
}else{
commonGroupPosition = groupPosition;
}
String GROUP_NAME = groupNames.get(groupPosition);
int end = groupNames.get(groupPosition).indexOf("(");
String GROUP_NAME_VALUE = GROUP_NAME.substring(0, end).trim();
if (menuItemList.contains(GROUP_NAME_VALUE)) {
menuType = false;
CCMStaticVariable.groupCatName = GROUP_NAME_VALUE;
} else {
menuType = true;
CCMStaticVariable.groupCatName = GROUP_NAME_VALUE;
}
long findCatId = dbHelper.getCategoryID(GROUP_NAME_VALUE);
if (findCatId != 0) {
categoryID = (int) findCatId;
}
childValContact="";
//showToast("Clicked on==" + GROUP_NAME_VALUE, 0);
return false;
}
});
/** Click on item */
mlist2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) {
if (commonGroupPosition >= 4) {
if(childValContact == ""){
if (pos == 0) {
showAlertEdit(CCMStaticVariable.groupCatName);
}
/** Move contact to catgory */
if (pos == 1) {
startActivity(new Intent(UserMenuActivity.this,AddContactCategoryActivity.class));
}
}else{
if(pos == 0){
Intent intent = new Intent(UserMenuActivity.this,UserChatActivity.class);
intent.putExtra("userNameVal",childValContact);
startActivity(intent);
}
if(pos == 1){
XMPPConn.removeEntry(childValContact);
showToast("Contact deleted sucessfully", 0);
Intent intent = new Intent(UserMenuActivity.this,UserMenuActivity.class);
}
}
} else {
/** MyProfile */
if (pos == 0) {
startActivity(new Intent(UserMenuActivity.this,
MyProfileActivity.class));
}
/** New multiperson chat start */
if (pos == 1) {
startActivity(new Intent(UserMenuActivity.this,
NewMultipersonChatActivity.class));
}
/** New Broadcast message */
if (pos == 2) {
startActivity(new Intent(UserMenuActivity.this,
NewBroadcastMessageActivity.class));
}
/** Click on add category */
if (pos == 3) {
showAlertAdd();
}
if (pos == 4) {
startActivity(new Intent(UserMenuActivity.this,
CreateGroupActivity.class));
}
if (pos == 5) {
startActivity(new Intent(UserMenuActivity.this,
InvitetoCCMActivity.class));
}
if (pos == 6) {
startActivity(new Intent(UserMenuActivity.this,
SearchActivity.class));
}
if (pos == 7) {
onGroupExpand(2);
for (int i = 0; i < groupNames.size(); i++) {
mExpandableListView.expandGroup(i);
}
}
/** Click on settings */
if (pos == 8) {
startActivity(new Intent(UserMenuActivity.this,
SettingsActivity.class));
}
if (pos == 10) {
System.exit(0);
}
if (pos == 14) {
if (mllpopmenu.getVisibility() == View.VISIBLE) {
mllpopmenu.setVisibility(View.INVISIBLE);
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}
} else {
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(
UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText,
data));
}
}
}
}
});
}
/** Toast message display here.. */
private void showToast(String msg, int time) {
Toast.makeText(this, msg, time).show();
}
/** Show EditAlert Box */
private void showAlertEdit(String msg) {
alert = new AlertDialog.Builder(UserMenuActivity.this);
input = new EditText(UserMenuActivity.this);
input.setSingleLine();
input.setText(msg);
alert.setTitle("Edit Category Name");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
etAlertVal = input.getText().toString();
/** isGroupFromServerOrMobile */
RosterGroup isGroupExists = CCMStaticVariable.CommonConnection
.getRoster().getGroup(CCMStaticVariable.groupCatName);
if (isGroupExists == null) {
dbHelper.updateCategory(categoryID, etAlertVal);
Intent intent = new Intent(UserMenuActivity.this,
UserMenuActivity.class);
startActivity(intent);
showToast("Category updated sucessfully", 0);
} else {
CCMStaticVariable.CommonConnection.getRoster()
.getGroup(CCMStaticVariable.groupCatName)
.setName(etAlertVal);
Intent intent = new Intent(UserMenuActivity.this,
UserMenuActivity.class);
startActivity(intent);
showToast("Category updated sucessfully", 0);
}
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
/** ShowAlertBox Edit */
private void showAlertAdd() {
alert = new AlertDialog.Builder(UserMenuActivity.this);
input = new EditText(UserMenuActivity.this);
input.setSingleLine();
alert.setTitle("New Category Name");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
etAlertVal = input.getText().toString();
if (!etAlertVal.equalsIgnoreCase("request")) {
long lastInsertedId = dbHelper.insertCategory(etAlertVal);
CCMStaticVariable.groupCatName = etAlertVal;
Intent intent = new Intent(UserMenuActivity.this,AddContactCategoryActivity.class);
startActivity(intent);
}
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
public String showSubscriptionStatus(String friend){
return friend;
}
public String userName(String jid){
String username = "";
if(jid.contains("#")){
int index = jid.indexOf("#");
username = jid.substring(0, index);
}else{
username = jid;
}
return username;
}
/**Set expandable handler here..*/
Handler expendableHandle = new Handler(){
public void handleMessage(android.os.Message msg) {
mCustomProgressDialog.dismiss();
setExpandableListView();
};
};
BroadcastReceiver UpdateList = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(UserMenuActivity.this, "CALLED", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
};
}
Please suggest me what is the problem here. I have seen so many posts and have tried a lot of things regarding the same. But It has not worked for me. Please tell me.
Thanks
This
startActivity(new Intent(LoginActivity.this,UserMenuActivity.class));
This
CCMStaticMethod.showAlert(context, "Login",
"Invalid Username or Password. Try Again !", R.drawable.unsuccess,
true, true, "Ok", LoginUnSuccessOkAlertListener, null,
null);
}
and this
mCustomProgressDialog.dismiss();
Do not perform UI events from an async task. Use activity.runOnUiThread() instead.

Categories

Resources