How to upload this gridview of base 64 converted images to firebase? - java

This is the code I am working on, make a multiple selection of images and the most in a gridview array that calls it ImageList, but I would recommend converting the images to a base64 to have more efficiency when uploading and displaying the images, so I looked for examples and documentation and I found a way to convert them, but I was somewhat confused, because the array where the images are stored was ready List of images I had to pass it to a chain of chains, but I did not understand very well how to upload them to the firebase both the storage and the database, since they are images that will be saved of products that will be shown in the store this is the code
here is the activity where the data will be uploaded, the data as name price and description already uploaded to the database the imagenes not.
public class adminActivity extends AppCompatActivity {
private EditText nombreP, precioP, infoP;
int PICK_IMAGE = 100;
Uri imagenUri;
Button btnCargar;
Button btnEditar;
GridView gvImagenes;
List<Uri> listaImagenes = new ArrayList<>();
List<Uri> listaBase64Imagenes = new ArrayList<>();
GridViewAdapter baseAdapter;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference mStorageRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
/*INICIALIZAMOS LA CONEXION CON FIREBASE*/
FirebaseApp.initializeApp(this);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
mStorageRef = FirebaseStorage.getInstance().getReference();
nombreP = (EditText) findViewById(R.id.nameProducto);
precioP = (EditText) findViewById(R.id.precioProducto);
infoP = (EditText) findViewById(R.id.infoProducto);
gvImagenes = findViewById(R.id.gvImagenes);
btnEditar = findViewById(R.id.editar);
btnCargar = (Button) findViewById(R.id.cargar);
btnEditar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
abrirGaleria();
}
});
btnCargar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre = nombreP.getText().toString();
String precio = precioP.getText().toString().trim();
String infor = infoP.getText().toString();
if (!nombre.isEmpty() && !precio.isEmpty() && !infor.isEmpty()){
cargarUsuario();
limpiarCaja();
}else {
Toast.makeText(adminActivity.this,"Deben llenarse todos los campos.",Toast.LENGTH_SHORT).show();
return;
}
}
});
}
private void limpiarCaja() {
nombreP.setText("");
precioP.setText("");
infoP.setText("");
}
public void cargarUsuario() {
listaBase64Imagenes.clear();
for (int i = 0 ; i < listaImagenes.size() ; i++){
try {
InputStream is = getContentResolver().openInputStream(listaImagenes.get(i));
Bitmap bitmap = BitmapFactory.decodeStream(is);
String cadena = convertirUriToBase64(bitmap);
enviarImagen(cadena);
bitmap.recycle();
} catch (IOException e){
}
}
//Toast.makeText(this, "Producto Registrado", Toast.LENGTH_LONG).show();
String nombre = nombreP.getText().toString();
String precio = precioP.getText().toString();
String infor = infoP.getText().toString();
productos p = new productos();
p.setUid(UUID.randomUUID().toString());
p.setNombre(nombre);
p.setPrecio(precio);
p.setInformacion(infor);
databaseReference.child("Productos").child(p.getUid()).setValue(p);
Toast.makeText(adminActivity.this,"Agregado.",Toast.LENGTH_SHORT).show();
}
private void enviarImagen(final String cadena) {
StorageReference folderRef = mStorageRef.child("imagenesProductos");
folderRef.putFile((Uri) listaImagenes).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
}
});
}
private String convertirUriToBase64(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
String encode = Base64.encodeToString(bytes, Base64.DEFAULT);
return encode;
}
private void abrirGaleria() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "SELECCIONA LAS IMAGENES"),PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ClipData clipData = data.getClipData();
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
/*PARA UNA SOLA IMAGEN*/
if (clipData == null){
imagenUri = data.getData();
listaImagenes.add(imagenUri);
}
}else {
/*PARA VARIAS IMAGENES*/
for (int i = 0; i < clipData.getItemCount(); i++){
listaImagenes.add(clipData.getItemAt(i).getUri());
}
}
baseAdapter = new GridViewAdapter(adminActivity.this, listaImagenes);
gvImagenes.setAdapter(baseAdapter);
}
}
and here is the gridview adapter code
#Override
public int getCount() {
return listaImagenes.size();
}
#Override
public Object getItem(int position) {
return listaImagenes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null){
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.item_carga_imagenes, null);
}
ImageView ivImagen = view.findViewById(R.id.ivImagen);
ImageButton ibtnEliminar = view.findViewById(R.id.ibtnEliminar);
ivImagen.setImageURI(listaImagenes.get(position));
ibtnEliminar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listaImagenes.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
here i point out the method where i try to make the connection to the storage of firebase, they could help to rebuild it in order to be able to upload them to the storage and also to the database with their respective name, price and description
private void enviarImagen(final String cadena) {
StorageReference folderRef = mStorageRef.child("imagenesProductos");
folderRef.putFile((Uri) listaImagenes).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
}
});
}

