App is not responding after running this activity - java

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()

Related

Getting data in intent giving error in only one activity

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.

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.

CountDownTimer is not stopping on BackPressed running in background,may be handler.postDelayed() is the issue. How to fix it in this code?

My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}

If RecyclerView scrolls, then item id changes. How to resolve this?

This is my PDFListAdapter class method. I have downloaded file locally and save on Sqlite database. But if I scroll my RecyclerView, then I am having different item id. If not scroll RecyclerView then item id is perfect.
The problem is when I scroll down the RecyclerView the item id changes. That is, I can fit one item on the screen at once. When I scroll to the second item, it saves different file and opens different.
public class PDFListAdapter extends RecyclerView.Adapter<PDFListAdapter.MyViewHolder> {
private ArrayList<NotesResponseInfo> pdfModelClasses;
Context context;
static NotesResponseInfo pdfList;
String final_nav_opt_name;
ProgressDialog progressDialog;
String TAG = "PDFListAdapter";
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
int id = 1;
DatabaseNotes databaseNotes;
MyViewHolder holder;
Downloader downloader;
int deepak =0 ;
public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
this.context = context;
this.pdfModelClasses = pdfModelClasses;
this.final_nav_opt_name = final_nav_opt_name;
databaseNotes = new DatabaseNotes(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
LinearLayout layout_open_pdf, layout_download_note_option;
ImageView imgDownloadNote, imgCancelDownloadNote;
ProgressBar progress_download_note;
public MyViewHolder(View view) {
super(view);
txtBookName = (TextView) view.findViewById(R.id.txtBookName);
txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
txtDownload = view.findViewById(R.id.txtDownload);
layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder1, final int index) {
final int position = index;
pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder1.txtDownload.setVisibility(View.VISIBLE);
holder1.layout_download_note_option.setVisibility(View.GONE);
} else {
holder1.txtDownload.setVisibility(View.GONE);
holder1.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfList = pdfModelClasses.get(position);
holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
alertDialog.show();
}
}
});
holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
deepak =index ;
holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
}
} else {
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
}
else Log.e("","Not in db");
}
});
holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
private void startSave(final Context context, NotesResponseInfo url) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
final base_url b = new base_url();
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
Retrofit retrofit = builder.client(httpClient.build()).build();
AllApis downloadService = retrofit.create(AllApis.class);
Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
downloader.execute(response.body());
} else {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
mNotifyManager.cancelAll();
}
#Override
protected Integer doInBackground(ResponseBody... params) {
NotesResponseInfo item = new NotesResponseInfo();
item = pdfModelClasses.get(deepak);
ResponseBody body = params[0];
try {
URL url = new URL(pdfList.getFileName());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("Accept-Encoding", "identity");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
int lenghtOfFile = c.getContentLength();
Log.w("getContentLength",""+lenghtOfFile);
File file = wrapper.getDir("PDF", MODE_PRIVATE);
file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
FileOutputStream f = new FileOutputStream(file);
InputStream in = c.getInputStream();
float finalValue = 0;
byte[] buffer = new byte[100 * 1024];
int len1 = 0;
int progress = 0;
long total = 0;
if (!(isCancelled())) {
while ((len1 = in.read(buffer)) >0) {
if (UtilsMethods.isNetworkAvailable(context)) {
f.write(buffer, 0, len1);
total += len1;
setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));
/* progress += len1;finalValue = (float) progress/body.contentLength() *100;
setProgress((int) finalValue);
mBuilder.setProgress((int) finalValue,0,false);*/
} else {
File file1 = new File(file.getPath());
file1.delete();
cancel(true);
}
}
new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
} else {
File file1 = new File(file.getPath());
file1.delete();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
mBuilder.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, 100, false);
mNotifyManager.notify(id, mBuilder.build());
holder.txtDownload.setVisibility(View.VISIBLE);
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
}
private void setProgress(int progress) {
mBuilder.setContentText("Downloading...")
.setContentTitle(progress + "%")
.setSmallIcon(R.mipmap.ic_logo)
.setOngoing(true)
.setContentInfo(progress + "%")
.setProgress(100, progress, false);
mNotifyManager.notify(id, mBuilder.build());
holder.progress_download_note.setProgress(progress);
}
}
public class CheckSpace extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String file_size = "";
URL url = null;
try {
url = new URL(params[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
file_size = UtilsMethods.generateFileSize(fileSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file_size;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onPostExecute(String result) {
if (UtilsMethods.compareSpace(result)) {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Download this PDF of size " + result + " ?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder.progress_download_note.setVisibility(View.VISIBLE);
startSave(context, pdfList);
}
});
alertDialog.show();
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Unable to download file. Storage space is not available");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
}
});
alertDialog.show();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
I have modified your onBindViewHolder function. The changes are following.
Declared the pdfList variable as final and used it everywhere. It is not necessary to get the pdfList from the pdfModelClasses, each time you use it.
The holder variable is removed, as it is not actually necessary. The holder1 is used everywhere.
There are some changes with the visibility of the buttons. Check holder1.imgDownloadNote.setOnClickListener.
I have found no other problem in your onBindViewHolder. Please let me know if the modified code works.
#Override
public void onBindViewHolder(final MyViewHolder holder1, final int index) {
final int position = index;
// Declare the variable here and make it final.
final PDFList pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder1.txtDownload.setVisibility(View.VISIBLE);
holder1.layout_download_note_option.setVisibility(View.GONE);
} else {
holder1.txtDownload.setVisibility(View.GONE);
holder1.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I have the desired pdfList already, no need to get that again.
// pdfList = pdfModelClasses.get(position);
// Assigning to holder is not necessary.
// holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
alertDialog.show();
}
}
});
holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
deepak =index ;
// We don't need the reassignment.
// holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
// Make them visible when the internet connection is there.
holder1.imgDownloadNote.setVisibility(View.VISIBLE);
holder1.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder1.progress_download_note.setVisibility(View.VISIBLE);
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
}
} else {
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
} else {
// Put proper visibility everywhere.
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
Log.e("","Not in db");
}
}
});
holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position) {
return position;
}

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