Android Progress Bar stops working in the middle - android

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.

Related

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

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.

Stop Timer on return to previous Activity

I have created a timer that starts timing on a handleClick() and continues timing throughout the app. When I return to the firstActivity I would like the timer to stop in the onResume(). however whenever I return to the firstActivity I get the following error below. How do I solve this?
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.warrenedy.julyfinal.TimeTracker2.isTracking()' on a null object reference
Code Below
#Override
protected void onResume() {
super.onResume();
prepareActivityTextsAndButtons();
prepareTimingButtons();
mTimeTracker2.stopTracker();
Toast.makeText(this, "Onresume call", Toast.LENGTH_SHORT).show();
}
public void handleClick(View v) {
if (DBG) Log.d(LOG_TAG, "handleClick()..");
if (!mServiceBound) return;
switch (v.getId()) {
case R.id.button_activity_start_stop:
onActivityButtonClick(v);
break;
}
}
private void onActivityButtonClick(View v) {
if (DBG)
Log.d(LOG_TAG, "onMeditateButtonClick().. tracking " + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (mTimeTracker2.isTracking()) {
if (mCurrentTrackingActivity == null) return;
if (button == mButtonActivityTimers[mCurrentTrackingActivity.ordinal()]) {
mTimeTracker2.stopTracker();
Utils2.playStopAudio(getApplicationContext());
// button.setText(R.string.str_start);
mCurrentTime.setText(Utils2.secToString(0));
button.setChecked(false);
}
}
}
Code Continued
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DBG) Log.d(LOG_TAG, "onCreate()..");
setContentView(R.layout.activity_meditation_tracker);
getSupportActionBar().hide();
mContext = getApplicationContext();
mSharedpreferences = getSharedPreferences(Utils.MyPREFERENCES, Context.MODE_PRIVATE);
exercise_star = sharedpreferences.getInt("exercise_star", 0);
meditation_star = sharedpreferences.getInt("meditation_star", 0);
study_star = sharedpreferences.getInt("study_star", 0);
isAlarmSet = sharedpreferences.getBoolean("isAlarmSet", false);
/* Retrieve a PendingIntent that will perform a broadcast */
mActivity = MeditationTrackerActivity.this;
mButtonSavePoints = (Button) findViewById(R.id.btn_save_points);
mButtonRestorePoints = (Button) findViewById(R.id.btn_restore_points);
btnHelpBut = (Button) findViewById(R.id.btnHelp);
ACTIVITY_NAMES = getResources().getStringArray(R.array.activity_names);
mCurrentTime = (TextView) findViewById(R.id.tv_current_time);
mCurrentTime.setText(Utils2.secToString(0));
if (!isAlarmSet) {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAlarmSet", true);
ed.commit();
startAlarmService();
}
isAuthenticated = sharedpreferences.getBoolean("isAuth", true);
if (Build.VERSION.SDK_INT < 23) {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
insertPermissionWrapper();
}
}
### StartAlarmService
public void startAlarmService() {
Intent alarmIntent = new Intent(MeditationTrackerActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MeditationTrackerActivity.this, 0, alarmIntent, 0);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 23); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 45); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(this, "Main Alarm Set", Toast.LENGTH_SHORT).show();
}
### CancelAlarm
public void cancelAlarmService() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
### StartService
private void startService() {
Intent serIntent = new Intent(this, TimeTrackingService2.class);
startService(serIntent);
bindService(serIntent, mServiceConnection, BIND_AUTO_CREATE);
}
### UpdateCurrentTime
private void updateCurrentTime() {
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
mCurrentTime.setText(sdf.format(date));
}
### ClientAuthenticationFromServer
private void clientAuthenticationFromServer() {
if (Utils2.getConnectivityStatus(mContext)) {
new Auth(mContext, mActivity).execute(Utils2.URL_VALIDATE_CLIENT);
} else {
Utils2.alertPopup(mContext, "You are not connected to internet.kindly connect with internet and try again.The internet is needed only first time for the authentication of client.After authentication no need of internet.", mActivity);
}
}
###Task Complete
#Override
public void onTaskComplete(boolean result) {
if (!result) {
Utils2.alertPopup(mContext, "You are not a valid client.Contact with the owner of the App.", mActivity);
return;
} else {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAuth", true);
ed.commit();
startService();
}
}
### OnStart
#Override
protected void onStart() {
super.onStart();
// updateCurrentTime();
// IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
// registerReceiver(mTimeTickReceiver, filter);
}
###OnStop
#Override
protected void onStop() {
super.onStop();
// unregisterReceiver(mTimeTickReceiver);
}
### onDestroy
#Override
protected void onDestroy() {
super.onDestroy();
if (mServiceBound) {
unbindService(mServiceConnection);
}
}
### onTimeButtonClick
private void onTimeButtonClick(View v) {
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. tracking" + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. checked ? " + button.isChecked());
if (mTimeTracker2.isTracking()) {
showStopToast();
Utils2.playStopAudio(getApplicationContext());
button.setChecked(false);
return;
} else {
Utils2.playStartAudio(getApplicationContext());
if (button.isChecked()) {
if (mCurrentCheckedButton != null) mCurrentCheckedButton.setChecked(false);
int time = (Integer) v.getTag();
mCountDownSecs = time;
mCurrentCheckedButton = button;
} else {
mCountDownSecs = 0;
mCurrentCheckedButton = null;
}
}
}
###ShowStopToast
private void showStopToast() {
Toast.makeText(this, "Please stop running activity..", Toast.LENGTH_SHORT).show();
}
### onTimerProgress
#Override
public void onTimerProgress(int sec, ACTIVITIES activity) {
if (mCurrentTrackingActivity == null) {
mCurrentTrackingActivity = activity;
}
mCurrentTime.setText(Utils2.secToString(sec));
if (activity == ACTIVITIES.STUDY) {
if (sec == 3600) {
mTimeTracker2.stopTracker();
}
}
}
### onTimerFinish
#Override
public void onTimerFinish(int end, ACTIVITIES activity) {
mCurrentTime.setText(Utils2.secToString(end));
mButtonActivityTimers[activity.ordinal()].setChecked(false);
mCurrentTrackingActivity = null;
Utils2.playStopAudio(getApplicationContext());
}
private void prepareActivityTextsAndButtons() {
for (int i = 0; i < ACTIVITY_COUNT; i++) {
View parent = findViewById(ACTIVITY_LAYOUT_IDS[i]);
mTextActivityNames[i] = (TextView) parent.findViewById(R.id.tv_activity_name);
mTextActivityNames[i].setText(ACTIVITY_NAMES[i]);
//mTextActivityTimers[i] = (TextView) parent.findViewById(R.id.tv_timer_progress);
mRatingBars[i] = (RatingBar) parent.findViewById(R.id.ratingBar);
mButtonActivityTimers[i] = (ToggleButton) parent.findViewById(R.id.button_activity_start_stop);
mButtonActivityTimers[i].setText(null);
mButtonActivityTimers[i].setTextOn(null);
mButtonActivityTimers[i].setTextOff(null);
mButtonActivityTimers[i].setTag(ACTIVITIES.values()[i]);
}
}
private void prepareTimingButtons() {
mTimingButtons = new ToggleButton[7];
mTimingButtons[0] = (ToggleButton) findViewById(R.id.button_timer_0);
addTextToTimingButtons(5, mTimingButtons[0]);
}
private void addTextToTimingButtons(int min, Button button) {
// button.setText(min + " " + getString(R.string.str_min));
button.setTag(min * 60);
}
public void onCustomTimeStarted(int secs) {
if (DBG) Log.d(LOG_TAG, "onCustomTimeStarted : secs " + secs);
if (mTimeTracker2.isTracking()) {
showStopToast();
} else {
int oneday = 24 * 3600;
if (secs > oneday) {
Toast.makeText(this, "Adjusted to 24 hrs", Toast.LENGTH_SHORT).show();
secs = oneday;
} else if (secs < 60) {
Toast.makeText(this, "Should be at least a minute.", Toast.LENGTH_SHORT).show();
return;
}
mTimingButtons[6].setChecked(true);
mTimingButtons[6].setTag(secs);
onTimeButtonClick(mTimingButtons[6]);
//mTimeTracker2.startTracker(secs, this);
//mButtonMeditate.setText(R.string.meditate_stop);
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
}
return true;
}
private void insertPermissionWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add("READ_PHONE_STATE");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
return;
} else {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
}
// insertDummyContact();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.app.AlertDialog.Builder(MeditationTrackerActivity.this)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
) {
// All Permissions Granted
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
// Permission Denied
Toast.makeText(MeditationTrackerActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void setBootReceiverEnabled(int componentEnabledState) {
ComponentName componentName = new ComponentName(this, DeviceBootReceiver.class);
PackageManager packageManager = getPackageManager();
packageManager.setComponentEnabledSetting(componentName,
componentEnabledState,
PackageManager.DONT_KILL_APP);
};
TimeTracker2.class
public class TimeTracker2 {
private static final int MSG_TRACKER_STOPPED = 1;
private static final int MSG_TRACKER_PROGRESS_UPDATE = 2;
private Context mContext;
private boolean mIsTrackingInProgress;
private TrackerServiceCallback mServiceCallback;
private TimerProgressCallback2 mProgressCallback;
private Timer mTimer = new Timer();
private TimerHandler mTimerHandler = new TimerHandler();
private TimerTask mIncrementTask, mDecrementTask;
private int mCounter;
private int mMaxCounter;
private MeditationTrackerActivity.ACTIVITIES mCurrentTrackingActivity;
private class IncrementTask extends TimerTask {
IncrementTask() {
mCounter = 0;
}
#Override
public void run() {
mCounter++;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
private class DecrementTask extends TimerTask {
DecrementTask(int sec) {
mCounter = sec;
}
#Override
public void run() {
if (mCounter == 0) {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_PIP, 500);
cancel();
mTimerHandler.sendEmptyMessage(MSG_TRACKER_STOPPED);
return;
}
mCounter --;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
public interface TimerProgressCallback2 {
void onTimerProgress(int sec, MeditationTrackerActivity.ACTIVITIES activity);
void onTimerFinish(int end, MeditationTrackerActivity.ACTIVITIES activity);
}
public TimeTracker2(Context context, TrackerServiceCallback serviceCallback) {
mContext = context;
mServiceCallback = serviceCallback;
}
public void startTracker(int time_secs, TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = time_secs;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mDecrementTask = new DecrementTask(time_secs);
mTimer.scheduleAtFixedRate(mDecrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void startTracker(TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = 0;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mIncrementTask = new IncrementTask();
mTimer.scheduleAtFixedRate(mIncrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void setTimerProgressCallback(TimerProgressCallback2 callback) {
if (!mIsTrackingInProgress) return;
mProgressCallback = callback;
}
public void removeTimerProgressCallback() {
mProgressCallback = null;
}
public void stopTracker() {
if (!mIsTrackingInProgress) {
Log.i(LOG_TAG, "stopTracker().. Tracker NOT started!!");
return;
}
mIsTrackingInProgress = false;
mServiceCallback.onTrackerStarted(false);
if (mProgressCallback != null) mProgressCallback.onTimerFinish(mCounter, mCurrentTrackingActivity);
mProgressCallback = null;
if (mIncrementTask != null) mIncrementTask.cancel();
if (mDecrementTask != null) mDecrementTask.cancel();
updateDb();
mCurrentTrackingActivity = null;
}
public boolean isTracking() {
return mIsTrackingInProgress;
}
public MeditationTrackerActivity.ACTIVITIES getCurrentTrackingActivity() {
return mCurrentTrackingActivity;
}
private class TimerHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if (DBG) Log.d(LOG_TAG, "handleMessage()..");
switch (msg.what) {
case MSG_TRACKER_PROGRESS_UPDATE:
if (mProgressCallback != null) mProgressCallback.onTimerProgress(mCounter, mCurrentTrackingActivity);
break;
case MSG_TRACKER_STOPPED:
default:
stopTracker();
break;
}
}
}
private void updateDb() {
final int secs = mMaxCounter > 0 ? mMaxCounter - mCounter : mCounter;
final MeditationTrackerActivity.ACTIVITIES activity = mCurrentTrackingActivity;
AsyncTask.execute(new Runnable() {
#Override
public void run() {
TrackerDb3.insertOrUpdateMeditation(mContext, secs, activity);
}
});
}
}

Trouble expanding image in samsung s8

As screen height of samsung s8 is quite large.My images in LoginUI(attached) were looking small.I calculated phone's height in dp programmatically.
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
Log.d("checkheightdp",dpHeight+"");
It gave me dpheight 692.So,I create a separate layout-h692dp and put my layout with increased image height.For some reason,It is still picking the default layout and hence image not expanding.
My code:
public class LoginActivity extends AppCompatActivity {
private EditText email, psd;
public ImageView deleteEmail;
public ImageView deletePsd;
public ImageView contactUs;
GlobalProvider globalProvider;
private int a = 0;
private Button sign_in_button, tourist_in_button;
private List<String> history = new ArrayList<String>();
private String usernameStr, newVersion = "x";
public static String character = "character";
private ConnectivityManager mConnectivityManager;
private NetworkInfo netInfo;
private ProgressDialog dialog;
public Thread thread;
private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo == null) {
Toast.makeText(LoginActivity.this, "网络链接不可用!", Toast.LENGTH_SHORT).show();
}
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
globalProvider = GlobalProvider.getInstance(LoginActivity.this);
IntentFilter mFilter = new IntentFilter();
mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(myNetReceiver, mFilter);
//找到对象email、psd、sign_in_button并绑定监听事件
email = (EditText) findViewById(R.id.email);
psd = (EditText) findViewById(R.id.psd);
contactUs = (ImageView) findViewById(R.id.contact_us);
sign_in_button = (Button) findViewById(R.id.sign_in_button);
tourist_in_button = (Button) findViewById(R.id.tourist_in_button);
deleteEmail = (ImageView) findViewById(R.id.deleteEmail);
deletePsd = (ImageView) findViewById(R.id.deletePsd);
// gview=(GridView) findViewById(R.id.grid_layout);
// ImageAdapter imgAdapter=new ImageAdapter(LoginActivity.this);
//gview.setAdapter(imgAdapter);
contactUs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, ContactActivity.class);
startActivity(intent);
}
});
deleteEmail.setVisibility(View.GONE);
deletePsd.setVisibility(View.GONE);
try {
findHistoryList();
} catch (IOException e) {
e.printStackTrace();
}
email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
deleteEmail.setVisibility(View.VISIBLE);
} else {
deleteEmail.setVisibility(View.GONE);
}
}
});
psd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
deletePsd.setVisibility(View.VISIBLE);
} else {
deletePsd.setVisibility(View.GONE);
}
}
});
deleteEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
email.setText("");
}
});
deletePsd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
psd.setText("");
}
});
sign_in_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (email.getText() == null || email.getText().toString().equals("") || psd.getText() == null || email.getText().toString().equals("")) {
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.notempty))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
} else {
try {
setHistoryList();
} catch (IOException e) {
e.printStackTrace();
}
dialog = new ProgressDialog(LoginActivity.this);
dialog.setMessage(getString(R.string.loging));
dialog.show();
sign_in_button.setEnabled(false);
loginAction(v);
}
}
});
//为sign_in_button绑定监听事件,调用loginAction(v)
tourist_in_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = new ProgressDialog(LoginActivity.this);
dialog.setMessage(getString(R.string.loging));
dialog.show();
sign_in_button.setEnabled(false);
loginActionTourist(v);
}
});
}
public static void setCharacter(Context context, String cha) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString(character, cha);
editor.commit();
}
public static String getToken(Context context) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
String cha = settings.getString(character, ""/*default value is ""*/);
//Log.v("err", tokenStr);
return cha;
}
//创建loginAction()方法
public void loginAction(View view) {
//分别把email、psd的值传递给usernameStr、passwordStr
final String usernameStr = email.getText().toString();
String passwordStr = psd.getText().toString();
Log.d("checkentries",usernameStr+" "+passwordStr);
setCharacter(this, "user");
// Log.d("chkpassword",passwordStr);
//GlobalProvider.getInstance().character =
Map<String, String> params = new HashMap<>();
params.put("password", passwordStr);
params.put("email",usernameStr );
CustomRequest jsonObjectRequest = new CustomRequest(Request.Method.POST, loginUrlStr, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("responsevolley", response.getString("token"));
dialog.dismiss();
globalProvider.IsLoging = true;
sign_in_button.setEnabled(true);
String token;
token = response.getString("token");
token = token.replaceAll("\"", "");//把token中的"\""全部替换成""
Constants.setToken(LoginActivity.this, token);
globalProvider.isLogined=true;
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("isLogin", usernameStr);
startActivity(intent);
//this.setResult(Activity.RESULT_OK);//为结果绑定Activity.RESULT_OK
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("errorvolley", error.toString());
dialog.dismiss();
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.errorId))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
sign_in_button.setEnabled(true);
}
});
globalProvider.addRequest(jsonObjectRequest);
}
public void loginActionTourist(View view) {
usernameStr = "guest#veg.com";
String passwordStr = "12345678";
setCharacter(this, "tourist");
globalProvider.isLogined = true;
// GlobalProvider.getInstance().character = "tourist";
// 绑定参数
Map<String,String> params = new HashMap();
params.put("email", usernameStr);
params.put("password", passwordStr);
CustomRequest customRequest=new CustomRequest(Request.Method.POST, loginUrlStr, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.dismiss();
globalProvider.IsLoging = true;
tourist_in_button.setEnabled(true);
String token;
try {
token = response.getString("token");
token = token.replaceAll("\"", "");
Constants.setToken(LoginActivity.this, token);
} catch (JSONException e) {
e.printStackTrace();
}
//把token中的"\""全部替换成""
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("isLogin", usernameStr);
startActivity(intent);
//this.setResult(Activity.RESULT_OK);//为结果绑定Activity.RESULT_OK
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.errorId))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
tourist_in_button.setEnabled(true);
}
});
}
private void findHistoryList() throws IOException {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/EasybuyCustomer.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
history.add(s);
//System.out.println(arrs[0] + " : " + arrs[1] + " : " + arrs[2]);
}
if (history.size() > 0) {
email.setText(history.get(0));
psd.setText(history.get(1));
}
br.close();
isr.close();
fis.close();
}
public void setHistoryList() throws IOException {
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/EasybuyCustomer.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("");
bw.write(email.getText().toString());
bw.newLine();
bw.write(psd.getText().toString());
bw.newLine();
bw.close();
osw.close();
fos.close();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
hideSoftInput(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
private boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = { 0, 0 };
v.getLocationInWindow(l);
int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
+ v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
return false;
} else {
return true;
}
}
return false;
}
private void hideSoftInput(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//按下键盘上返回按钮
if(keyCode == KeyEvent.KEYCODE_BACK){
new AlertDialog.Builder(this)
.setMessage(getString(R.string.youconfirmtologout))
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
a=a+1;
finish();
}
}).show();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(myNetReceiver);
if(a>0){
System.exit(0);
}
a=0;
}
}
Finally I got my answer,why creating a separate height layout was not working.
Though screen height of samsung s8 is 692 dp,but 25dp is not available as It is used by system UI.
Apparently it was stated in developer.android.com.
The Android system might use some of the screen for system UI (such as the system bar at the bottom of the screen or the status bar at the top), so some of the screen might not be available for your layout.
Therefore,subtracting 25 dp from 692 gives 667dp.Creating layout-h667dp worked.
I went to this post.
https://medium.com/#elye.project/an-important-note-when-managing-different-screen-height-3140e26e381a

