0

Jeder, ich brauche Datei umbenennen, bevor Firebase Speicher mit mehreren Bild-Upload und codieren zu sha-1(Bildname + uid + aktuelle Zeit) Hochladen :Android - Firebase umbenennen Datei (SHA-1) vor dem Hochladen

915731b2094b1cb23c1b176ef8633947f737804b, fdf15718d6d988ce188bdc8debcb7d5998229db3

Multi Bild auswählen i von diesem Link erhalten https://github.com/donglua/PhotoPicker

Mainboard Beitrag Klasse (Klasse Firebase Lagerung und Stempel auf Firebase Datenbank Beiträge zu schreiben, aber jetzt muss ich

nicht setzen sha1hash auf Firebase Datenbank

private static final String TAG = "MainboardPost"; 
private static final int MAP_REQUEST_CODE = 334; 
private static final int ADD_PHOTO_REQUEST = 335; 
private Toolbar toolbar; 
private TextView cancle; 
private Mainboard post; 
private PhotoAdapter photoAdapter; 
private ArrayList<String> selectedPhotos = new ArrayList<>(); 
Button img_btn,map_btn,removeMapBtn; 
RelativeLayout layout_img , layout_map ; 
private RecyclerView recyclerView; 
EditText header , body; 

private UploadTask mUploadtask; 

ImageButton addMapBtn; 
FrameLayout frameLayout; 

private FirebaseStorage storageRef; 
private StorageReference mStorage , folderRef; 
private DatabaseReference mDatabase; 

// รับค่าlat lon เพื่อโพส 
private String loc_latlon; 
private String loc_address; 

private FirebaseAuth mAuth; 

GoogleMap map; 
Marker mMarker; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.view_mainbard_post); 
    toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar 
    setSupportActionBar(toolbar); // Class Actionbar ให้ใช้ Toolbar แทนของระบบ 
    getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar 


    mAuth = FirebaseAuth.getInstance(); 

    mDatabase = FirebaseDatabase.getInstance().getReference(); 

    storageRef = FirebaseStorage.getInstance(); 
    mStorage = storageRef.getReference(); 
    folderRef = mStorage.child("mainboard"); 


    frameLayout = (FrameLayout)findViewById(R.id.map_frame); 
    removeMapBtn = (Button)findViewById(R.id.remove_btn); 
    addMapBtn = (ImageButton)findViewById(R.id.addmap_btn); 
    layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo); 
    layout_map = (RelativeLayout)findViewById(R.id.layout_add_map); 
    recyclerView = (RecyclerView)findViewById(R.id.addimg_view); 
    header = (EditText)findViewById(R.id.topic); 
    body = (EditText)findViewById(R.id.detail); 
    photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos); 

    img_btn = (Button)findViewById(R.id.add_img); 
    img_btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      layout_img.setVisibility(View.VISIBLE); 
      layout_map.setVisibility(View.GONE); 
     } 
    }); 
    map_btn = (Button)findViewById(R.id.add_map); 
    map_btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      layout_map.setVisibility(View.VISIBLE); 
      layout_img.setVisibility(View.GONE); 

     } 
    }); 

    cancle = (TextView) findViewById(R.id.toolbar_cancle); 
    cancle.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      finish(); 
     } 
    }); 


    addMapBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(MainboardPost.this, MapsActivity.class); 
      startActivityForResult(intent, MAP_REQUEST_CODE); 
     } 
    }); 

    removeMapBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      frameLayout.setVisibility(View.GONE); 
      addMapBtn.setVisibility(View.VISIBLE); 
     } 
    }); 

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL)); 
    recyclerView.setAdapter(photoAdapter); 

    recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this, 
      new RecyclerItemClick.OnItemClickListener() { 
       @Override 
       public void onItemClick(View view, int position) { 
        if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) { 
         PhotoPicker.builder() 
           .setPhotoCount(PhotoAdapter.MAX) 
           .setShowCamera(true) 
           .setPreviewEnabled(false) 
           .setSelected(selectedPhotos) 
           .start(MainboardPost.this, REQUEST_CODE); 
        } else { 
         PhotoPreview.builder() 
           .setPhotos(selectedPhotos) 
           .setCurrentItem(position) 
           .start(MainboardPost.this, REQUEST_CODE); 
        } 
       } 
      })); 

    setUpGoogleMap(); 

} 

//Menu Item ขวามือสุดของ Toolbar 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.menu_post, menu); 
    return true; 
} 

