Call number when click list view item - java

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

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.

Scanning for bluetooth devices programmatically don't find anything in android 6+

I created an application which pairs a cellphone to a bluetooth module.
i tested this application with a 4.2 android cellphone and it worked quite well but in cellphones with android higher than 6 the device is not fidning anything when i press " Scan for new devices " button.
but when i go through my phone bluetooth itself, i can find the module i was looking for..
Bluetooth connection class :
public class BluetoothConnectionActivity extends AppCompatActivity {
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
BluetoothDevice device ;
private MediaPlayer mediaplayer = null ;
private Button bluetoothOnOff;
private Button viewpairedDevices;
private Button scanfornewDevices;
private Button blue2;
ImageView unMute;
View view1;
View view2;
private Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetoothconnectionlayout);
bluetoothOnOff = (Button) findViewById(R.id.bluetoothOnOff);
viewpairedDevices = (Button) findViewById(R.id.viewpairedDevicesButton);
scanfornewDevices = (Button) findViewById(R.id.scanfornewDevicesButton);
blue2 = (Button) findViewById(R.id.bluetoothOnOff2);
view1 = findViewById(R.id.viewFader);
view2 = findViewById(R.id.viewFader2);
unMute = (ImageView) findViewById(R.id.settingStartupSecondary);
mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.sfxturnon);
Handler startup1 = new Handler();
startup1.postDelayed(new Runnable() {
#Override
public void run() {
view1.animate().alpha(1f).setDuration(500);
view2.animate().alpha(1f).setDuration(500);
}
},1000);
Handler startup2 = new Handler();
startup2.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(500);
viewpairedDevices.animate().alpha(1f).setDuration(500);
scanfornewDevices.animate().alpha(1f).setDuration(500);
unMute.animate().alpha(1f).setDuration(100);
}
},1000);
//
// settingBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
//
// AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
// amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
//
//// settingBtn.setEnabled(false);
//// settingBtn.animate().alpha(0f);
//
// unMute.animate().alpha(1f);
// unMute.setEnabled(true);
//
//
// Toast.makeText(getApplicationContext(), " Application muted. ", Toast.LENGTH_SHORT).show();
//
//
// }
// });
Handler dawg = new Handler();
dawg.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(1500);
viewpairedDevices.animate().alpha(1f).setDuration(2500);
scanfornewDevices.animate().alpha(1f).setDuration(3000);
}
},500);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning, Please wait...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});}
if (mBluetoothAdapter.isEnabled()){
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
}else {
blue2.setText("Bluetooth is Off");
bluetoothOnOff.setText("Bluetooth is Off");
}
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
viewpairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
Toast toast = Toast.makeText(getApplicationContext()," No paired device found.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
scanfornewDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
bluetoothOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
blue2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onBackPressed() {
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(true);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(true);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showDisabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showUnsupported() {
Toast toast = Toast.makeText(getApplicationContext()," Bluetooth is not supported by this device.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
bluetoothOnOff.setEnabled(false);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
showEnabled();
final Handler handler5 = new Handler();
handler5.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(150f).setDuration(5000);
blue2.animate().translationY(150f).setDuration(5000);
bluetoothOnOff.animate().alpha(0f).setDuration(3000);
blue2.animate().alpha(1f).setDuration(3000);
}
}, 500);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
// Intent newIntent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
//
// newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
//
// startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
Toast toast = Toast.makeText(getApplicationContext()," Found device" + device.getName(), Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.optionmenu,menu);
return super.onCreateOptionsMenu(menu);
}
}
Device list Class :
public class DeviceList extends AppCompatActivity {
private ListView mListView;
private AdapterClassBluetooth mAdapterClassBluetooth;
private ArrayList<BluetoothDevice> mDeviceList;
private BluetoothDevice device ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapterClassBluetooth = new AdapterClassBluetooth(this);
mAdapterClassBluetooth.setData(mDeviceList);
mAdapterClassBluetooth.setListener(new AdapterClassBluetooth.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Pairing..." , Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapterClassBluetooth);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast toast = Toast.makeText(getApplicationContext()," Device are paired, please wait...", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
Handler delaying = new Handler();
delaying.postDelayed(new Runnable() {
#Override
public void run() {
Intent communicate = new Intent(DeviceList.this,Security.class);
startActivity(communicate);
finish();
}
},1500);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast toast = Toast.makeText(getApplicationContext(),"Unpaired.", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
mAdapterClassBluetooth.notifyDataSetChanged();
}
}
};}
Adapter class :
public class AdapterClassBluetooth extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public AdapterClassBluetooth(){
}
public AdapterClassBluetooth(Context context) {
super();
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adapterlist, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
in an article i studied about this issue and find out that with this code :
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
i can make the application to support phones with android more than 6 so i can discover all nearby devices and pair with them,
The issue is, i don't know where should i exactly use this code..
i would really appreciate if you could tell me where to use it within the codes i showed here.
or simply tell me how to overcome this problem with any other code you may know.
In your AndroidManifest.xml file add this:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Then, instead of calling registerReceiver call this function:
private tryRegisterReceiver() {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Here, permission is not granted
// after calling requestPermissions, the result must be treated in onRequestPermissionResult
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1000); // 100 or other desired code
} else {
// Permission has already been granted
// continue registering your receiver
registerReceiver();
}
}
To treat the result of the permission request
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// continue registering your receiver
registerReceiver();
} else {
// permission denied
// show a message or finish your activity
}
return;
}
// other 'case' for other permissions if needed
}
}

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

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;
}