Your question is still little bit of confusion, In my case what i understand from you, you want to store images to firebase in BASE64 format.
String encode = Base64.encodeToString(bytes, Base64.DEFAULT);
Now, you don't have you store string, you can simply store byte[] in firbase and retrive it and just converted it to bitmap, here is a example for you:
byte[] byteImage = Base64.decode(encode, Base64.DEFAULT);
Bitmap imageBitmap = BitmapFactory.decodeByteArray(byteImage, 0, decodedString.length);

Related

How to retrieve image from firestore in a clickable span widget?

I have successfully uploaded the media in the firebase but i'm unable to retrieve it. apparently it shows that the media_problem is pointing to a null object. below is my code.
This is my code to retrieve:
this.view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "TOO FAST! TRY AGAIN", Toast.LENGTH_LONG);
try {
Dash_agri.this.firestore.collection("problems").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete( Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
Dash_agri.this.records.clear();
Iterator it = ((QuerySnapshot) task.getResult()).iterator();
while (it.hasNext()) {
QueryDocumentSnapshot document = (QueryDocumentSnapshot) it.next();
Dash_agri.this.single_ID = document.getId();
Dash_agri.this.single_name = (String) document.get("NAME_problems");
Dash_agri.this.single_phone = (String) document.get("PHONE_problems");
Dash_agri.this.single_description = (String) document.get("DESCRIPTION_problems");
Dash_agri.this.single_URL = (String) document.get("MEDIA_problems");
String view_media = "Touch to view media";
new SpannableString(view_media).setSpan(new ClickableSpan() {
public void onClick(View widget) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
}
}, 0, 9, 33);
Dash_agri.this.record_id.add(Dash_agri.this.single_ID);
ArrayList<String> arrayList = Dash_agri.this.records;
StringBuilder sb = new StringBuilder();
sb.append("QUERY#");
sb.append(Dash_agri.this.single_ID);
sb.append(" by ");
sb.append(Dash_agri.this.single_name);
sb.append("\n");
sb.append(Dash_agri.this.single_description);
sb.append("\n\n");
sb.append(view_media);
arrayList.add(sb.toString());
}
}
}
});
} catch (Exception e) {
Toast.makeText(Dash_agri.this.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
}
Dash_agri.this.listView.setAdapter(new ArrayAdapter<>(Dash_agri.this.getApplicationContext(), R.layout.simple_list_item_1, Dash_agri.this.records));
}
});
This is my code to upload:
public class Upload extends AppCompatActivity {
private static final int PICK_MEDIA_REQUEST = 1;
String MEDIA_url;
String NAME;
String PHONE;
long TIME_ID = System.currentTimeMillis();
String USER_ID;
TextView file;
FirebaseAuth firebaseAuth;
FirebaseFirestore firestore;
Button img;
EditText prob;
ProgressBar progressBar;
StorageReference storageReference;
Button upld;
/* access modifiers changed from: private */
public Uri uri;
Button vid;
/* access modifiers changed from: protected */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == -1 && data != null && data.getData() != null) {
this.uri = data.getData();
this.file.setText(this.uri.getPath());
}
}
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_upload);
this.firebaseAuth = FirebaseAuth.getInstance();
this.firestore = FirebaseFirestore.getInstance();
this.storageReference = FirebaseStorage.getInstance().getReference();
this.prob = (EditText) findViewById(R.id.editTextProblem_upload);
this.file = (TextView) findViewById(R.id.textViewFile_upload);
this.img = (Button) findViewById(R.id.buttonImage_upload);
this.vid = (Button) findViewById(R.id.buttonVideo_Upload);
this.upld = (Button) findViewById(R.id.buttonUpload_upload);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar_upload);
this.progressBar.setVisibility(View.VISIBLE);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction("android.intent.action.GET_CONTENT");
Upload.this.startActivityForResult(intent, 1);
}
});
this.vid.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction("android.intent.action.GET_CONTENT");
startActivityForResult(intent, 1);
}
});
try {
this.upld.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (prob.getText().toString().isEmpty() || file.getText().toString().equals("No file selected")) {
Toast.makeText(getApplicationContext(), "Please write your problem and upload a file!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
upload_file_also(uri);
USER_ID = firebaseAuth.getCurrentUser().getUid();
TIME_ID = System.currentTimeMillis();
firestore.collection("users").document(USER_ID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
NAME = documentSnapshot.getString("NAME_");
PHONE = documentSnapshot.getString("PHONE_");
}
});
NAME = NAME == null ? "null" : NAME;
PHONE = PHONE == null ? "null" : PHONE;
if (!NAME.equals("null") && !PHONE.equals("null")) {
CollectionReference collection = firestore.collection("problems");
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(TIME_ID);
DocumentReference documentReference = collection.document(String.valueOf(sb.toString()));
Map<String, Object> user_problems = new HashMap<>();
user_problems.put("DESCRIPTION_problems", prob.getText().toString());
user_problems.put("NAME_problems", NAME);
user_problems.put("PHONE_problems", PHONE);
user_problems.put("MEDIA_problems", Upload.this.MEDIA_url);
documentReference.set(user_problems).addOnSuccessListener(new OnSuccessListener<Void>() {
public void onSuccess(Void aVoid) {
Toast.makeText(Upload.this.getApplicationContext(), "Successfully uploaded", Toast.LENGTH_SHORT).show();
Upload.this.startActivity(new Intent(Upload.this.getApplicationContext(), Dash_farmer.class));
Upload.this.finish();
}
});
}
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
/* access modifiers changed from: private */
public void upload_file_also(Uri fileUri) {
StorageReference storageReference2 = this.storageReference;
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(this.TIME_ID);
final StorageReference sr = storageReference2.child(String.valueOf(sb.toString()));
sr.putFile(fileUri).addOnSuccessListener((OnSuccessListener<TaskSnapshot>) new OnSuccessListener<TaskSnapshot>() {
public void onSuccess(TaskSnapshot taskSnapshot) {
sr.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
public void onSuccess(Uri uri) {
Upload.this.MEDIA_url = uri.toString();
Upload.this.progressBar.setVisibility(View.VISIBLE);
Upload.this.upld.setText("TAP AGAIN TO UPLOAD MEDIA");
}
});
}
});
}
}
I'm unable to find why this isn't working. Please put a light on where this is going wrong.

