Getting data in intent giving error in only one activity - java

I'm trying to pass an intent from adapter and get it in my activity.
Whenever I did this it went to the else condition.
It doesn't get the value and I don't no why. When I try the same code in any other activity it worked perfectly, but in this activity it always gives a null value in intent.
I know there are so many answers to how to get and pass intent, but in my case it doesn't work in one activity and I don't know why.
My Adapter class:
holder.getSurvey.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AuthorMainScreen.class);
intent.putExtra("work", "getting");
context.startActivity(intent);
}
My AuthorMainScreen Activity:
public class AuthorMainScreen extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Button newSurveyBtn, surveyWithRef, surveyResult;
ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>();
public static TextView textView;
DatabaseReference databaseReference, surveyReference;
String referenceNo, loggedInUserId;
AlertDialog dialog;
ProgressDialog progressDialog;
DrawerLayout drawerLayout;
NavigationView navigationView;
LinearLayout linearLayout;
FirebaseAuth firebaseAuth;
TextView headerEmailView, rateOk;
Button headerLogout;
EditText reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author_navigation);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Processing your request...");
viewDeclaration();
clickFunctionalities();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
//drawerLayout.addDrawerListener(actionBarDrawerToggle);
navigationView.setNavigationItemSelectedListener(this);
}
private void clickFunctionalities() {
newSurveyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
surveyTitleDialog();
}
});
surveyWithRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty()) {
progressDialog.show();
getSurvey();
dialog.dismiss();
} else {
progressDialog.dismiss();
reference.setError("Reference # is required");
}
}
});
}
});
surveyResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty()) {
progressDialog.show();
getSurveyResultFile();
dialog.dismiss();
} else {
progressDialog.dismiss();
reference.setError("Reference # is required");
}
}
});
}
});
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
headerLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(AuthorMainScreen.this, LoginSignupActivity.class);
startActivity(intent);
finish();
}
});
}
private void surveyTitleDialog() {
final AlertDialog.Builder textBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_name_dialog, null);
final EditText surveyName = view.findViewById(R.id.edt_set_survey_name);
TextView ok = view.findViewById(R.id.survey_name_btn);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String surveyTitleName = surveyName.getText().toString().trim();
if (!surveyTitleName.equals("")) {
dialog.dismiss();
Intent intent = new Intent(AuthorMainScreen.this, MakeSurvey.class);
intent.putExtra("surveyname", surveyTitleName);
Toast.makeText(AuthorMainScreen.this, surveyTitleName, Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
surveyName.setError("Title is Required");
}
}
});
TextView cancelBtn = view.findViewById(R.id.dismiss_dialog);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
textBuilder.setView(view);
dialog = textBuilder.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
}
private void getSurvey() {
surveyReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.survey).child(referenceNo);
surveyReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot);
if (dataSnapshot.hasChildren()) {
progressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), GetSurveys.class);
intent.putExtra(Constants.ref_no, referenceNo);
startActivity(intent);
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Reference number is not valid !!!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Something went wrong!!!", Toast.LENGTH_SHORT).show();
}
});
}
public void getSurveyResultFile() {
databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.Answers).child(loggedInUserId).child(referenceNo);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
progressDialog.dismiss();
JSONArray dataSnapshotArray = new JSONArray();
JSONArray dataSnapshotChildrenArray;
JSONObject dataSnapshotChildrenAnswer;
JSONArray dataSnapshotChildrenAnswerValues;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println("sdsd" + ds);
dataSnapshotChildrenArray = new JSONArray();
ArrayList<Object> list = (ArrayList<Object>) ds.getValue();
for (int i = 0; i < list.size(); i++) {
HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
Iterator<Map.Entry<String, Object>> finalIterator = map.entrySet().iterator();
dataSnapshotChildrenAnswer = new JSONObject();
while (finalIterator.hasNext()) {
Map.Entry<String, Object> entry = finalIterator.next();
Object value = entry.getValue();
String key = entry.getKey();
try {
dataSnapshotChildrenAnswer.put(key, value);
if (value instanceof ArrayList) {
dataSnapshotChildrenAnswerValues = new JSONArray();
ArrayList<String> answers = (ArrayList<String>) value;
for (int j = 0; j < answers.size(); j++) {
dataSnapshotChildrenAnswerValues.put(answers.get(j));
}
dataSnapshotChildrenAnswer.put(key, dataSnapshotChildrenAnswerValues);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
dataSnapshotChildrenArray.put(dataSnapshotChildrenAnswer);
}
dataSnapshotArray.put(dataSnapshotChildrenArray);
System.out.println("jso " + dataSnapshotArray);
}
try {
saveCsv(dataSnapshotArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(AuthorMainScreen.this, "Sorry!!user or survey not found.", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
String fileName = referenceNo + " Result";
String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = null;
file = new File(rootPath, fileName);
if (!file.exists()) {
progressDialog.dismiss();
file.createNewFile();
}
if (file.exists()) {
progressDialog.dismiss();
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
for (int i = 0; i < outerArray.length(); i++) {
JSONArray innerJsonArray = (JSONArray) outerArray.getJSONArray(i);
for (int k = 0; k < innerJsonArray.length(); k++) {
String[][] arrayOfArrays = new String[innerJsonArray.length()][];
JSONObject innerJsonObject = (JSONObject) innerJsonArray.getJSONObject(k);
String[] stringArray1 = new String[innerJsonObject.length()];
//stringArray1[0]= (String) innerJsonObject.getString("type");
stringArray1[1] = "Questions";
stringArray1[2] = "Answers";
stringArray1[1] = (String) innerJsonObject.getString("title");
stringArray1[2] = "";
JSONArray jsonArray = (JSONArray) innerJsonObject.getJSONArray("answer");
for (int j = 0; j < jsonArray.length(); j++) {
stringArray1[2] += jsonArray.get(j).toString();
stringArray1[2] += ",";
}
arrayOfArrays[k] = stringArray1;
writer.writeNext(arrayOfArrays[k]);
System.out.println("aa " + Arrays.toString(arrayOfArrays[k]));
}
}
writer.close();
Toast.makeText(this, fileName + " is been saved at " + rootPath, Toast.LENGTH_LONG).show();
}
}
public void referenceDialog() {
final AlertDialog.Builder rateBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_refno_dialog, null);
reference = view.findViewById(R.id.edt_survey_ref_no);
rateOk = view.findViewById(R.id.ref_btnOk);
TextView rateCancel = view.findViewById(R.id.ref_btnCancel);
rateBuilder.setView(view);
rateCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog = rateBuilder.create();
dialog.show();
Window rateWindow = dialog.getWindow();
rateWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
}
private void viewDeclaration() {
newSurveyBtn = findViewById(R.id.new_surveys_button);
surveyWithRef = findViewById(R.id.get_survey_button);
surveyResult = findViewById(R.id.analyze_survey);
linearLayout = findViewById(R.id.hamburg_icon_layout);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
View view = navigationView.getHeaderView(0);
headerEmailView = view.findViewById(R.id.header_email);
headerLogout = findViewById(R.id.nav_logout);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
String userEmail = firebaseAuth.getCurrentUser().getEmail();
headerEmailView.setText(userEmail);
}
if (firebaseAuth.getCurrentUser() != null && firebaseAuth.getCurrentUser().getUid() != null) {
loggedInUserId = firebaseAuth.getCurrentUser().getUid();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "DataPro");
intent.putExtra(Intent.EXTRA_TEXT, Constants.shareMessage);
startActivity(Intent.createChooser(intent, "Share Via"));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_survey_count:
startActivity(new Intent(getApplicationContext(), UserAllSurveys.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_new_instruments:
startActivity(new Intent(getApplicationContext(), CreateInstrument.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_about_us:
Toast.makeText(getApplicationContext(), "About us", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(GravityCompat.START);
break;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
/* if (intent.hasExtra("work") ) {
String k = getIntent().getStringExtra("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "eroor", Toast.LENGTH_SHORT).show();
} */
Bundle bundle = getIntent().getExtras();
if (bundle != null ) {
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}

Try like this
Bundle bundle = getIntent().getExtras();
if (bundle != null ) {
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "error" , Toast.LENGTH_SHORT).show();
}

Do you have another class with the same class name, but different package name?
Because it seems like there is no extra parameter present in your receiver activity (AuthorMainScreen). Sometimes mistakes like this can take more time than any other logical mistake. Or you can try to call it onCreate() by commenting the rest of the code. Just check this.

Related

Android Activity is restarting multiple times in a loop in android studio

Email login activity allows user to log in to his account. here , after the user is logged in , he will be sent to main activity using the main activity intent. here as soon as the user is logged in to the account , he is sent to main activity , and the main activity is restating continously . the screen recording video is uploaded in the link mentioned "https://drive.google.com/file/d/1QRy2J1YkMRJdbjgMIIl-T58DsGnamtGX/view?usp=sharing"
here is the "LOGCAT"
1650989781.030 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.184 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971948, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=9033321453691971949}]
1650989781.193 22200-22200/com.example.indiatalks I/InputTransport: Create ARC handle: 0x7d16279460
1650989781.263 22200-22231/com.example.indiatalks V/FA: Activity resumed, time: 629575044
1650989781.437 22200-22231/com.example.indiatalks V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 264
1650989781.439 22200-22231/com.example.indiatalks V/FA: Activity paused, time: 629575308
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: applied 1 plugins for [com.example.indiatalks]:
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: plugin 1: [libMEOW_gift.so]:
1650989781.687 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.777 22200-22225/com.example.indiatalks I/mple.indiatalk: Waiting for a blocking GC ProfileSaver
1650989781.830 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971949,
public class MainActivity extends AppCompatActivity {
private ImageButton AddNewPostButton, ChatListButton;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private DatabaseReference RootRef, PostsRef;
private ProgressDialog loadingBar;
public ImageButton selectPostButton;
private Button UpdatePostButton, WritePost;
private EditText PostDescription;
private static final int GalleryPick = 100;
private Uri ImageUri;
private String checker = "";
private String Description;
private StorageReference PostsReference;
private DatabaseReference UsersRef;
private String saveCurrentDate, saveCurrentTime, postRandomName, downloadurl, currentUserid, userName;
private Toolbar mToolbar;
private CircleImageView navProfileImage;
private TextView navUserName;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ViewPager myNewsFeedViewpager;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private BottomNavigationView BottomNavMenu;
private RecyclerView postsLists;
private RecyclerView.LayoutManager newsFeedsLinearlayoutManager;
private PostsAdapter postsAdapter;
private final List < Posts > postsArraylist = new ArrayList < > ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
RootRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsReference = FirebaseStorage.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.explore_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Boww Talks");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (currentUser == null) {
SendUserToLoginActivity();
} else {
updateUserStatus("online");
VerifyUserExistence();
}
IntializeControllers();
drawerLayout = (DrawerLayout) findViewById(R.id.drawyer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
navUserName = (TextView) navView.findViewById(R.id.nav_profile_name);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem Item) {
NavMenuSelector(Item);
return false;
}
});
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
return true;
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent MyaddPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(MyaddPostIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_alert)
{
Intent NotificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
overridePendingTransition(0, 0);
startActivity(NotificationIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_profile)
{
Intent MyProfileIntent = new Intent(MainActivity.this, settingsActivity.class);
overridePendingTransition(0, 0);
startActivity(MyProfileIntent);
return true;
}
return false;
}
});
BottomNavMenu.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
Intent MyMainIntent = new Intent(MainActivity.this, MainActivity.class);
overridePendingTransition(0, 0);
startActivity(MyMainIntent);
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent addPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(addPostIntent);
}
if (menuItem.getItemId() == R.id.ic_alert)
{
}
}
});
ChatListButton = (ImageButton) findViewById(R.id.chat_list_button);
ChatListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Intent = new Intent(MainActivity.this, ChatListActivity.class);
startActivity(Intent);
}
});
}
#Override
protected void onRestart() {
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
super.onRestart();
}
private void NavMenuSelector(MenuItem Item) {
switch (Item.getItemId()) {
case R.id.BirthDays:
Toast.makeText(this, "Birthdays selected", Toast.LENGTH_SHORT).show();
break;
case R.id.shortClips:
Toast.makeText(this, "Short Clips selected", Toast.LENGTH_SHORT).show();
break;
case R.id.short_Films:
Toast.makeText(this, "ShortFilms selected", Toast.LENGTH_SHORT).show();
break;
case R.id.marketing:
Toast.makeText(this, "Marketing selected", Toast.LENGTH_SHORT).show();
break;
case R.id.Find_Friends_option:
Toast.makeText(this, "Find Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.my_contacts:
Toast.makeText(this, "My Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.privacy_Settings_option:
Toast.makeText(this, "Privacy Settings selected", Toast.LENGTH_SHORT).show();
break;
case R.id.main_Log_Out_option:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
private void IntializeControllers() {
postsAdapter = new PostsAdapter(postsArraylist);
postsLists = (RecyclerView) findViewById(R.id.news_feeds);
postsLists.setHasFixedSize(true);
newsFeedsLinearlayoutManager = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
postsLists.setLayoutManager(newsFeedsLinearlayoutManager);
postsLists.setAdapter(postsAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
if (currentUser != null) {
updateUserStatus("offline");
}
}
private void updateNewsFeeds() {
PostsRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Posts posts = dataSnapshot.getValue(Posts.class);
postsArraylist.add(posts);
postsAdapter.notifyDataSetChanged();
postsAdapter.notifyDataSetChanged();
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
postsAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateNavMenu() {
currentUserid = currentUser.getUid();
UsersRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
} else {
navUserName.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "Set profile NAVIGATION", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void VerifyUserExistence() {
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
updateNavMenu();
updateNewsFeeds();
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
updateNavMenu();
updateNewsFeeds();
navUserName.setText(retrieveUserName);
} else if ((dataSnapshot.child("name").exists())) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
updateNavMenu();
updateNewsFeeds();
} else {
SendUserTosettingsActivity();
Toast.makeText(MainActivity.this, "Update your profile for settings!!!!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateUserStatus(String state) {
String saveCurrentTime, saveCurrentDate;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
saveCurrentTime = currentTime.format(calendar.getTime());
HashMap < String, Object > onlineStateMap = new HashMap < > ();
onlineStateMap.put("time", saveCurrentTime);
onlineStateMap.put("date", saveCurrentDate);
onlineStateMap.put("state", state);
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).child("userOnlineState")
.updateChildren(onlineStateMap);
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserTosettingsActivity() {
Intent settingsIntent = new Intent(MainActivity.this, settingsActivity.class);
startActivity(settingsIntent);
}
private void SendUserToFIndFriendsActivity() {
Intent findfriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
startActivity(findfriendsIntent);
}
private void SendUserToMyProfileActivity() {
Intent MyProfileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(MyProfileIntent);
}
}
public class emailloginActivity extends AppCompatActivity
{
private EditText UserEmail,UserPassword;
private TextView ForgotPasswordLink;
private Button LoginButton ,NeedNewAccount;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private DatabaseReference UsersRef;
private FirebaseUser currentUser;
public emailloginActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emaillogin);
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = mAuth.getCurrentUser();
LoginButton = (Button) findViewById(R.id.login_button);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AllowUserToLogin();
}
});
InitializeFields();
NeedNewAccount.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SendUserToRegisterActivity();
}
});
}
#Override
protected void onPause() {
if (loadingBar != null) {
loadingBar.dismiss();
}
super.onPause();
}
private void AllowUserToLogin()
{
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if (TextUtils.isEmpty(email))
{
Toast.makeText(this, "Please Enter Email", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Sign in");
loadingBar.setMessage("Please wait........");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
}
{
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
String currentUserId = mAuth.getCurrentUser().getUid();
String deviceToken = FirebaseInstanceId.getInstance().getToken();
UsersRef.child(currentUserId).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
VerifyUserExistence();
Toast.makeText(emailloginActivity.this, "Welcome!!!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(emailloginActivity.this, "Roasted!!!: Check the Email Id and Password", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields()
{
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccount = (Button) findViewById(R.id.Need_new_Account_button);
LoginButton = (Button) findViewById(R.id.login_button);
ForgotPasswordLink = (TextView) findViewById(R.id.Forgot_password);
loadingBar = new ProgressDialog(this);
}
private void VerifyUserExistence ()
{
String userName = mAuth.getCurrentUser().getUid();
UsersRef.child(userName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists())&& (dataSnapshot.hasChild("name"))) {
SendUserToMain();
loadingBar.dismiss();
finish();
}
else
{
SendUserTosettingsActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserTosettingsActivity()
{
Intent mainIntent = new Intent(emailloginActivity.this , settingsActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
finish();
}
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent MainIntent = new Intent(emailloginActivity.this, MainActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
MainIntent.putExtra("mUserID" , userName );
finish();
startActivity(MainIntent);
}
private void SendUserToRegisterActivity()
{
Intent RegisterIntent = new Intent(emailloginActivity.this, RegisterActivity.class);
startActivity(RegisterIntent);
}
}
Mistake is here that you called finish(); before calling startActivity(MainIntent);. Use camelCaseinstade of Capital case in defining variable.
Make changes in your emailloginActivity as below
// changed from MainIntent to mIntent.
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent mIntent = new Intent(emailloginActivity.this, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("mUserID" , userName );
startActivity(mIntent);
finish();
}

Item duplicated in RecyclerView after application call onStart

Every time the application is destroyed and opened again, by another mean every time the method "onStart" is called, every new item added two times.
And when I close it and open it again, every new item will be repeated three times , and so on...
Here is the code of the activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
IntializeControllers();
if (getIntent().getExtras() != null && getIntent().getStringExtra("userID" ) != null&& getIntent().getStringExtra("userName") != null&& getIntent().getStringExtra("userImage") != null){
messageReceiverID = getIntent().getExtras().get("userID").toString();
if (messageReceiverID.equals(auth.getCurrentUser().getUid())){
Toast.makeText(this, "يرجى التأكد من إعدادات تسجيل الدخول", Toast.LENGTH_SHORT).show();
finish();
}
messageReceiverName = getIntent().getExtras().get("userName").toString();
messageReceiverImage = getIntent().getExtras().get("userImage").toString();
}
else {
Toast.makeText(this, "لا يوجد بيانات", Toast.LENGTH_SHORT).show();
finish();
}
DisplayLastSeen();
userName.setText(messageReceiverName);
Picasso.get().load(messageReceiverImage).placeholder(R.drawable.profile_image).into(userImage);
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
MessageInputText.setText("");
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
itemPos =0;
LoadMoreMessages();
}
});
sendFileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Images",
"PDF Files",
"Ms Word Files"
};
AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
builder.setTitle("Select the File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
checker ="image";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"),438);
}if (i == 1){
checker ="pdf";
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select PDF File"),438);
}if (i == 2){
checker ="docx";
Intent intent = new Intent();
intent.setType("application/msword");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Ms Word File"),438);
}
}
});
builder.show();
}
});
seenListener =null;
}
#Override
protected void onStart() {
super.onStart();
LoadMessages();
callImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sheckSelfPermissionsAndCallUser();
}
});
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
}
private void IntializeControllers() {
toolbar = findViewById(R.id.group_chat_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
View actionBarView = layoutInflater.inflate(R.layout.custom_chat_bar, null);
actionBar.setCustomView(actionBarView);
}
auth = FirebaseAuth.getInstance();
messageSenderID = auth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
callImage = findViewById(R.id.custom_user_call);
userImage = findViewById(R.id.custom_profile_image);
userName = findViewById(R.id.custom_profile_name);
userLastSeen = findViewById(R.id.custom_user_last_seen);
SendMessageButton = findViewById(R.id.send_message_btn);
MessageInputText = findViewById(R.id.input_message);
recyclerView = findViewById(R.id.private_messages_list_of_users);
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
sendFileButton = findViewById(R.id.send_files_btn);
progressDialog = new ProgressDialog(ChatActivity.this);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate =currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
saveCurrentTime =currentTime.format(calendar.getTime());
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
sinchClient = Sinch.getSinchClientBuilder()
.context(this)
.applicationKey("b3ecda78-59b0-400e-91bb-53f14fc1efc1")
.applicationSecret("pi0eQwXOzEGP7Crsk8Zepw==")
.environmentHost("clientapi.sinch.com")
.userId(firebaseUser.getUid())
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
callImage.setVisibility(View.VISIBLE);
userLastSeen.setVisibility(View.VISIBLE);
sinchClient.getCallClient().addCallClientListener(new CallClientListener() {
#Override
public void onIncomingCall(CallClient callClient, final com.sinch.android.rtc.calling.Call calli) {
alertDialog = new AlertDialog.Builder(ChatActivity.this).create();
alertDialog.setTitle("وردتك مكالمة من قبل " + messageReceiverName);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "رفض", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
call.hangup();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "قبول", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
call = calli;
call.answer();
call.addCallListener(new sinchCallListenr());
Toast.makeText(ChatActivity.this, "Calling is Start", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
});
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null && data.getData() != null){
progressDialog.setTitle("Sending File");
progressDialog.setMessage("please wait, we are sending that file...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
fileUri = data.getData();
if (!checker.equals("image")){
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Document Files");
final String messageSenderRef = "Messages/" + messageSenderID +"/" + messageReceiverID;
final String messageReceiverRef = "Messages/" + messageReceiverID + "/" +messageSenderID;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID =userMessageKeyRef.getKey();
final StorageReference filePath =storageReference.child(messagePushID +"."+checker);
filePath.putFile(fileUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
myUrl = downloadUrl;
notify = true;
Map messageTextBody = new HashMap();
messageTextBody.put("message",myUrl);
messageTextBody.put("name", Objects.requireNonNull(fileUri.getLastPathSegment()));
messageTextBody.put("type",checker);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("seenMessage",false);
messageTextBody.put("messageID",messagePushID);
messageTextBody.put("time",saveCurrentTime);
messageTextBody.put("date",saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef
+"/" +messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef +"/" +messagePushID,
messageTextBody); RootRef.updateChildren(messageBodyDetails);
progressDialog.dismiss();
if (notify) {
//
sendNotification(messageReceiverID, GetNameUser(), myUrl, checker);
}
notify = false;
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double p = (100.0*taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
progressDialog.setMessage((int) p +" % Uploading....");
}
});
}else if (checker.equals("image")){
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files");
final String messageSenderRef = "Messages/" + messageSenderID +"/" + messageReceiverID;
final String messageReceiverRef = "Messages/" + messageReceiverID + "/" +messageSenderID;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID =userMessageKeyRef.getKey();
final StorageReference filePath =storageReference.child(messagePushID +".jpg");
uploadTask = filePath.putFile(fileUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task){
if (!task.isSuccessful()){
Toast.makeText(ChatActivity.this, ""+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>(){
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
Map messageTextBody = new HashMap();
messageTextBody.put("message",myUrl);
messageTextBody.put("name",fileUri.getLastPathSegment());
messageTextBody.put("type",checker);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("seenMessage",false);
messageTextBody.put("messageID",messagePushID);
messageTextBody.put("time",saveCurrentTime);
messageTextBody.put("date",saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef +"/" +messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef +"/" +messagePushID, messageTextBody);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
notify=true;
//messageAdapter.notifyDataSetChanged();
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, "Message Sent Successfully", Toast.LENGTH_SHORT).show();
if (notify) {
sendNotification(messageReceiverID, GetNameUser(), myUrl, checker);
}
notify = false;
}else {
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, "Error : "+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}else {
Toast.makeText(this, "Nothing Selected, Error.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
}
#Override
protected void onResume() {
Log.d("tester","onResume");
super.onResume();
//move recycler from here
messageAdapter =new MessageAdapter(messagesList,ChatActivity.this,messageReceiverImage);
recyclerView.setAdapter(messageAdapter);
ItemTouchHelper itemTouchHelper = new
ItemTouchHelper(new SwipeToDeleteCallback(messageAdapter));
itemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount());
seenMessage();
UpdateUserStatus("online");
DisplayLastSeen();
messageAdapter.notifyDataSetChanged();
// messagesListAdapter = new MessagesListAdapter(messagesList,messageReceiverImage);
// recyclerView.setAdapter(messagesListAdapter);
}
}
#Override
protected void onStop() {
super.onStop();
Log.d("tester","onStop");
FirebaseUser firebaseUser = auth.getCurrentUser();
if (firebaseUser != null){
UpdateUserStatus("offline");
RootRef.removeEventListener(seenListener);
RootRef.removeEventListener(listener);
}
}
#Override
protected void onDestroy() {
Log.d("tester","onDestroy");
super.onDestroy();
FirebaseUser firebaseUser = auth.getCurrentUser();
if (firebaseUser != null){
UpdateUserStatus("offline");
if (seenListener != null) {
RootRef.removeEventListener(seenListener);
}
}
}
}
I appreciate your help as I can't figure out the problem. Please note that a lot of functions have been removed for readability.
To resolve your issue, clear adap zter while loading new data, so duplicacy can be removed and update new data. This issue occur due to multiple call on Android Lifecycle method in various state like
onResume - Called multiple times. So avoid initalization in here
onStart - is called whenever application is come from background to foreground or visible state
// When adding new data
adapter.addAll(data);
adapter.notifyDataSetChanged();
// when updating data again in onResume or onStart
adapter.clear();// clear old data from list
adapter.addAll(data);
adapter.notifyDataSetChanged();
//Inside adapter
//Adding item
void addAll(List<Data> data){
list.addAll(data);
}
//For clearing list
void clear(){
list.clear();
// To update list automatically add below line
//notifyDataSetChanged();
}

Multiple layout setVisibility wont show correct layout after getting pressed on certain layout

I have a layout in which there are several other layouts by including in XML, I add some textviews as buttons to change the view layouts from one layout to another.
I display each layout with the setVisibility method between layouts, with setOnClickListener in the textview.
The problem is just after finishing displaying the "profile" layout and trying to display the "about us" layout, the system displays a "profile" layout instead of the "about us" layout.
Here is myJava
public class SettingMenu extends AppCompatActivity {
View userProfile, settingLayout, userFavorite, UserEditProfile, aboutUS, contactUS, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
int x = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
settingLayout = findViewById(R.id.SettingLayout);
userProfile = findViewById(R.id.user_profile);
userProfile.setVisibility(View.GONE);
aboutUS = findViewById(R.id.AboutUs);
aboutUS.setVisibility(View.GONE);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (x == 0){
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
else if (x == 1){
x = 0;
UserEditProfile.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 2){
x = 0;
userFavorite.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 3) {
x = 0;
aboutUS.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 4){
x = 0;
settingLayout.setVisibility(View.VISIBLE);
contactUS.setVisibility(View.GONE);
}
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aboutUS.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
AboutUs();
x = x + 3;
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userProfile.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
UserProfile();
x = x + 1;
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
UPDATE
I change my method from setVisibility to setContentView
here's the code. it works fine for me
public class SettingMenu extends AppCompatActivity {
View UserEditProfile, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
ControllerHome();
}
private void ControllerHome() {
setContentView(R.layout.activity_setting);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AboutUs();
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserProfile();
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
setContentView(R.layout.setting_user_profile);
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
setContentView(R.layout.about_us);
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
solved by using setContentView rather than setVisibility.

App is not responding after running this activity

New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()

Call number when click list view item

I have a contact list activity but want to add some functionality so that when you click on a contact it will begin calling their phone number. I have tried this code snippet but nothing happens when I tap on a contact:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + currentContact.getPhone()));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
try{
((Activity) context).startActivity(callIntent);
}catch (Exception e){
e.printStackTrace();
}
All Contact activity code:
public class ContactList extends ActionBarActivity {
Spinner spinner, spinnerFilter;
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
ImageView contactImageimgView, btnSort;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
//Uri imageUri = null;
AlertDialog alertDialog;
Bitmap photoTaken;
String userId;
boolean isReverseEnabledPriority = false, isReverseEnabledName = false;
//ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
userId = user.get("uid");
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
contactListView = (ListView) findViewById(R.id.listView);
contactImageimgView = (ImageView) findViewById(R.id.imgViewContactImage);
spinner = (Spinner) findViewById(R.id.spinner);
spinnerFilter = (Spinner) findViewById(R.id.spinnerFilter);
btnSort = (ImageView) findViewById(R.id.btnSort);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("add contact");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("List");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("contact list");
tabHost.addTab(tabSpec);
getContacts(ContactList.this);
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filter = spinnerFilter.getSelectedItem().toString();
if(filter.equals("Priority")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getPriorityVal().compareTo(v2.getPriorityVal());
}
});
if(isReverseEnabledPriority)
Collections.reverse(Contacts);
isReverseEnabledPriority = !isReverseEnabledPriority;
populateList();
}else if(filter.equals("Name")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getName().compareTo(v2.getName());
}
});
if(isReverseEnabledName)
Collections.reverse(Contacts);
isReverseEnabledName = !isReverseEnabledName;
populateList();
}else{
Toast.makeText(ContactList.this, "Please selectr a method to sort..!", Toast.LENGTH_SHORT).show();
}
}
});
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Contact contact = new Contact(photoTaken, nameTxt.getText().toString(), phoneTxt.getText().toString(), emailTxt.getText().toString(), addressTxt.getText().toString(), spinner.getSelectedItem().toString(), userId);
Contacts.add(contact);
saveContact(contact, ContactList.this);
}
});
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
addBtn.setEnabled(!nameTxt.getText().toString().trim().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageimgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
}
void getContacts(final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Please wait..", false);
}
});
try {
Contacts = ContactsController.getAllContactsOfUser(userId);
populateList();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
}
}.start();
}
void saveContact(final Contact contact, final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
boolean result = false;
int id;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Saving Contact..", false);
}
});
try {
id = ContactsController.saveContact(contact);
if(id > 0){
contact.setId(id);
result = ContactsController.uploadImage(contact);
}
} catch (Exception e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(id == 0){
Toast.makeText(context, "Contact is not saved..!", Toast.LENGTH_SHORT).show();
}
if(!result){
Toast.makeText(context, "Image upload failed..!", Toast.LENGTH_SHORT).show();
}else{
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1) {
Uri imageUri = data.getData();
try {
photoTaken = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
} catch (IOException e) {
e.printStackTrace();
}
contactImageimgView.setImageURI(data.getData());
}
}
}
private void populateList() {
ArrayAdapter<Contact> adapter = new ContactListAdapter();
contactListView.setAdapter(adapter);
}
private class ContactListAdapter extends ArrayAdapter<Contact> {
public ContactListAdapter() {
super(ContactList.this, R.layout.listview_item, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
final Contact currentContact = Contacts.get(position);
try {
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
TextView cPriority = (TextView) view.findViewById(R.id.cPriority);
cPriority.setText(currentContact.getPriority());
ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
if(currentContact.getImage() != null)
ivContactImage.setImageBitmap(currentContact.getImage());
} catch (Exception e) {
e.printStackTrace();
}
ImageView btnDeleteContact = (ImageView) view.findViewById(R.id.btnDeleteContact);
btnDeleteContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(ContactList.this);
builder.setTitle("Confirm Delete");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteContact(currentContact, ContactList.this);
alertDialog.dismiss();
}
});
builder.setNegativeButton("No", null);
alertDialog = builder.create();
alertDialog.show();
}
});
return view;
}
#Override
public int getCount() {
return Contacts.size();
}
void deleteContact( final Contact contact, final Context context){
new Thread(){
Handler handler = new Handler();
ProgressDialog progressDialog;
Boolean result = false;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Deleting Contact..", false);
}
});
try {
result = ContactsController.deleteContact(contact);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(!result){
Toast.makeText(context, "Contact delete failed..!", Toast.LENGTH_SHORT).show();
}else{
Contacts.remove(contact);
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been deleted from your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
}
}
Have you try this code??
Uri number = Uri.parse("tel:123456789");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);

Categories

Resources