Remove notification from status bar after 20 second in android?

I created an android application. In this application I use the push notification concept. The notification is sent and received properly on the receiver.
Now I want to display the notification on status bar only for 20 second after that it will disappear. Can anyone tell me how can I do this? This is what I´ve so far.
public class ViewRecievedJobs extends Activity {
//private Button accept,reject;
private SharedPreferences pref;
private String login_token;
int status;
FragmentSendJob fsj;
ListView list;
Context con;
int pos;
static String job_id;
DatabaseAdmin database ;
ArrayList<HashMap<String, String>> adsArray = new ArrayList<HashMap<String,String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_received_jobs);
con=this;
pref=this.getSharedPreferences("Driver", MODE_WORLD_READABLE);
login_token = pref.getString("login_token","login_token");
database = new DatabaseAdmin(getApplicationContext());
//adsArray = database.getRecords_ads("Select * from SUN_NOTI where received =0");
//
//fsj.job_id=id;
//Log.e("adsArray", ""+adsArray);
list=(ListView)findViewById(R.id.listView1);
}
#Override
protected void onResume()
{
// Log.e("onResume", "onResume");
adsArray.clear();
adsArray = database.getRecords_ads("Select * from SUN_NOTI where status = 1");
list.setAdapter(new ReceivedJobList());
super.onResume();
}
class ReceivedJobList extends BaseAdapter
{
public int getCount() {
// TODO Auto-generated method stub
return adsArray.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return adsArray.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int arg0, View cView, ViewGroup arg2)
{
pos=arg0;
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cView = inflater.inflate(R.layout.job_received, null);
TextView name = (TextView)cView.findViewById(R.id.esuburb);
TextView dest = (TextView)cView.findViewById(R.id.edestination);
name.setText(adsArray.get(arg0).get("suburb"));
dest.setText(adsArray.get(arg0).get("destination"));
// Button view = (Button) cView.findViewById(R.id.view);
Button accept = (Button) cView.findViewById(R.id.accept);
Button reject = (Button) cView.findViewById(R.id.reject);
accept.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
status=0;
job_id=adsArray.get(arg0).get("message_id");
new JobStatus().execute();
// new ViewAdvertisement().execute();
// Toast.makeText(LoginScreen.this, "You clicked the button", Toast.LENGTH_SHORT).show();
}
});
/* view.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i =new Intent(con,Job_Detail.class);
i.putExtra("pos", ""+pos);
i.putExtra("from", "view");
i.putExtra("array",adsArray );
startActivity(i);
}
});*/
reject.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
status=2;
new JobStatus().execute();
}
});
return cView;
}
}
private class JobStatus extends AsyncTask<String, String, String[]> {
private ProgressDialog dialog;
protected void onPreExecute()
{
dialog = ProgressDialog.show(ViewRecievedJobs.this, "", "");
dialog.setContentView(R.layout.main);
dialog.show();
}
#Override
protected String[] doInBackground(final String... params)
{
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
{
HttpClient httpclient = new DefaultHttpClient();
JSONObject job1= new JSONObject();
try
{
job1.put("status_key",status);
job1.put("method", "job_status");
job1.put("login_token", login_token);
//job1.put("status",status);
job1.put("job_id",job_id);
StringEntity se = new StringEntity(job1.toString());
HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/DGCapp/webservice.php");
httppost.setEntity(se);
HttpResponse response1 = httpclient.execute(httppost);
String data1 = EntityUtils.toString(response1.getEntity());
Log.e("response",""+data1);
JSONObject jo = new JSONObject(data1);
String err=jo.getString("err-code");
if(err.equals("0"))
{
if( status == 0)
{
database.update_data(adsArray.get(pos).get("message_id"),"2");
//Toast.makeText(con, "Job Accepted", Toast.LENGTH_SHORT).show();
//show_Toast("Job Accepted");
dialog.dismiss();
Intent i =new Intent(con,Job_Detail.class);
i.putExtra("pos", ""+pos);
i.putExtra("from", "accept");
i.putExtra("array",adsArray );
startActivity(i);
}
else
{
database.delete_data(adsArray.get(pos).get("message_id"));
//show_Toast("Job Rejected");
//Toast.makeText(con, "Job Rejected", Toast.LENGTH_SHORT).show();
adsArray.clear();
adsArray = database.getRecords_ads("Select * from SUN_NOTI where status = 1");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
final AlertDialog.Builder alert = new AlertDialog.Builder(ViewRecievedJobs.this);
alert.setTitle("Alert !");
alert.setMessage("No Internet connection ");
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2,
int whichButton)
{
dialog.dismiss();
dialog2.dismiss();
}
});
runOnUiThread(new Runnable()
{
public void run()
{
//pDialog.dismiss();
alert.show();
}
});
}
return params;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String[] result)
{
super.onPostExecute(result);
if(dialog.isShowing())
{
dialog.dismiss();
}
if(status == 2)
{
Toast.makeText(con, "Job Rejected", Toast.LENGTH_SHORT).show();
list.setAdapter(new ReceivedJobList());
}
}
/*public void show_Toast(String msg)
{
Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
}*/
}
}
you can create a service that runs in the background and that will timeout after 20 minutes and delete your notification.Before that a notification should be there to notify the user... and the user should be able to dismiss it on their own.
Reference :
Make notification disappear after 5 minutes

Categories

Resources