我正在与我的一些朋友一起开发一个应用程序:它是关于发现流浪动物的。我负责设置firebase部分,并且正在寻找一些解决方案,例如1)创建链接到特定用户的所有票证的列表;每个票证都有一些字段,用户可以发送大量票证2)将一张或多张图片链接到特定票证。我已经编写了Ticket.java类。 我需要设置和解决这些问题吗?
我正在使用Android Studio(intelliJ)和firebase。我既没有Android Studio也没有Firebase,没有太多专业知识。
public class UserTicketFragment extends Fragment {
public TextView nome;
public TextView cognome;
public TextView telefono;
public TextView commenti;
public Button invia;
public Button camera;
public ImageView foto;
public Bitmap bitmap;
public Button gps;
public TextView coordinate;
private FusedLocationProviderClient clientGPS;
private static final int PERMISSION_CODE = 1000;
private static final int codicepermesso = 1;
private FirebaseUser user;
private FirebaseAuth firebaseAuth;
private Ticket segnalazione;
private DatabaseHelper databaseInstance;
private static final String TAG = "testo";
private FirebaseDatabase firebaseDatabase;
private DatabaseReference reference;
private Uri uri;
View view;
public UserTicketFragment() {
// Required empty public constructor
}
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_user_ticket, container, false);
nome = view.findViewById(R.id.nomeText);
cognome = view.findViewById(R.id.cognomeTicket);
telefono = view.findViewById(R.id.telTicket);
commenti = view.findViewById(R.id.commentoTicket);
invia = view.findViewById(R.id.invioTicket);
camera = view.findViewById(R.id.apriFoto);
foto = view.findViewById(R.id.testImmagine);
gps = view.findViewById(R.id.gpsButton);
clientGPS = LocationServices.getFusedLocationProviderClient(getContext());
coordinate = view.findViewById(R.id.gpsView);
firebaseAuth = FirebaseAuth.getInstance();
databaseInstance = DatabaseHelper.getInstance();
return view;
}
@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
requestPermission();
gps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != 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;
}
clientGPS.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
coordinate.setText(location.toString());
}
});
}
});
invia.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nomeUtente = nome.getText().toString();
String cognomeUtente = cognome.getText().toString();
Date data = new Date();
String numeroTel = telefono.getText().toString();
String commentoTicket = commenti.getText().toString();
if (bitmap != null) {
// TODO: caricamento + get Uri
saveTicketToFirebase();
//segnalazione = new Ticket(true, nomeUtente, cognomeUtente, data, numeroTel, commentoTicket, bitmap);
//manca la gestione della segnalazione da inviare da qualche parte nell'universo.
} else {
saveTicketToFirebase();
segnalazione = new Ticket(true, nomeUtente, cognomeUtente, data, numeroTel, commentoTicket);
}
user = firebaseAuth.getCurrentUser();
String userReference = "ticket/" + user.getUid() + "/" + data.getTime() + "/"; // TODO: id usiamo data e ora con secondi
// TODO aggiungere controllo degli input, e autofill
databaseInstance.writeOnDatabase(userReference + "status/", segnalazione.getStatus().toString());
databaseInstance.writeOnDatabase(userReference + "nome/", segnalazione.getNome());
databaseInstance.writeOnDatabase(userReference + "cognome/", segnalazione.getCognome());
databaseInstance.writeOnDatabase(userReference + "data/", segnalazione.getData());
databaseInstance.writeOnDatabase(userReference + "numero/", segnalazione.getNumero());
databaseInstance.writeOnDatabase(userReference + "note/", segnalazione.getNote());
Toast.makeText(getContext(), "Grazie, Una autorità prenderà in carico la sua segnalazione ", Toast.LENGTH_SHORT).show();
}
});
camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission_group.CAMERA) == PackageManager.PERMISSION_DENIED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, PERMISSION_CODE);
}
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
private void requestPermission() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
/**
* private void saveTicket() {
* if (user != null) {
* // if the user is not null, then the user has authenticated already.
* } else {
* // we need to authenticate
* List<AuthUI.IdpConfig> providers = Arrays.asList(new AuthUI.IdpConfig.EmailBuilder().build(),
* new AuthUI.IdpConfig.GoogleBuilder().build());
* startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().
* setAvailableProviders(providers).build(), AUTHORIZATION_REQUEST_CODE);
* }
* }
**/
// qua ci dovrebbe essere il bottone di fotocamera + costruttore con bitmap
private void saveTicketToFirebaseUri() {
Ticket ticket = new Ticket();
/**
ticket.setNome(actNome.getText().toString());
ticket.setCognome(actCognome.getText().toString());
ticket.setLatitudine(Double.toString(latitudine));
ticket.setLongitudine(Double.toString(longitudine));
ticket.setNote(edtNote.getText().toString());
ticket.setPosizione(actPosizione.getText().toString());
ticket.setStatus(actStatus.getText().toString());
ticket.setNumero(actNumero.getText().toString());
ticket.setIdUser(UserGuid);
**/
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference();
if (uri != null) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
final StorageReference imageRef = storageReference.child("foto_segnalazioni/" + uri.getLastPathSegment());
final StorageReference imageRef = storageReference.child("foto_segnalazioni/" + user.getUid() + "/" + uri.getLastPathSegment());
Upload uploadTask = imageRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
public void onFailure(@NonNull Exception e) {
int i = 1 + 1;
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// this is where we will end up if our image uploads successfully.
StorageMetadata snapShotMetadata = taskSnapshot.getMetadata();
Task<Uri> downloadUrl = imageRef.getDownloadUrl();
downloadUrl.addOnSuccessListner(new OnSuccessListener<Uri>() {
public void onSuccess(Uri uri) {
String imageReference = uri.toString();
reference.child("tickets").child(ticket.getKey()).child("imageUrl").setValue(imageReference);
ticket.setImageUrl(imageReference);
}
});
}
});
DatabaseReference ticketReference = reference.child("tickets").push();
ticket.setImageUrl(" "); //TODO: devo mettere il path
ticketReference.setValue(ticket);
String key = ticketReference.getKey();
ticket.setKey(key);
}
private void takePhoto(){
prepInvokeCamera();
}
private void prepInvokeCamera(){
// permissions check.
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
invokeCamera();
} else {
String[] permissionRequest = {Manifest.permission.CAMERA};
requestPermissions(permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
}
private void invokeCamera(){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// path to the images directory.
File imagePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
// create an image file at this path.
File picFile = new File(imagePath, getPictureName());
// convert file to URI
uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", picFile);
// where do I want to save the image?
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
// pass permission to the camera
cameraIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
private void saveTicketToFirebase () {
Ticket ticket = new Ticket();
ticket.setNome(actNome.getText().toString());
ticket.setCognome(actCognome.getText().toString());
ticket.setLatitudine(Double.toString(latitudine));
ticket.setLongitudine(Double.toString(longitudine));
ticket.setNote(edtNote.getText().toString());
ticket.setPosizione(actPosizione.getText().toString());
ticket.setStatus(actStatus.getText().toString());
ticket.setNumero(actNumero.getText().toString());
ticket.setIdUser(UserGuid);
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference();
DatabaseReference ticketReference = reference.child("tickets").push();
ticketReference.setValue(ticket);
String key = ticketReference.getKey();
ticket.setKey(key);
}
private String getPictureName () {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Date now = new Date();
String timestamp = sdf.format(now);
// assemble a picture name
String pictureName = "image" + timestamp + ".jpg";
return pictureName;
}
public class AllTickets extends AsyncTask<String, Integer, List<Ticket>> {
@Override
protected void onPostExecute(List<Ticket> ticketDTOS) {
super.onPostExecute(ticketDTOS);
// adapt the data to be UI friendly.
ArrayAdapter<Ticket> ticketAdapter = new ArrayAdapter<Ticket>
(GPSATicket.this, android.R.layout.simple_list_item_1, ticketDTOS);
// associate the data with the auto complete text view.
actTicketName.setAdapter(ticketAdapter);
progressDialog.dismiss();
}
@Override
protected List<Ticket> doInBackground(String... searchTerms) {
List<Ticket> allTickets = new ArrayList<Ticket>();
// declare a variable for our DAO class that will do a lot of the networking for us.
ITicketDAO ticketDAO = new TicketJSONDAO();
String searchTerm = searchTerms[0];
try {
allTickets = ticketDAO.search(searchTerm);
int ticketCounter = 0;
// iterate over all of the tickets we fetched, and place them into the local database.
for (Ticket ticket : allTickets) {
// act like we're saving to the database.
ticketCounter++;
if (ticketCounter % (allTickets.size() / 25) == 0) {
// update progress
publishProgress(ticketCounter * 100 / allTickets.size());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return allTickets;
}
}
摘要Firebase:
{
"ticket" : {
"GyRZLOHEzpWgl94VHDJPTpM4XmJ2" : {
"1558613937081" : {
"nome" : "xxx",
"status" : "true"
}
},
"st7VHYtVw9ZJFkzyU0lSNCjYBNz1" : {
"1559040068589" : {
"cognome" : "asdfasdfasdf",
"data" : "Tue May 28 10:41:08 GMT 2019",
"nome" : "adfasdfasf",
"note" : "ffffffd",
"numero" : "273327332733",
"status" : "true"
},
"1559040347210" : {
"cognome" : "pippa",
"data" : "Tue May 28 10:45:47 GMT 2019",
"nome" : "pippo",
"note" : "pippo la pippa",
"numero" : "123123",
"status" : "true"
}
}
},
"tickets" : {
"id_ticket" : {
"cognome" : true,
"data" : true,
"id_user" : true,
"nome" : true,
"note" : true,
"numero" : true,
"posizione" : {
"latitudine" : true,
"longitudine" : true
},
"status" : true
}
},
"users" : {
"3pLJfyD6SBUqC7FzgDD12TyQE0r1" : {
"cognome" : "b",
"email" : "c@gmail.com",
"nome" : "a",
"telefono" : "123456"
},
"6lFKqSjtZ1eUEnuIWe1TI6G0Y742" : {
"admin" : true,
"cognome" : "D",
"email" : "d@gmail.com",
"nome" : "I",
"telefono" : "333333333"
},
"GyRZLOHEzpWgl94VHDJPTpM4XmJ2" : {
"cognome" : "a",
"email" : "y@gmail.com",
"nome" : "l",
"telefono" : "4444444444"
},
"st7VHYtVw9ZJFkzyU0lSNCjYBNz1" : {
"admin" : true,
"cognome" : "s",
"email" : "n@gmail.com",
"nome" : "e",
"telefono" : "666666666"
}
}
}