Android contact picker returning nulll (resultCode == 0)

I'm new to Android and I'm trying to attach a contact picker to a form. This "contact picker code" works well when I test it with other forms but with this form, the resultCode = RESULT_CANCELED. I have checked other examples, but it doesn't work with this from but still works with other forms.
public class EmergencyButtonActivity extends Activity {
static private MoreEditText mPhonesMoreEditText = null;
private static final String DEBUG_TAG = "EmergencyButtonActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, new StackMailer());
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first phone
if (cursor.moveToFirst()) {
phone = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtPhoneNo.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Phone : "+ phone, Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
private void popup(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyButtonActivity.this);
builder.setMessage(text)
.setTitle(title)
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void initUI() {
setContentView(R.layout.main);
this.restoreTextEdits();
ImageButton btnEmergency = (ImageButton) findViewById(R.id.btnEmergency);
btnEmergency.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// try sending the message:
EmergencyButtonActivity.this.redButtonPressed();
}
});
ImageButton btnHelp = (ImageButton) findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupHelp();
}
});
}
public void popupHelp() {
final String messages [] = {
"Welcome To App xxxxxx",
"XXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXX."
};
// inverted order - They all popup and you hit "ok" to see the next one.
popup("3/3", messages[2]);
popup("2/3", messages[1]);
popup("1/3", messages[0]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
initUI();
}
private class StackMailer implements ExceptionHandler.StackTraceHandler {
public void onStackTrace(String stackTrace) {
EmailSender.send("a#zzz.com", "Error", "ButtonError\n" + stackTrace);
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
initUI();
//IntroActivity.openOnceAfterInstallation(this);
helpOnceAfterInstallation();
}
#Override
protected void onPause() {
super.onPause();
this.saveTextEdits();
}
#Override
protected void onStop() {
super.onStop();
}
public void helpOnceAfterInstallation() {
// runs only on the first time opening
final String wasOpenedName = "wasOpened";
final String introDbName = "introActivityState";
SharedPreferences settings = this.getSharedPreferences(introDbName, Context.MODE_PRIVATE);
boolean wasOpened = settings.getBoolean(wasOpenedName, false);
if (wasOpened) {
return;
}
// mark that it was opened once
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(wasOpenedName, true);
editor.commit();
popupHelp();
}
private class EditTextRow {
LinearLayout mLinlay;
EditText mEditText;
ImageButton mRemoveBtn;
public EditTextRow(String text, EditText example) {
mEditText = new EditText(EmergencyButtonActivity.this);
mEditText.setLayoutParams(example.getLayoutParams());
mEditText.setText(text);
mEditText.setInputType(example.getInputType());
mRemoveBtn = new ImageButton(EmergencyButtonActivity.this);
mRemoveBtn.setBackgroundResource(R.drawable.grey_x);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mRemoveBtn.setLayoutParams(params);
mLinlay = new LinearLayout(EmergencyButtonActivity.this);
mLinlay.setOrientation(LinearLayout.HORIZONTAL);
mLinlay.addView(mEditText);
mLinlay.addView(mRemoveBtn);
}
}
private class MoreEditText {
private LinearLayout mContainer;
private ArrayList<EditText> mEditTextList = null;
public MoreEditText(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from scratch, this should only happen onCreate
mContainer = container;
mEditTextList = new ArrayList<EditText>();
EditText edit;
edit = textWidget;
if(! stringsList.isEmpty()) {
edit.setText(stringsList.get(0));
}
mEditTextList.add(edit);
for (int i = 1; i < stringsList.size(); i++) {
addRow(stringsList.get(i));
}
}
public void restore(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from older existing rows, this can happen on
// changes of orientation, onResume, etc
mContainer = container;
for(int i = 0; i < mEditTextList.size(); i++) {
EditText edit;
if (i == 0) {
edit = textWidget;
mEditTextList.set(0, edit);
if (stringsList.size() > 0) {
edit.setText(stringsList.get(0));
}
} else {
edit = mEditTextList.get(i);
View viewRow = (LinearLayout) edit.getParent();
((LinearLayout)viewRow.getParent()).removeView(viewRow);
mContainer.addView(viewRow);
}
}
}
#SuppressWarnings("unused")
public EditText getDefaultTextEdit(LinearLayout container) {
// TODO: turn this into something like "getEditTextChild" rather than counting on the index "0"
return (EditText) ((LinearLayout)container.getChildAt(0)).getChildAt(0);
}
public void removeRow(EditText editText) {
mContainer.removeView((View) editText.getParent());
mEditTextList.remove(editText);
}
public void addRow(String text) {
final EditTextRow editRow = new EditTextRow(text, mEditTextList.get(0));
editRow.mRemoveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MoreEditText.this.removeRow(editRow.mEditText);
}
});
mContainer.addView(editRow.mLinlay);
mEditTextList.add(editRow.mEditText);
}
public List<String> GetTexts() {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < mEditTextList.size(); i ++) {
texts.add(mEditTextList.get(i).getText().toString());
}
return texts;
}
}
private void addPhonesEmailsUI(List<String> phones, List<String> emails) {
LinearLayout phoneNoLin = (LinearLayout)findViewById(R.id.linPhoneNo);
EditText txtPhoneNo = (EditText)findViewById(R.id.txtPhoneNo);
// NOTE: we don't always create from scratch so that empty textboxes
// aren't erased on changes of orientation.
if (mPhonesMoreEditText == null) {
mPhonesMoreEditText = new MoreEditText(phoneNoLin, txtPhoneNo, phones);
} else {
mPhonesMoreEditText.restore(phoneNoLin, txtPhoneNo, phones);
}
}
public void restoreTextEdits() {
EmergencyData emergencyData = new EmergencyData(this);
addPhonesEmailsUI(emergencyData.getPhones(), emergencyData.getEmails());
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(emergencyData.getMessage());
}
#SuppressWarnings("unused")
public void saveTextEdits() {
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
EmergencyData emergencyData = new EmergencyData(this);
emergencyData.setPhones(mPhonesMoreEditText.GetTexts());
emergencyData.setMessage(txtMessage.getText().toString());
}
public void redButtonPressed() {
this.saveTextEdits();
EmergencyData emergency = new EmergencyData(this);
if ((emergency.getPhones().size() == 0) && (emergency.getEmails().size() == 0)) {
Toast.makeText(this, "Enter a phone number or email.",
Toast.LENGTH_SHORT).show();
return;
}
EmergencyActivity.armEmergencyActivity(this);
Intent myIntent = new Intent(EmergencyButtonActivity.this, EmergencyActivity.class);
EmergencyButtonActivity.this.startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ebutton_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(Intent.ACTION_VIEW);
switch (item.getItemId()) {
case R.id.project_page:
i.setData(Uri.parse("http://#/"));
startActivity(i);
break;
case R.id.credits:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.credits_dialog);
dialog.setTitle("Credits");
TextView text = (TextView) dialog.findViewById(R.id.textView);
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.credits);
byte[] b = new byte[in_s.available()];
in_s.read(b);
text.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
text.setText("Error: can't show credits.");
}
dialog.show();
break;
}
return true;
}
}
Finally found a solution, the problem was with the android:launchMode in the manifest.

