Stack Overflow en español Asked by DarkVi on December 22, 2021
(EDITADO)
Leyendo la documentacion de firebase mi MainActivity queda asi…pero al correr en el emulador se me cierra la app…
public class MainActivity2 extends AppCompatActivity implements AdapterView.OnItemClickListener {
private EditText tv_nombre, tv_precio, tv_detalle;
private ImageView imagen;
private ListView mListView;
private List<Modelo> mLista;
private StorageReference storageRef;
private DatabaseReference databaseReference;
private ProgressBar mProgressBar;
private Uri mImageUri;
ListAdapter mAdapter;
FirebaseFirestore mFirestore;
FirebaseStorage storage;
@SuppressLint("WrongThread")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mFirestore = FirebaseFirestore.getInstance();
mListView = findViewById(R.id.listView);
mListView.setOnItemClickListener(this);
imagen.setDrawingCacheEnabled(true);
imagen.buildDrawingCache();
mLista = new ArrayList<>();
mLista.add(new Modelo(" Zapatos de futbol 1", "$ 56.99", "Nike Tiempo Legend VIII", R.mipmap.pupos1));
mLista.add(new Modelo(" Zapatos de futbol 2", "$ 71.49", "Nike Phantom Vision 2", R.mipmap.pupos2));
mLista.add(new Modelo(" Zapatos de futbol 3", "$ 37.49", "New Balance Furon v5", R.mipmap.pupos3));
mLista.add(new Modelo(" Zapatos de futbol 4", "$ 18.49", "Umbro Classico V AG", R.mipmap.pupos4));
mAdapter = new ListAdapter(this, R.layout.item_row, mLista);
mListView.setAdapter(mAdapter);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bitmap bitmap = ((BitmapDrawable) imagen.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageReference storageRef = storage.getReference();
StorageReference puposRef = storageRef.child("pupos1.jpg");
StorageReference puposImagesRef = storageRef.child("images/pupos1");
puposRef.getName().equals(puposImagesRef.getName()); // true
puposRef.getPath().equals(puposImagesRef.getPath());
UploadTask uploadTask = puposImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
String nombre = tv_nombre.getText().toString();
String precio = tv_precio.getText()introducir el código aquí.toString();
String detalle = tv_detalle.getText().toString();
Map<String, Object> map = new HashMap<>();
map.put("Nombre", nombre);
map.put("Precio", precio);
map.put("Detalle", detalle);
mFirestore.collection("Modelo").add(map).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(MainActivity2.this, "Producto Seleccionado", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity2.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
/////ADJUNTO EL ERROR QUE ME APARECE EN EL RUN, SE ME ACABARON LAS IDEAS Y SIGO SIN PODER SUBIR LA IMAGEN JUNTO A MIS DEMAS DATOS A FIREBASE//////////
07/25 17:15:38: Launching 'app' on Pixel 3a API 30.
$ adb shell am start -n "com.example.cgpractica/com.example.cgpractica.MainActivity2" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 23649 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/MultiDex: VM with version 2.1.0 has multidex support
Installing application
I/MultiDex: VM has multidex support, MultiDex support library is disabled.
I/FirebaseInitProvider: FirebaseApp initialization successful
I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:15 and remote module com.google.android.gms.measurement.dynamite:0
I/DynamiteModule: Selected local version of com.google.android.gms.measurement.dynamite
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/mple.cgpractic: Unsupported class loader
W/mple.cgpractic: Unsupported class loader
V/FA: onActivityCreated
W/mple.cgpractic: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/mple.cgpractic: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cgpractica, PID: 23649
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cgpractica/com.example.cgpractica.MainActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setDrawingCacheEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setDrawingCacheEnabled(boolean)' on a null object reference
at com.example.cgpractica.MainActivity2.onCreate(MainActivity2.java:74)
at android.app.Activity.performCreate(Activity.java:7995)
at android.app.Activity.performCreate(Activity.java:7979)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package, google app id: com.example.cgpractica, 1:482635389447:android:13cf0723f55607780728a2
I/FA: App measurement initialized, version: 31000
To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.cgpractica
D/FA: Debug-level message logging enabled
W/mple.cgpractic: Verification of java.lang.Object com.google.android.gms.measurement.internal.zzm.createFromParcel(android.os.Parcel) took 215.207ms (1356.83 bytecodes/s) (6016B approximate peak alloc)
V/FA: Connecting to remote service
V/FA: Connection attempt already in progress
/////ADJUNTO EL ERROR QUE ME APARECE EN EL RUN, SE ME ACABARON LAS IDEAS Y SIGO SIN PODER SUBIR LA IMAGEN JUNTO A MIS DEMAS DATOS A FIREBASE//////////
////Logre subir la imagen a firebase, tenia que convertir la imagen a bytes, por si alguien lo necesita dejo el codigo.
private String encodeImage(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String img = Base64.encodeToString(b, Base64.DEFAULT);
return img;`introducir el código aquí`
}
Answered by DarkVi on December 22, 2021
Para guardar la imagen, primero debes obtener el bitmap que seria lo que vas a subir a firebase
Luego debes seguir los pasos de la documentacion de Firebase Storage para cargar la imagen
https://firebase.google.com/docs/storage/android/upload-files?hl=es
final StorageReference ref = storageRef.child("images/mountains.jpg"); // -> Donde guardamos la imagen en Firebase Storage
uploadTask = ref.putFile(file); // -> Acá file deberia ser el bitmap de la imagen
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult(); // -> una vez subida la imagen a Firebase obtenemos la url de la imagen de ser necesario
} else {
// Maneja fallos si no se cargó correctamente
// ...
}
}
});
Answered by Gastón Saillén on December 22, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP