CREAT BARCODE ANDROID STUDIO & UPLOAD MYSQL STORAGE MY PHONSEL

save my storage

kali ini akan membahas tentang upload image dan membuat barcode di android studio adapun langkah yang kita harus lakukan untuk proses pengaplikasiannya.
ok bisa kita mulai

proses disini membiat kode batang atau disebut dengan QR_code di android studio setelah itu kita uplaod ke tampilan dan menyimpannya ke mysql da sedikit bantuan dengan PHP coding caranya mudah ngosah dipikirkan setelah ini kita akan simpan ke mymemory kita sendiri contohnya saja ke memory internalnya androi studio itu sendiri untuk rangkaian pengaplikasiannya seperti gambar bentuk interface pertama pada aplikasi ini.

  1. button pilihan image
  2. pembuatan kode batang qr code
  3. menyimpan storage my berkas android
  4. share ++
  5. pada gambar kita beri tampilan awal
  6. dan tombol upload
ok langsung saja ke koding pertama untuk layoout kalau nama layout bisa kita atut sendiri 

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>

<include layout="@layout/content_main" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/buttonUpload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
masuk untuk java ya 
package l.com.myusaha;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.view.View;

import l.com.myusaha.app.AppController;

public class Regiert_upload extends AppCompatActivity {

Button buttonChoose, generate, Btnstorege,BtnShare ;
FloatingActionButton buttonUpload;
Toolbar toolbar;
ImageView imageView;
EditText txt_name;
Bitmap bitmap, decoded;
int success;
int PICK_IMAGE_REQUEST = 1;
int bitmap_size = 60; // range 1 - 100

private static final String TAG = MainActivity.class.getSimpleName();

/* 10.0.2.2 adalah IP Address localhost Emulator Android Studio. Ganti IP Address tersebut dengan
IP Address Laptop jika di RUN di HP/Genymotion. HP/Genymotion dan Laptop harus 1 jaringan! */
private String UPLOAD_URL = "http://192.168.43.233/ANDROID/Usahaku/upload_image/Upload_Profile.php";

private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String KEY_IMAGE = "image";
private String KEY_NAME = "username";

String tag_json_obj = "json_obj_req";

String teksbarcode;
private static final int WRITE_EXTERNAL_STORAGE_CODE = 1;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regiert_upload);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==
PackageManager.PERMISSION_DENIED){
String[] permission = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission,WRITE_EXTERNAL_STORAGE_CODE);
}
}

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

buttonChoose = (Button) findViewById(R.id.buttonChoose);
Btnstorege = (Button) findViewById(R.id.save_storage);
generate = (Button) findViewById(R.id.generate_barcode);
BtnShare = (Button) findViewById(R.id.btn_share);
buttonUpload = (FloatingActionButton) findViewById(R.id.buttonUpload);

txt_name = (EditText) findViewById(R.id.editText);

imageView = (ImageView) findViewById(R.id.imageView);

generate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
teksbarcode = txt_name.getText().toString();

if(txt_name.getText().toString().length()==0){
//jika form Email belum di isi / masih kosong
txt_name.setError("Opss Input Text");

}else {
//jika form sudah terisi semua
Toast.makeText(getApplicationContext(), "Barcode Berhasil!",
Toast.LENGTH_SHORT).show();





try {
BitMatrix bitMatrix = multiFormatWriter.encode(teksbarcode, BarcodeFormat.QR_CODE, 300,300);
BarcodeEncoder encoder = new BarcodeEncoder();
Bitmap bitmap = encoder.createBitmap(bitMatrix);
imageView.setImageBitmap(bitmap);

setToImageView(getResizedBitmap(bitmap, 512));
} catch (WriterException e) {
e.printStackTrace();
}
}
}
});


buttonChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFileChooser();
}
});

buttonUpload.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
uploadImage();
}
});
Btnstorege.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
String time = new SimpleDateFormat("yyyymmdd_HHmmss", Locale.getDefault())
.format(System.currentTimeMillis());
File path = Environment.getExternalStorageDirectory();
File dir = new File(path + "/DCIM/Myusahaku/");
dir.mkdir();
String imagename = time + ".png";
File file = new File(dir, imagename);
OutputStream out;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(Regiert_upload.this, "Image Save in DCIM", Toast.LENGTH_SHORT).show();

} catch (Exception e) {
Toast.makeText(Regiert_upload.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
BtnShare.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
//get image as imageq
Drawable drawable=imageView.getDrawable();
Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();

try {
File file = new File(getApplicationContext().getExternalCacheDir(), File.separator +"myusahaku.jpg");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri photoURI = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID +".provider", file);

intent.putExtra(Intent.EXTRA_STREAM, photoURI);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/jpg");

startActivity(Intent.createChooser(intent, "Share image via"));
} catch (Exception e) {
e.printStackTrace();
}

}
});

}



public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}

private void uploadImage() {
//menampilkan 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 response) {
Log.e(TAG, "Response: " + response.toString());

try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);

if (success == 1) {
Log.e("v Add", jObj.toString());

Toast.makeText(Regiert_upload.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

kosong();

} else {
Toast.makeText(Regiert_upload.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}

//menghilangkan progress dialog
loading.dismiss();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//menghilangkan progress dialog
loading.dismiss();

//menampilkan toast
Toast.makeText(Regiert_upload.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, error.getMessage().toString());
}
}) {
@Override
protected Map<String, String> getParams() {
//membuat parameters
Map<String, String> params = new HashMap<String, String>();

//menambah parameter yang di kirim ke web servis
params.put(KEY_IMAGE, getStringImage(decoded));
params.put(KEY_NAME, txt_name.getText().toString().trim());

//kembali ke parameters
Log.e(TAG, "" + params);
return params;
}
};

AppController.getInstance().addToRequestQueue(stringRequest, tag_json_obj);
}

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 {
//mengambil fambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// 512 adalah resolusi tertinggi setelah image di resize, bisa di ganti.
setToImageView(getResizedBitmap(bitmap, 512));
} catch (IOException e) {
e.printStackTrace();
}
}
}

private void kosong() {
imageView.setImageResource(0);
txt_name.setText(null);
}

private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));

//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}

// fungsi resize image
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();

float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}

}
maniferst
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="l.com.myusaha">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
android:name=".app.AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".data_Profil"></activity>
<activity
android:name=".Regiert_upload"
android:label="@string/title_activity_regiert_upload"
android:theme="@style/AppTheme.NoActionBar" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".camera" />
<activity android:name=".Login"/>
<activity android:name=".MainActivity" />
<activity android:name=".Register" />

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_path" />
</provider>
</application>

</manifest>
lebih kurang seperti itu dan jika berkenan untuk file atau source kode jika berkenan download disini ya,,

Comments

Post a Comment

Popular posts from this blog

MENENTUKAN BILANGAN GANJIL DAN GENAP DI EMULATOR ANDROID AVD

MULTI USER FOR ANDROID STUDIO WITH MYSQL