randomly output quiz questions from xml file using array

This is my code for questions, my problem is that i cannot create a code to randomly output a question from xml without any duplication,
Here's my code:
public class QuizFunActivity extends Activity{
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(3*1000);
finish();
loadQuestions();
Intent intent = new Intent(QuizFunActivity.this, QuestionActivity.class);
QuizFunActivity.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
}
can you give me a sample of which part on my code should i create a code for random output?
thanks for the help!
you may take a look with this activity,
public class QuestionActivity extends Activity {
/** Called when the activity is first created. */
EditText question = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioButton answer4 = null;
RadioGroup answers = null;
Button finish = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review =false;
Button prev, next = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
TableLayout quizLayout = (TableLayout) findViewById(R.id.quizLayout);
quizLayout.setVisibility(android.view.View.INVISIBLE);
try {
question = (EditText) findViewById(R.id.question1);
answer1 = (RadioButton) findViewById(R.id.a0);
answer2 = (RadioButton) findViewById(R.id.a1);
answer3 = (RadioButton) findViewById(R.id.a2);
answer4 = (RadioButton) findViewById(R.id.a3);
answers = (RadioGroup) findViewById(R.id.answers);
RadioGroup questionLayout = (RadioGroup)findViewById(R.id.answers);
Button finish = (Button)findViewById(R.id.finish);
finish.setOnClickListener(finishListener);
prev = (Button)findViewById(R.id.Prev);
prev.setOnClickListener(prevListener);
next = (Button)findViewById(R.id.Next);
next.setOnClickListener(nextListener);
selected = new int[QuizFunActivity.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[QuizFunActivity.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0,review);
quizLayout.setVisibility(android.view.View.VISIBLE);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex,boolean review) {
try {
JSONObject aQues = QuizFunActivity.getQuesList().getJSONObject(qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.WHITE);
answer2.setTextColor(Color.WHITE);
answer3.setTextColor(Color.WHITE);
answer4.setTextColor(Color.WHITE);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(3).getString("Answer");
answer4.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("",selected[qIndex]+"");
if (selected[qIndex] == 0)
answers.check(R.id.a0);
if (selected[qIndex] == 1)
answers.check(R.id.a1);
if (selected[qIndex] == 2)
answers.check(R.id.a2);
if (selected[qIndex] == 3)
answers.check(R.id.a3);
setScoreTitle();
if (quesIndex == (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(false);
if (quesIndex == 0)
prev.setEnabled(false);
if (quesIndex > 0)
prev.setEnabled(true);
if (quesIndex < (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(true);
if (review) {
Log.d("review",selected[qIndex]+""+correctAns[qIndex]);;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
if (selected[qIndex] == 3)
answer4.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 3)
answer4.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private OnClickListener finishListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
//Calculate Score
int score = 0;
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
score++;
}
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(QuestionActivity.this).create();
alertDialog.setTitle("Score");
alertDialog.setMessage((score) +" out of " + (QuizFunActivity.getQuesList().length()));
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Retake", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
quesIndex=0;
QuestionActivity.this.showQuestion(0, review);
}
});
/* alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Review", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = true;
quesIndex=0;
QuestionActivity.this.showQuestion(0, review);
}
}); */
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"Quit", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
Intent instructionsIntent = new Intent(QuestionActivity.this,MainBookActivity.class);
startActivity(instructionsIntent);
finish();
}
});
alertDialog.show();
}
};
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
if (answer4.isChecked())
selected[quesIndex] = 3;
Log.d("",Arrays.toString(selected));
Log.d("",Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex++;
if (quesIndex >= QuizFunActivity.getQuesList().length())
quesIndex = QuizFunActivity.getQuesList().length() - 1;
showQuestion(quesIndex,review);
}
};
private OnClickListener prevListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex--;
if (quesIndex < 0)
quesIndex = 0;
showQuestion(quesIndex,review);
}
};
private void setScoreTitle() {
this.setTitle("SciQuiz3 " + (quesIndex+1)+ "/" + QuizFunActivity.getQuesList().length());
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
}
Thanks!

Categories

Resources