private void setUpGoogleMap() { 
    if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) { 

     SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2)); 
     map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method 
    } 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    switch (requestCode) { 
     case MAP_REQUEST_CODE: 
      if (resultCode == Activity.RESULT_OK) { 
       //Location Fetched 
       double lat = data.getDoubleExtra("location_lat", 0); 
       double lng = data.getDoubleExtra("location_lng", 0); 

       loc_latlon = lat + "," + lng; 

       Log.e("Selected Lat-lng", lat + " - " + lng); 
       frameLayout.setVisibility(View.VISIBLE); 
       addMapBtn.setVisibility(View.GONE); 
       //Here after getting lat lng add marker to ur google map using fetched lat lng 
       setPickedLocationOverMap(lat, lng); 
       // 
      } 
      break; 
     case REQUEST_CODE: 
      if (resultCode == RESULT_OK && 
        (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) { 
       List<String> photos = null; 
       if (data != null) { 
        photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS); 
       } 
       selectedPhotos.clear(); 

       if (photos != null) { 

        selectedPhotos.addAll(photos); 
       } 
       photoAdapter.notifyDataSetChanged(); 
      } 
      break; 
    } 
} 

private void setPickedLocationOverMap(double lat, double lng) { 
    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls 
    MapsInitializer.initialize(this.getApplicationContext()); 
    // Updates the location and zoom of the MapView 
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17); 
    if (map != null) 
     map.animateCamera(cameraUpdate); 

} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    this.map = googleMap; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    submitPost(); 
    return true; 
} 

@Override 
public void onClick(View view) { 
    switch (view.getId()){ 
     case R.id.button_upload_resume: 
      Helper.mProgressDialog.show(); 
      mUploadtask.resume(); 
      break; 
    } 
} 

private void submitPost() { 


    final String title = header.getText().toString().trim(); 
    final String detail = body.getText().toString().trim(); 

    if (loc_latlon == null){ 
     loc_latlon = ""; 
    } 

    if (loc_address == null){ 
     loc_address = ""; 
    } 

    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){ 
     final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); 
     mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       User user = dataSnapshot.getValue(User.class); 
       if (user == null){ 
        Log.e(TAG, "User " + userId + " is unexpectedly null"); 
        Toast.makeText(MainboardPost.this, 
          "Error: could not fetch user.", 
          Toast.LENGTH_SHORT).show(); 

       }else { 
        writenewpost(title , detail , loc_latlon , loc_address); 

       } 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 
       Log.w(TAG, "getUser:onCancelled", databaseError.toException()); 
      } 
     }); 
    } 
    for (String imagePath : selectedPhotos){ 
     Uri file = Uri.fromFile(new File(imagePath)); 
     StorageReference imageRef = folderRef.child(file.getLastPathSegment()); 
     mUploadtask = imageRef.putFile(file); 

    } 

} 

private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress) 

{ 

    String key = mDatabase.child("mainboard").push().getKey(); 
    PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress); 

    Map<String, Object>postvalue = mainboard_post.toMap(); 
    Map<String, Object>childUpdates = new HashMap<>(); 
    childUpdates.put("/mainboard/" + key , postvalue); 

    mDatabase.updateChildren(childUpdates); 
} 

Mainboard Beitrag Modell

public String mb_address; 
public String mb_body; 
public String mb_location; 
public String mb_pic; 
public String mb_title ; 

public PostMainboard(){ 

} 

public PostMainboard(String mb_title ,String mb_body,String mb_location,String mb_address , String mb_pic) 

{ 
    this.mb_address = mb_address; 
    this.mb_body = mb_body; 
    this.mb_location = mb_location; 
    this.mb_pic = mb_pic; 
    this.mb_title = mb_title; 
} 

@Exclude 
public Map<String , Object> toMap(){ 
    HashMap<String, Object> result = new HashMap<>(); 
    result.put("mb_title" , mb_title); 
    result.put("mb_body" , mb_body); 
    result.put("mb_location" , mb_location); 
    result.put("mb_address" , mb_address); 
    result.put("mb_pic" , mb_pic); 
    return result; 
} 

}

Antwort

2

Im Folgenden finden Sie eine Support-Klasse zum Erstellen eines SHA-1-Zertifikats. Das ist vielleicht hilfreich für dich.

1. Erstellen Sie einen class mit dem Namen SHA1Hash.java und fügen Sie den folgenden Code ein. Importiert notwendiges Paket.

public class SHA1Hash { 

    private static String convertToHex(byte[] data) { 
     StringBuilder buf = new StringBuilder(); 
     for (byte b : data) { 
      int halfbyte = (b >>> 4) & 0x0F; 
      int two_halfs = 0; 
      do { 
       buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10))); 
       halfbyte = b & 0x0F; 
      } while (two_halfs++ < 1); 
     } 
     return buf.toString(); 
    } 

    public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { 
     MessageDigest md = MessageDigest.getInstance("SHA-1"); 
     md.update(text.getBytes("iso-8859-1"), 0, text.length()); 
     byte[] sha1hash = md.digest(); 
     return convertToHex(sha1hash); 
    } 
} 