How to retrieve a photo from the camera for gridview?

I'm developing an app that, in the first activity, it takes a photo saved, and it is shown in an imageview, but at the same time I want a gridview to be created in another activity, which will recover each captured image, showing in order.
So far I can take a picture, save it in the gallery, and show it on the imageview, but when I go to the other activity, it shows the gridview retrieving all the photos from the gallery, could someone help me? This is my schedule:
Activity in which you take the photo and save it:
public class Main2Activity extends AppCompatActivity {
private Uri uri;
private static final int CAMERA = 1;
private String caminhoDaImagem;
ImageView imageViewFoto;
private EditText etCliente;
private EditText etPostes;
private EditText etObservacao;
String mCurrentPhotoPath;
String imgSaved;
private Button botao;
#Override
public void onBackPressed() { //Botão BACK padrão do android
startActivity(new Intent(this, MainActivity.class)); //O efeito ao ser pressionado do botão (no caso abre a activity)
//finishAffinity(); //Método para matar a activity e não deixa-lá indexada na pilhagem
return;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final Button btnSalvarRelatorio = (Button) findViewById(R.id.btnAvancar);
Button btnAvancar = (Button) findViewById(R.id.btnAvancar);
//CÓDIGO NECESSÁRIO PARA A PERMISSÃO A MEMÓRIA INTERNA
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
}
//PERMISSÃO DE ACESSO Á CAEMRA
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
}
findViewById(R.id.btnTirarFotos).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tirarFoto();
}
});
findViewById(R.id.btnAvancar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chamar3Activity();
}
});
}
/*public void onRequestPermissionResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResult) {
switch (requestCode) {
case 1000:
if (grantResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permissão Concedida!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permissão não Concedida!", Toast.LENGTH_SHORT).show();
finish();
}
}
}*/
private void chamar3Activity() {
Intent novaintent = new Intent();
novaintent.setClass(Main2Activity.this, Main3Activity.class);
startActivity(novaintent);
finish();
}
//DANDO A FUNÇÃO AO BOTÃO DE TIRAR FOTO
public void tirarFoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
//SALVANDO IMAGEM DA CAMERA E DIRECIONANDO ELA A UM IMAGEVIEW
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
File file = null;
try {
file = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
}
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.imageView2);
imageview.setImageBitmap(image);
// Chame este método pra obter a URI da imagem
Uri uri = getImageUri(getApplicationContext(), image);
// Em seguida chame este método para obter o caminho do arquivo
File file = new File(getRealPathFromURI(uri));
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "CANCELADO", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_LONG).show();
return image;
}
** Activity where the Grid View will be shown: **
public class MainActivity extends AppCompatActivity {
GridView gv;
ArrayList<File> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = imageRead(Environment.getExternalStorageDirectory());
gv = (GridView) findViewById(R.id.gv);
gv.setAdapter(new GridAdapter());
}
class GridAdapter extends BaseAdapter{
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.single_grid, parent, false);
ImageView imageView = convertView.findViewById(R.id.imageView);
imageView.setImageURI(Uri.parse( getItem(position) . toString()));
return convertView;
}
}
ArrayList<File> imageRead(File root){
ArrayList<File> a = new ArrayList<>();
File[] files = root.listFiles();
for(int i =0; i< files.length; i++){
if(files[i].isDirectory()){
a.addAll(imageRead(files[i]));
}
else{
if( files[i].getName().endsWith(".jpg")){
a.add(files[i]);
}
}
}
return a;
}

