My app is an sos app that can send an sms with location by shaking the phone to a saved contact.
But when i want to try my app it keep show me "permission denied can't use the app" although i added the permission (contact and location and sms)
Can you please help me to solve this problem
This is my code :
Button button1;
ListView listView;
databaseOpenHelper db;
List<ContactModel> list;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone);
// check for runtime permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS}, 100);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 100);
}
// start the service
SensorService sensorService = new SensorService();
Intent intent = new Intent(this, sensorService.getClass());
if (!isMyServiceRunning(sensorService.getClass())) {
startService(intent);
}
button1 = findViewById(R.id.Button1);
listView = (ListView) findViewById(R.id.ListView);
db = new databaseOpenHelper(this);
list = db.getAllContacts();
customAdapter = new CustomAdapter(this, list);
listView.setAdapter(customAdapter);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calling of getContacts()
if (db.count() != 5) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
} else {
Toast.makeText(phone.this, "Can't Add more than 5 Contacts", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i("Service status", "Running");
return true;
}
}
Log.i("Service status", "Not running");
return false;
}
#Override
protected void onDestroy() {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, ReactivateService.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permissions Denied!\n Can't use the App!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// get the contact from the PhoneBook of device
switch (requestCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phone = null;
try {
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
phones.moveToFirst();
phone = phones.getString(phones.getColumnIndex("data1"));
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
db.addcontact(new ContactModel(0, name, phone));
list = db.getAllContacts();
customAdapter.refresh(list);
} catch (Exception ex) {
}
}
}
break;
}
}
}
Related
I have a call method on button click
button_call=(Button) findViewById(R.id.button_call);
button_call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+79142214017"));
startActivity(intent);
}
});
And the data transfer method in Firebase
private void validateClientInfo() {
if (TextUtils.isEmpty(client_edit.getText().toString())) {
Toast.makeText(this, "Введите имя", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(client_number.getText().toString())){
Toast.makeText(this, "Введите номер", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> userMap = new HashMap<>();
userMap.put("uid", mAuth.getCurrentUser().getUid());
userMap.put("numberphone_client",client_number.getText().toString());
clientRef.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);
startActivity(new Intent(ClientName.this,HomeActivity.class));
}
}
transcripts
client_number=(EditText) findViewById(R.id.client_number);
mAuth=FirebaseAuth.getInstance();
how to make it so that when the call button is pressed, the number is received and called?
I want that when the button _call button is pressed, the data transmitted by the transfer method is received and a call is made on them.
Request permission android.permission.CALL_PHONE before calling.
Add into AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
Request permission before calling:
boolean isPermissionGranted = (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED);
if (isPermissionGranted) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + mNumber));
startActivity(intent);
} else {
Toast.makeText(this, "Отсутствует разрешение на звонок с устройства", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CALL_PHONE }, 0);
}
Add request result:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
//RETURN, PERMISSION NOT GRANTED
Toast.makeText(this, "Вы не выдали разрешение, приложение может работать неккоректно!", Toast.LENGTH_SHORT).show();
return;
}
}
//PERMISSIONS GRANTED
Toast.makeText(this, "Спасибо за выданное разрешение!", Toast.LENGTH_SHORT).show();
}
}
If your are looking to call the selected number then just use the following code.
Intent intentCallForward = new Intent(Intent.ACTION_DIAL); // ACTION_CALL
Uri uri2 = Uri.fromParts("tel", "79142214017, "#");
intentCallForward.setData(uri2);
startActivityForResult(intentCallForward, 101);
How can I check permission for every activity ???
I am trying to make a video player app. I am trying to get External Storage on Android 11 and the lower version. When I am clicking on the button it is asking for permission for both android 11 and the lower version (ex: Kitkat). But the problem is when I am going to the next activity after granting permission and turning off the storage permission from settings in the background. It was not asking for any permission for this new activity.
If anyone has any solution please help me I was shared my code bellow
My permission activity(MainActivity.java) and I want to check permission in (activity_allow_access.java).
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 100;
final static int REQUEST_CODE = 333;
private Button signIn;
public static String PREFS_NAME="MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = findViewById(R.id.button);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
} else {
requestPermission();
}
}
});
}
private void requestPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
try {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package",this.getPackageName(),null);
intent.setData(uri);
storageActivityResultLauncher.launch(intent);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
storageActivityResultLauncher.launch(intent);
}
}else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
}
}
private ActivityResultLauncher<Intent> storageActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.R){
if(Environment.isExternalStorageManager()){
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
}
else{
Toast.makeText(MainActivity.this, "storage permission required", Toast.LENGTH_SHORT).show();
}
}
}
}
);
public boolean checkPermission(){
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}else {
int write = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int read = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return write == PackageManager.PERMISSION_GRANTED && read == PackageManager.PERMISSION_GRANTED;
}
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
#SuppressLint("MissingSuperCall")
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE){
if (grantResults.length >0){
boolean write = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean read = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(write && read) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
} else {
requestPermission();
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if (checkPermission()) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
}
}
}
AllowAccessActivity.java
public class AllowAccessActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allow_access);
}
}
Having the following error:
android.os.FileUriExposedException: file:///storage/emulated/0/temp.jpg exposed beyond app through ClipData.Item.getUri()
when I choose Option Camera from chosen AlertDialog
And the following error when I try to choose a photo from Gallery:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0 (Is a directory)
The Gallery opens up, but I can't choose an image to set it to my ImageView
Here is the code:
public class MainActivity extends AppCompatActivity {
private Button contactsButton, galleryButton;
public static final int Gallery_Code = 100;
public static final int Contacts_Code = 101;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsButton = findViewById(R.id.buttonContacts);
galleryButton = findViewById(R.id.buttonGallery);
imageView = findViewById(R.id.imageView);
contactsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkPermission(Manifest.permission.READ_CONTACTS, Contacts_Code);
}
});
galleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
}
private void uploadImage() {
final String[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Upload Photo");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
File[] files = f.listFiles();
if (files != null) {
for (File temp : files) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
imageView.setImageBitmap(thumbnail);
}
}
}
private void checkPermission(String readContacts, int contacts_code) {
if (ContextCompat.checkSelfPermission(MainActivity.this, readContacts)
== PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{readContacts},
contacts_code);
} else {
Toast.makeText(MainActivity.this,
"Permission already granted",
Toast.LENGTH_SHORT)
.show();
if (contacts_code == Contacts_Code) {
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super
.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == Gallery_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Gallery Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else {
Toast.makeText(MainActivity.this,
"Gallery Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == Contacts_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Contacts Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Toast.makeText(MainActivity.this,
"Contacts Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
}
} }
the problem when I click on Button choose a contact and choose a contact not call the number, I want when choosing a Number phone call Directly
buttoncontact = findViewById(R.id.choosecontact);
public void choosecontact1 (View view){
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT)
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String call = buttoncontact.getText().toString();
if ((requestCode == 1) && (resultCode == RESULT_OK)) {
Cursor cursor = null;
try {
Uri uri = data.getData();
cursor = getContentResolver().query(uri, new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, null, null, null);
if (cursor != null && cursor.moveToNext()) {
String phone = cursor.getString(0);
// the Problem on that code
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(String.valueOf("tel:" + CONTENT_TYPE)));
// i want open phone contact and call directly
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
What is "CONTENT_TYPE"? Shouldn't it be the phone string you just get?
intent.setData(Uri.parse("tel:" + phone));
Add permission in manifest file :
Make function of calling phone number
private static final int CALL_REQUEST = 100;
private void callPhoneNumber(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ProfileActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_REQUEST);
return;
}
}
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9879879879" ));
startActivity(callIntent);
}
Above api level 23, need to ask runtime permission of call and if user allow it, it will go in below method :
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults)
{
if(requestCode == CALL_REQUEST)
{
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
callPhoneNumber();
}
else
{
Toast.makeText(ProfileActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
I have an issue with onActivityResult.
I'm using startActivityForResult to update some elements which data source is from a local database when these activities that I'm starting are over.
It works for two activities but, for some reason, it don't work in the last one. The statements that I put on onActivityResult don't trigger.
This is the code of the first activity, which calls the others:
public class ActivityEquipos extends AppCompatActivity {
public ArrayList<String> equipos = new ArrayList<>();
Spinner spEquipos;
ListView lvJugadores, lvPartidos;
Button btAddJugador, btAddPartido;
final public static int CODE_ADD_JUGADOR = 1, CODE_ADD_PARTIDO = 2, CODE_NEW_EQUIPO = 3;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_equipo, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.itNuevo:
Intent i = new Intent(getApplicationContext(), ActivityNewEquipo.class);
startActivityForResult(i, CODE_NEW_EQUIPO);
break;
case R.id.itVolver:
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_equipos);
spEquipos = findViewById(R.id.spEquipos);
lvJugadores = findViewById(R.id.lvJugadores);
lvPartidos = findViewById(R.id.lvPartidos);
btAddJugador = findViewById(R.id.btAddJugador);
btAddPartido = findViewById(R.id.btAddPartido);
cargaSpinner();
spEquipos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
actualizarJugadoresPartidos(i);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_ADD_JUGADOR && resultCode == RESULT_OK){
actualizarJugadoresPartidos(spEquipos.getSelectedItemPosition());
Toast.makeText(ActivityEquipos.this, "Jugador añadido con éxito.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_ADD_JUGADOR && resultCode == RESULT_CANCELED){
Toast.makeText(ActivityEquipos.this, "Añadido cancelado.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_ADD_PARTIDO && resultCode == RESULT_OK){
actualizarJugadoresPartidos(spEquipos.getSelectedItemPosition());
Toast.makeText(ActivityEquipos.this, "Partido añadido con éxito.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_NEW_EQUIPO && requestCode == RESULT_OK){
Log.d("carga", "precarga");
cargaSpinner();
Log.d("carga", "postcarga");
Toast.makeText(ActivityEquipos.this, "Equipo añadido con éxito.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_NEW_EQUIPO && requestCode == RESULT_CANCELED){
Toast.makeText(ActivityEquipos.this, "Añadido de equipo cancelado.", Toast.LENGTH_SHORT).show();
}
}
private void cargaSpinner(){
BaloncestoSQLiteHelper helper = new BaloncestoSQLiteHelper(this, "baloncesto", null, 7);
SQLiteDatabase db = helper.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM equipos", null);
equipos.clear();
if (c.moveToFirst()){
do {
equipos.add(c.getString(0));
} while (c.moveToNext());
}
spEquipos.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item, equipos));
db.close();
helper.close();
}
private void actualizarJugadoresPartidos(int i){
BaloncestoSQLiteHelper helper = new BaloncestoSQLiteHelper(ActivityEquipos.this, "baloncesto", null, 7);
final SQLiteDatabase db = helper.getWritableDatabase();
ArrayList<String> jugadores = new ArrayList<>();
final Cursor c = db.rawQuery("SELECT * FROM jugadores WHERE Nombre_equipo='" + equipos.get(i) + "'", null);
if (c.moveToFirst()){
do {
jugadores.add(c.getString(1));
} while (c.moveToNext());
}
ListJugadoresAdapter adapter = new ListJugadoresAdapter(ActivityEquipos.this, jugadores);
lvJugadores.setAdapter(adapter);
Log.d("tam", "" + jugadores.size());
//PARTIDOS
BaloncestoSQLiteHelper helperP = new BaloncestoSQLiteHelper(ActivityEquipos.this, "baloncesto", null, 7);
final SQLiteDatabase dbP = helperP.getWritableDatabase();
ArrayList<Partido> partidos = new ArrayList<>();
final Cursor cP = dbP.rawQuery("SELECT * FROM partidos WHERE equipo_local='" + equipos.get(i) + "' OR equipo_visitante='" + equipos.get(i) + "'", null);
if (cP.moveToFirst()){
do {
Partido partido = new Partido(cP.getString(1), cP.getString(2), cP.getInt(3), cP.getInt(4), cP.getString(5));
partidos.add(partido);
} while (cP.moveToNext());
}
ListPartidosAdapter partidosAdapter = new ListPartidosAdapter(ActivityEquipos.this, partidos);
lvPartidos.setAdapter(partidosAdapter);
dbP.close();
}
I removed the other activity calls from the code to make easier to see with which activity I have the problem.
Here is the second activity:
public class ActivityNewEquipo extends AppCompatActivity {
EditText etNombre, etConferencia, etDivision, etCiudad;
Button btAceptar, btCancelar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_equipo);
etNombre = findViewById(R.id.etNombreEquipo);
etConferencia = findViewById(R.id.etConferenciaEquipo);
etDivision = findViewById(R.id.etDivisionEquipo);
etCiudad = findViewById(R.id.etDivisionEquipo);
btAceptar = findViewById(R.id.btAniadirEquipo);
btCancelar = findViewById(R.id.btCancelarEquipo);
btCancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setResult(RESULT_CANCELED);
finish();
}
});
btAceptar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (etNombre.getText().toString().trim().isEmpty() ||
etCiudad.getText().toString().trim().isEmpty() ||
etConferencia.getText().toString().trim().isEmpty() ||
etDivision.getText().toString().trim().isEmpty()){
Toast.makeText(getApplicationContext(), "Campos vacíos. Imposible introducir", Toast.LENGTH_SHORT).show();
} else{
BaloncestoSQLiteHelper helper = new BaloncestoSQLiteHelper(getApplicationContext(), "baloncesto", null, 7);
final SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Nombre", etNombre.getText().toString().trim());
values.put("Ciudad", etCiudad.getText().toString().trim());
values.put("Conferencia", etConferencia.getText().toString().trim());
values.put("Division", etDivision.getText().toString().trim());
try{
db.insert("equipos", null, values);
db.close();
setResult(Activity.RESULT_OK);
finish();
}catch (SQLiteConstraintException ex){
Toast.makeText(getApplicationContext(), "Nombre de equipo duplicado", Toast.LENGTH_SHORT).show();
}
}
}
});
}
} else if (requestCode == CODE_NEW_EQUIPO && requestCode == RESULT_OK){
Change to
} else if (requestCode == CODE_NEW_EQUIPO && resultCode == RESULT_OK){
And... you made that error twice!!!
If you only -as a test- had put one Toast in it only...