2. Verwenden Sie wie unten dieser Aufruf Methode SHA1-Zertifikat Mit Datetime und Ihre erforderlichen String-Wert zu erstellen.

 public static String getDateTimeHash(String uid, String imageName){ 
      final String HASH_KEY = uid+imageName; 
      String hashString = ""; 
      String timeInMilliSeconds = String.valueOf(System.currentTimeMillis()); 
      try { 
       hashString = SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY)); 
      } catch (NoSuchAlgorithmException e) { 
       e.printStackTrace(); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
      Log.d("Utils","Hash Value is "+hashString); 
      return hashString ; 
     } 

die Verwendungen Verfahren nach Ihrem Bedarf bearbeitet werden. Sie können imageName+uid+currentTime als String passieren, wie die Methode String Typ Wert nimmt

Ihre endgültige Code:

private static final String TAG = "MainboardPost"; 
private static final int MAP_REQUEST_CODE = 334; 
private static final int ADD_PHOTO_REQUEST = 335; 
private Toolbar toolbar; 
private TextView cancle; 
private Mainboard post; 
private PhotoAdapter photoAdapter; 
private ArrayList<String> selectedPhotos = new ArrayList<>(); 
Button img_btn,map_btn,removeMapBtn; 
RelativeLayout layout_img , layout_map ; 
private RecyclerView recyclerView; 
EditText header , body; 

private UploadTask mUploadtask; 

ImageButton addMapBtn; 
FrameLayout frameLayout; 

private FirebaseStorage storageRef; 
private StorageReference mStorage , folderRef; 
private DatabaseReference mDatabase; 

// รับค่าlat lon เพื่อโพส 
private String loc_latlon; 
private String loc_address; 

private FirebaseAuth mAuth; 

GoogleMap map; 
Marker mMarker; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.view_mainbard_post); 
    toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar 
    setSupportActionBar(toolbar); // Class Actionbar ให้ใช้ Toolbar แทนของระบบ 
    getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar 


    mAuth = FirebaseAuth.getInstance(); 

    mDatabase = FirebaseDatabase.getInstance().getReference(); 

    storageRef = FirebaseStorage.getInstance(); 
    mStorage = storageRef.getReference(); 
    folderRef = mStorage.child("mainboard"); 


    frameLayout = (FrameLayout)findViewById(R.id.map_frame); 
    removeMapBtn = (Button)findViewById(R.id.remove_btn); 
    addMapBtn = (ImageButton)findViewById(R.id.addmap_btn); 
    layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo); 
    layout_map = (RelativeLayout)findViewById(R.id.layout_add_map); 
    recyclerView = (RecyclerView)findViewById(R.id.addimg_view); 
    header = (EditText)findViewById(R.id.topic); 
    body = (EditText)findViewById(R.id.detail); 
    photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos); 

    img_btn = (Button)findViewById(R.id.add_img); 
    img_btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      layout_img.setVisibility(View.VISIBLE); 
      layout_map.setVisibility(View.GONE); 
     } 
    }); 
    map_btn = (Button)findViewById(R.id.add_map); 
    map_btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      layout_map.setVisibility(View.VISIBLE); 
      layout_img.setVisibility(View.GONE); 

     } 
    }); 

    cancle = (TextView) findViewById(R.id.toolbar_cancle); 
    cancle.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      finish(); 
     } 
    }); 


    addMapBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(MainboardPost.this, MapsActivity.class); 
      startActivityForResult(intent, MAP_REQUEST_CODE); 
     } 
    }); 

    removeMapBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      frameLayout.setVisibility(View.GONE); 
      addMapBtn.setVisibility(View.VISIBLE); 
     } 
    }); 

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL)); 
    recyclerView.setAdapter(photoAdapter); 

    recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this, 
      new RecyclerItemClick.OnItemClickListener() { 
       @Override 
       public void onItemClick(View view, int position) { 
        if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) { 
         PhotoPicker.builder() 
           .setPhotoCount(PhotoAdapter.MAX) 
           .setShowCamera(true) 
           .setPreviewEnabled(false) 
           .setSelected(selectedPhotos) 
           .start(MainboardPost.this, REQUEST_CODE); 
        } else { 
         PhotoPreview.builder() 
           .setPhotos(selectedPhotos) 
           .setCurrentItem(position) 
           .start(MainboardPost.this, REQUEST_CODE); 
        } 
       } 
      })); 

    setUpGoogleMap(); 

} 