Show the image stored in Firebase storage in Imageview from Firebase Database

I'm trying to show the image which has been sucessfully uploaded in firebase storage and whose unique id is also updated in Firebase Database under "pics" in my Imageview but I did tried multiple time but am unable to show the image or retrive images .
Below is my Firebase Database Structure.
and my Imageview is
Where image should be displayed in place of Bookshelf which is default pic but unable to do so.
Below is my upload Activity
public class UploadBook extends AppCompatActivity {
FirebaseDatabase database;
EditText etAuthor, etbookDesc, etbookTitle, etName, etEmail, etMobile, etUniversity, etbookPrice;
ImageView iv1;
Button b1;
AlertDialog.Builder builder1;
DatabaseReference dbreference;
String item = "start"; // for spinner
FirebaseStorage storage;
private static final int CAMERA_REQUEST_CODE = 1;
StorageReference mStorageRef;
FirebaseAuth fauth;
int count = 0;
Uri filePath = null;
public Books b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.nepalpolice.bookbazaar.R.layout.activity_upload_book);
getSupportActionBar().setTitle("Upload book");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
ActivityCompat.requestPermissions(UploadBook.this, new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 11);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference();
fauth = FirebaseAuth.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference();
iv1 = (ImageView) findViewById(com.nepalpolice.bookbazaar.R.id.itemImage1);
etAuthor = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText1);
etbookDesc = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText2);
etbookTitle = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText3);
etName = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText4);
etEmail = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText5);
etMobile = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText6);
etUniversity = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText7);
etbookPrice = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText8);
b1 = (Button) findViewById(com.nepalpolice.bookbazaar.R.id.buttonPost);
t3 t = new t3();
t.execute();
Spinner spinner = (Spinner) findViewById(com.nepalpolice.bookbazaar.R.id.spinner1);
final String[] items = new String[]{"Select your category :", "Computer Science", "Electronics", "Mechanical", "Civil", "Electrical", "Mechatronics", "Software", "Others"};
ArrayAdapter<String> spinneradapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
spinner.setAdapter(spinneradapter);
spinner.setActivated(false);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
item = adapterView.getItemAtPosition(position).toString();
count = position;
if (position == 0)
return;
Toast.makeText(adapterView.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
imageButtonclick();
postButtonClick();
builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Discard this item !");
builder1.setCancelable(true);
builder1.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent in = new Intent(UploadBook.this, BooksPage.class);
startActivity(in);
finish();
dialog.cancel();
}
});
}
void imageButtonclick() {
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity(filePath).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(UploadBook.this);
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//intent.putExtra(MediaStore.EXTRA_OUTPUT,imageuri);
//startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
void postButtonClick() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (count == 0) {
Toast.makeText(UploadBook.this, "Please select a valid category", Toast.LENGTH_SHORT).show();
return;
}
if (!TextUtils.isDigitsOnly(etMobile.getText()) || etMobile.getText().toString().trim().length() != 10) {
Toast.makeText(UploadBook.this, "Please check number format !", Toast.LENGTH_SHORT).show();
return;
}
if (etAuthor.getText().toString().trim().length() > 0 && etbookDesc.getText().toString().trim().length() > 0
&& etbookTitle.getText().toString().trim().length() > 0 && etName.getText().toString().trim().length() > 0
&& etEmail.getText().toString().trim().length() > 0 && etMobile.getText().toString().trim().length() > 0
&& etUniversity.getText().toString().trim().length() > 0 && etbookPrice.getText().toString().trim().length() > 0
&& filePath!=null) {
String bauthor = etAuthor.getText().toString();
String bdesc = etbookDesc.getText().toString();
String btitle = etbookTitle.getText().toString();
String sellername = etName.getText().toString();
String selleremail = etEmail.getText().toString();
Long sellermobile = Long.parseLong(etMobile.getText().toString());
String selleruniversity = etUniversity.getText().toString();
Double bprice = Double.parseDouble(etbookPrice.getText().toString());
Toast.makeText(getApplicationContext(), "Your book will be uploaded shortly !", Toast.LENGTH_SHORT).show();
b = new Books(btitle, bauthor, bdesc, sellername, selleremail, sellermobile, item, selleruniversity, bprice);
String bookid = dbreference.child("books").child(item).push().getKey();
dbreference.child("books").child(item).child(bookid).setValue(b);
t2 t2 = new t2();
t2.execute(bookid);
Intent in = new Intent(UploadBook.this, BooksPage.class);
startActivity(in);
finish();
} else {
Toast.makeText(UploadBook.this, "Please enter your complete details !", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
/*AlertDialog alert2 = builder1.create();
alert2.show();*/
CustomDialogClass cdd = new CustomDialogClass(UploadBook.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
filePath = data.getData();
iv1.setImageURI(filePath);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
iv1.setImageURI(resultUri);
filePath = resultUri;
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
class t2 extends AsyncTask<String,Integer,Boolean> {
#Override
protected Boolean doInBackground(final String... bookid) {
if(filePath != null) {
mStorageRef.child(bookid[0]).putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Toast.makeText(UploadBook.this, "Upload successful", Toast.LENGTH_SHORT).show();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadBook.this, "Upload Failed : " + e, Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
}
class t3 extends AsyncTask<String,Integer,Boolean>{
#Override
protected Boolean doInBackground(String... strings) {
publishProgress();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
etName.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("name","Delault name"));
etEmail.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("email","Default email"));
etUniversity.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("university","Default university"));
etMobile.setText(String.valueOf(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("phone","Default phone")));
}
}
and my Adapter class is
public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
ArrayList<Books> bookslist;
CardView cv;
FirebaseAuth fauth;
FirebaseDatabase database;
DatabaseReference dbreference;
Books b;
public SubjectBooksAdapter(ArrayList<Books> bookslist){
this.bookslist = bookslist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bookName,bookAuthor,bookDesc,bookPrice,bookCall;
ImageView iv;
MyViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.my_card_view);
iv = (ImageView) itemView.findViewById(R.id.imageView);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
bookName = (TextView) itemView.findViewById(R.id.bookName);
bookAuthor = (TextView) itemView.findViewById(R.id.bookAuthor);
bookDesc = (TextView) itemView.findViewById(R.id.bookDesc);
bookPrice = (TextView) itemView.findViewById(R.id.bookPrice);
bookCall = (TextView) itemView.findViewById(R.id.bookCall);
fauth = FirebaseAuth.getInstance();
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
b = bookslist.get(position);
holder.bookName.setText(b.getBname());
holder.bookAuthor.setText(b.getBauthor());
holder.bookDesc.setText(b.getBdesc());
holder.bookPrice.setText("Rs. "+b.getPrice());
holder.bookCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Log.e("Current user is ", fauth.getCurrentUser().getEmail());
b = bookslist.get(position);
String[] arr = {b.getSelleremail(),b.getSellername(),b.getBname(),b.getBauthor()};
//Log.e("Seller is ",b.getSellername());
Intent in = new Intent(v.getContext(),Chat.class);
in.putExtra("seller",arr);
v.getContext().startActivity(in);
}
});
Glide.with(cv.getContext()).load(Uri.parse(b.getPics())).placeholder(R.drawable.bshelf).error(R.drawable.bshelf).into(holder.iv);
}
#Override
public int getItemCount() {
return bookslist.size();
}
}
Please help.
Here is my whole project
https://github.com/BlueYeti1881/Pustak
Thanks in advance.
In UploadBook class change this
if(filePath != null) {
mStorageRef.child(bookid[0]).putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Toast.makeText(UploadBook.this, "Upload successful", Toast.LENGTH_SHORT).show();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
To This-
final StorageReference ref = mStorageRef.child(bookid[0]);
UploadTask uploadTask = ref.putFile(file);
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();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUri.toString());
} else {
// Handle failures
}
}
});

