title: Decode and Show Image Thumbnail in MessageBox Android Activity Firebase
body: <p>I am following this <a href="http://www.thecrazyprogrammer.com/2016/10/android-real-time-chat-application-using-firebase-tutorial.html#comment-44484" rel="nofollow noreferrer">tutorial</a>. With this link you can see my comment for the particular problem, I followed this tutorial and I was at success to send and receive text messages on both peers. I can also see my Firebase database from console and its updating as well. Thing working fine till here.</p>
  
  <p>Now, I want to send/receive camera images to Firebase, so I found various methods to convert a image to Base64 encode string, upload that string to Firebase database, I am success at this also.</p>
  
  <p>I have successfully uploaded the encoded string to Firebase. Now as my current system is build for only text string messages application got crash when it receives encode string .</p>
  
  <ol>
  <li><p>How to decode encoded string back to bitmap?</p></li>
  <li><p>Show bitmap image thumbnail in MessageBox</p></li>
  </ol>
  
  <p>Here is my modified chat.java activity code: as a reference you can follow the provided url up for chat.java class and how it works originally, but I am unable to achieve decoding and showing bitmap thumbnail in messagebox.</p>
  
  <p><strong>chat.java</strong></p>
  
  <pre><code>public class Chat extends AppCompatActivity {
      LinearLayout layout;
      ImageView sendButton,vidcall,cam;
      public final static String AUTH_KEY_FCM = "";
      public final static String API_URL_FCM = "";
      EditText messageArea;
      ScrollView scrollView;
      Firebase reference1, reference2;
      private ConnectionDetector cd;
      String urltok;
      public static String msg;
      String tuk;
      private Uri selectedImage = null;
      private Bitmap bitmap, bitmapRotate;
      String imagepath = "";String fname;
      File file;
      private Boolean upflag = false;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.act_chat);
  
          cd = new ConnectionDetector(Chat.this);
  
          layout = (LinearLayout)findViewById(R.id.layout1);
          sendButton = (ImageView)findViewById(R.id.sendButton);
          vidcall = (ImageView)findViewById(R.id.vidBtnk);
          messageArea = (EditText)findViewById(R.id.messageArea);
          scrollView = (ScrollView)findViewById(R.id.scrollView);
          cam = (ImageView)findViewById(R.id.pictk);
  
          Firebase.setAndroidContext(this);
          reference1 = new Firebase("https://*******.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
          reference2 = new Firebase("https://*******.firebaseio.com/messages/" + UserDetails.chatWith + "_" + UserDetails.username);
  
          cd = new ConnectionDetector(getApplicationContext());
  
          sendButton.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  String messageText = messageArea.getText().toString();
                  msg = messageText;
  
                  if(!messageText.equals("")){
                      Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
                      map.put("message", messageText);
                      map.put("user", UserDetails.username);
                      reference1.push().setValue(map);
                      reference2.push().setValue(map);
                }
  
                  new RetrieveFeedTask().execute();
                  messageArea.setText("");
  
              }
          });
  
          vidcall.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  startActivity(new Intent(Chat.this, ConnectActivity.class));
              }
          });
  
  
         cam.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  Intent cameraintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                  startActivityForResult(cameraintent, 101);
              }
          });
  
          reference1.addChildEventListener(new ChildEventListener() {
              @Override
              public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                  Map map = dataSnapshot.getValue(Map.class);
                  String message = map.get("message").toString();
                  String userName = map.get("user").toString();
  
                  if(userName.equals(UserDetails.username)){
                      addMessageBox("You:-\n" + message, 1);
                     // addimagethumb(bitmapRotate,1);
                  }
                  else{
                      addMessageBox(UserDetails.chatWith + ":-\n" + message, 2);
                     // addimagethumb(bitmapRotate,2);
                  }
              }
  
              @Override
              public void onChildChanged(DataSnapshot dataSnapshot, String s) {
  
              }
  
              @Override
              public void onChildRemoved(DataSnapshot dataSnapshot) {
  
              }
  
              @Override
              public void onChildMoved(DataSnapshot dataSnapshot, String s) {
  
              }
  
              @Override
              public void onCancelled(FirebaseError firebaseError) {
  
              }
          });
      } //oncreate ends
  
  
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          try {
              switch (requestCode) {
                  case 101:
                      if (resultCode == Activity.RESULT_OK) {
                          if (data != null) {
                              selectedImage = data.getData(); // the uri of the image taken
                              if (String.valueOf((Bitmap) data.getExtras().get("data")).equals("null")) {
                                  bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
                                  } else {
                                  bitmap = (Bitmap) data.getExtras().get("data");
                                  }
                              if (Float.valueOf(getImageOrientation()) &gt;= 0) {
                                  bitmapRotate = rotateImage(bitmap, Float.valueOf(getImageOrientation()));
                                  } else {
                                  bitmapRotate = bitmap;
                                  bitmap.recycle();
                                  }
  
                             // ivImage.setVisibility(View.VISIBLE);
                              //ivImage.setImageBitmap(bitmapRotate);
  
  //                            Saving image to mobile internal memory for sometime
                              //String root = getApplicationContext().getFilesDir().toString();
  
                              String root = "/storage/emulated/0";
  
                              File myDir = new File(root + "/hidoctor");
                              myDir.mkdirs();
  
                              Random generator = new Random();
                              int n = 10000;
                              n = generator.nextInt(n);
  
  //                            Give the file name that u want
                              fname = "null" + n + ".jpg";
  
                              imagepath = root + "/hidoctor/" + fname;
                              file = new File(myDir, fname);
                              upflag = true;
                              }
                          }
                      }
              } catch (Exception e) {
              e.printStackTrace();
            }
          super.onActivityResult(requestCode, resultCode, data);
  
          if (cd.isConnectingToInternet()) {
          if (!upflag) {
          Toast.makeText(Chat.this, "Image Not Captured..!", Toast.LENGTH_LONG).show();
          } else {
          saveFile(bitmapRotate, file);
          encodeBitmapAndSaveToFirebase(bitmapRotate);
          }
          } else {
          Toast.makeText(Chat.this, "No Internet Connection !", Toast.LENGTH_LONG).show();
          }
      }
  
      public void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
              String imageEncoded = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
  
          reference1.child("imageUrl").push().setValue(imageEncoded);
          reference2.child("imageUrl").push().setValue(imageEncoded);
       }
  
       private int getImageOrientation() {
       final String[] imageColumns = {MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
      final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
      Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      imageColumns, null, null, imageOrderBy);
  
     if (cursor.moveToFirst()) {
      int orientation = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION));
       System.out.println("orientation===" + orientation);
      cursor.close();
       return orientation;
     } else {
      return 0;
      }
    }
  
  
      public static Bitmap rotateImage(Bitmap source, float angle) {
      Bitmap retVal;
  
      Matrix matrix = new Matrix();
      matrix.postRotate(angle);
      retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
          return retVal;
      }
  
      // Saving file to the mobile internal memory
      private void saveFile(Bitmap sourceUri, File destination) {
      if (destination.exists()) destination.delete();
     try {
      FileOutputStream out = new FileOutputStream(destination);
      sourceUri.compress(Bitmap.CompressFormat.JPEG, 60, out);
      out.flush();
      out.close();
      if (cd.isConnectingToInternet()) {
      //new DoFileUpload().execute();
      } else {
      Toast.makeText(Chat.this, "No Internet Connection..", Toast.LENGTH_LONG).show();
      }
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
  
      public void addimagethumb(Bitmap pic , int type){
                ImageView imgpresc = new ImageView(Chat.this);
                imgpresc.setImageBitmap(pic);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                lp.setMargins(0, 0, 0, 10);
                imgpresc.setLayoutParams(lp);
  
                if(type == 1) {
                   // textView.setBackgroundResource(R.drawable.rounded_corner1);
                }
                else{
                   // textView.setBackgroundResource(R.drawable.rounded_corner2);
                }
  
                layout.addView(imgpresc);
                scrollView.fullScroll(View.FOCUS_DOWN);
      }
  
      public void addMessageBox(String message, int type){
          TextView textView = new TextView(Chat.this);
          //ImageView imgpresc = new ImageView(Chat.this);
          textView.setText(message);
          LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
          lp.setMargins(0, 0, 0, 10);
          textView.setLayoutParams(lp);
  
          if(type == 1) {
              textView.setBackgroundResource(R.drawable.rounded_corner1);
          }
          else{
              textView.setBackgroundResource(R.drawable.rounded_corner2);
          }
  
          layout.addView(textView);
          scrollView.fullScroll(View.FOCUS_DOWN);
      }
  
  
  
   }
  </code></pre>
  
  <p>So Far I am getting this :</p>
  
  <p><a href="https://i.stack.imgur.com/9OOpW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9OOpW.png" alt="enter image description here"></a></p>
  
  <p>Now when we tap cam icon on appbar it goes to camera takes the picture and on return it saves image to device storage and encode&amp;upload to firebase after this iwant both users to see like this image </p>
  
  <p><strong>I Want like this</strong> </p>
  
  <p><a href="https://i.stack.imgur.com/iEgrq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iEgrq.png" alt="enter image description here"></a></p>
  
  <p>If you check my chat.java activity class I tried to add imageview dynamically to view but when user encode and upload the picture once and when on next session upon oncreate the activity crashed for null value . system gets confuse when retrieving the message from map for user . and all the references got lost .</p>
  
  <p>Kindly help me , I am stuck on this for more than 30 days . It will be much appreciated . Thanks</p>