//Menu Item ขวามือสุดของ Toolbar 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.menu_post, menu); 
    return true; 
} 

private void setUpGoogleMap() { 
    if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) { 

     SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2)); 
     map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method 
    } 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    switch (requestCode) { 
     case MAP_REQUEST_CODE: 
      if (resultCode == Activity.RESULT_OK) { 
       //Location Fetched 
       double lat = data.getDoubleExtra("location_lat", 0); 
       double lng = data.getDoubleExtra("location_lng", 0); 

       loc_latlon = lat + "," + lng; 

       Log.e("Selected Lat-lng", lat + " - " + lng); 
       frameLayout.setVisibility(View.VISIBLE); 
       addMapBtn.setVisibility(View.GONE); 
       //Here after getting lat lng add marker to ur google map using fetched lat lng 
       setPickedLocationOverMap(lat, lng); 
       // 
      } 
      break; 
     case REQUEST_CODE: 
      if (resultCode == RESULT_OK && 
        (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) { 
       List<String> photos = null; 
       if (data != null) { 
        photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS); 
       } 
       selectedPhotos.clear(); 

       if (photos != null) { 

        selectedPhotos.addAll(photos); 
       } 
       photoAdapter.notifyDataSetChanged(); 
      } 
      break; 
    } 
} 

private void setPickedLocationOverMap(double lat, double lng) { 
    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls 
    MapsInitializer.initialize(this.getApplicationContext()); 
    // Updates the location and zoom of the MapView 
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17); 
    if (map != null) 
     map.animateCamera(cameraUpdate); 

} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    this.map = googleMap; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    submitPost(); 
    return true; 
} 

@Override 
public void onClick(View view) { 
    switch (view.getId()){ 
     case R.id.button_upload_resume: 
      Helper.mProgressDialog.show(); 
      mUploadtask.resume(); 
      break; 
    } 
} 

private void submitPost() { 


    final String title = header.getText().toString().trim(); 
    final String detail = body.getText().toString().trim(); 
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); 

    if (loc_latlon == null){ 
     loc_latlon = ""; 
    } 

    if (loc_address == null){ 
     loc_address = ""; 
    } 

    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){ 

     mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       User user = dataSnapshot.getValue(User.class); 
       if (user == null){ 
        Log.e(TAG, "User " + userId + " is unexpectedly null"); 
        Toast.makeText(MainboardPost.this, 
          "Error: could not fetch user.", 
          Toast.LENGTH_SHORT).show(); 

       }else { 
        writenewpost(title , detail , loc_latlon , loc_address); 

       } 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 
       Log.w(TAG, "getUser:onCancelled", databaseError.toException()); 
      } 
     }); 
    } 
    for (String imagePath : selectedPhotos){ 
     Uri file = Uri.fromFile(new File(imagePath)); 
     String imageName=imagePath.substring(imagePath.lastIndexOf("/")+1); 
     Log.d("ImageName" , imageName) ; 
     String hashImageName = getDateTimeHash(userId, imageName); 
     Log.d("HashImageName" , hashImageName); 
     StorageReference imageRef = folderRef.child(hashImageName); 
     mUploadtask = imageRef.putFile(file); 

    } 

} 

private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress) 

{ 

    String key = mDatabase.child("mainboard").push().getKey(); 
    PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress); 

    Map<String, Object>postvalue = mainboard_post.toMap(); 
    Map<String, Object>childUpdates = new HashMap<>(); 
    childUpdates.put("/mainboard/" + key , postvalue); 

    mDatabase.updateChildren(childUpdates); 
} 

public static String getDateTimeHash(String uid, String imageName){ 
      final String HASH_KEY = uid+imageName; 
      String hashString = ""; 
      String timeInMilliSeconds = String.valueOf(System.currentTimeMillis()); 
      try { 
       hashString = SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY)); 
      } catch (NoSuchAlgorithmException e) { 
       e.printStackTrace(); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
      Log.d("Utils","Hash Value is "+hashString); 
      return hashString ; 
     } 

Hoffnung, dies für Sie hilfreich ist. Danke

+0

Danke für die Antwort, aber ich bin Neuling für das ich die Klasse erstellen und wie kann ich in meinem Code verwenden –

+0

ok lassen Sie mich überprüfen Sie Ihren Code und erhalten Sie die ImageName und UID für Sie. @ C.Junior wo bekomme ich imageName & uid in deiner Klasse. –

+0

Ich habe den Funktionsparameter bearbeitet, jetzt benutze diese Methode nur, indem du deine UID und ImageName übergibst, es gibt einen sha1 Schlüssel als String zurück. Sie können diese Funktion in jeder beliebigen Klasse oder Aktivität verwenden. –

Verwandte Themen