How to compress image while uploading to the firebase?

i am working on the a social app where the user can upload their image on their feeds but when the user is picking up the image ,the image less than 2 mb are getting picked up and are successfully uploaded to the firebase but when the user uploads the image more than 2mb the app crashes. what can be done to compress the image ..
postactivity.java
private Toolbar mToolbar;
private ImageButton SelectPostImage;
private Button UpdatePostButton;
private ProgressDialog loadingBar;
private EditText PostDescription;
private static final int Gallery_pick = 1;
private Uri ImageUri;
private String Description;
private StorageReference PostsImagesReference;
private DatabaseReference usersRef, PostsRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, saveCurrentTime,current_user_id, postRandomName, downloadUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
PostsImagesReference = FirebaseStorage.getInstance().getReference();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
SelectPostImage = (ImageButton)findViewById(R.id.select_post_image);
UpdatePostButton = (Button) findViewById(R.id.update_post_button);
PostDescription = (EditText)findViewById(R.id.post_description);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update Post");
SelectPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
UpdatePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ValidatePostInfo();
}
});
}
private void ValidatePostInfo() {
Description = PostDescription.getText().toString();
if (ImageUri == null){
Toast.makeText(this, "Please select the image", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(Description)){
Toast.makeText(this,"Please write something here",Toast.LENGTH_SHORT).show();
}else {
loadingBar.setTitle(" Add New Post");
loadingBar.setMessage("Please wait, while we updating your new post");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH: mm");
saveCurrentTime = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTime;
StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
downloadUrl = task.getResult().getDownloadUrl().toString();
Toast.makeText(PostActivity.this,"Image is sucessfully uploaded to storage",Toast.LENGTH_LONG).show();
SavingPostInformationToDatabase();
}else{
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this,"Error Occured:" + message,Toast.LENGTH_SHORT).show();
}
}
});
}
private void SavingPostInformationToDatabase() {
usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String userfullname = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
HashMap postsMap = new HashMap();
postsMap.put("uid",current_user_id);
postsMap.put("date",saveCurrentDate);
postsMap.put("time",saveCurrentTime);
postsMap.put("description",Description);
postsMap.put("postimage",downloadUrl);
postsMap.put("profileimage",userProfileImage);
postsMap.put("fullname",userfullname);
PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(PostActivity.this,"Your New Post is Updated Sucessfully",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}else{
Toast.makeText(PostActivity.this,"Error Occured while updating your post .please try again ",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_pick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_pick && resultCode == RESULT_OK && data != null){
ImageUri = data.getData();
SelectPostImage.setImageURI(ImageUri);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity() {
Intent mainintent = new Intent(PostActivity.this,MainActivity.class);
startActivity(mainintent);
}
}
byte[] thumb_byte_data;
Uri resultUri = ImageUri;
//getting imageUri and store in file. and compress to bitmap
File file_path = new File(resultUri.getPath());
try {
Bitmap thumb_bitmap = new Compressor(this)
.setMaxHeight(200)
.setMaxWidth(200)
.setQuality(75)
.compressToBitmap(file_path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
thumb_byte_data = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
You can then upload to firebase with the this code:
final UploadTask uploadTask = bytepath.putBytes(thumb_byte_data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
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();
}
// Continue with the task to get the download URL
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
You can create bitmap with captured image as below:
Bitmap bitmap = Bitmap.createScaledBitmap(yourimageuri, width, height, true);// the uri you got from onactivityresults
You can also view this thirdparty lib to compress your image Click Here
//declear local variable first
Bitmap bitmap;
Uri imageUri;
//button action to call Image picker method
companyImage.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,"Pick Comapany Image"),GALLERY_REQ_CODE);
}
});
//get bitmap from onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageURI(imageUri);
}
}
//compress image first then upload to firebase
public void postImage() {
StorageReference storageReference = mStorageRef.child("Images/" + //imageName);
databaseReference =
FirebaseDatabase.getInstance().getReference().child("Jobs").child(//imageName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(SaveJobActivity.this.getContentResolver(),bitmap,//imageName,null);
Uri uri = Uri.parse(path);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
final String downloadUrl = task.getResult().toString();
if (task.isSuccessful()){
Map<String, Object> update_hashMap = new HashMap<>();
//assign download url in hashmap to upadate database reference
update_hashMap.put("Image",downloadUrl);
//update database children here
databaseReference.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
//do what you want
}else {
//show exception
}
}
});
}else{
//show exception
}
}
});
}
});
}

For some reason on the #overide part it says 'method does not override method from it's superclass'. How do I resove this?

For some reason on the #overide part it says 'method does not override method from it's superclass'. How do I resove this?
public class Main6Activity extends AppCompatActivity {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL = "http://simplifiedcoding.16mb.com/VolleyUpload/upload.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
editTextName = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
private void uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(Main6Activity.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(Main6Activity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
//returning parameters
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
}
}
Thankyou and help would be appreciated.
For some reason on the #overide part it says 'method does not override method from it's superclass'. How do I resove this?
It means your method has its declaration imperfect, maybe missing some parts. Look to which method the error is been raised and search for the pattern declaration of this obligatory method on the web.
I assume the "does not override" complain is against the onClick() method. The AppCompatActivity does not have such method. Your Main6Activity class needs to implement the View.OnClickListener interface as follows:
public class Main6Activity extends AppCompatActivity implements View.OnClickListener {

Categories