lawang code

lawang Code


Tanyakan kode disini

simpan kemysql foto&data yg dinputkan dari android

ditanyakan oleh asywalilfikri 4 tahun yang lalu
package com.example.aa;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    public static final int MEDIA_TYPE_IMAGE = 1;
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 2;
    private static final int CROP_IMAGE_REQUEST_CODE = 3;
    private static final int PICK_FROM_GALLERY = 4;
    private Uri fileUri;
    private static final String IMAGE_DIRECTORY_NAME = "ternakku";


    Bitmap tempbmp;
    EditText nama,jenis,breed;
    ImageView propic;
    String url = "";
    Button submit;
    boolean isImageSet = false;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        nama = (EditText) findViewById(R.id.namaternak);
        jenis = (EditText) findViewById(R.id.jenisternak);
        breed = (EditText) findViewById(R.id.breed);
        propic = (ImageView) findViewById(R.id.img_profpic);

        propic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                selectImage();
            }
        });

        submit = (Button) findViewById(R.id.btn_submit);
        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if(!nama.getText().toString().equals("") && !jenis.getText().toString().equals("") && !breed.getText().toString().equals("")){
                    new postReg().execute();
                }else{
                    Toast.makeText(getApplicationContext(), "isi semua form tambah ternak", Toast.LENGTH_SHORT).show();
                }

            }
        });



    }

    public class postReg extends AsyncTask<String, Void, Void> {

        private ProgressDialog dialog;
        boolean isDone = false;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Proses Tambah Ternak  ...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub

            String url = "http://10.0.2.2/login/tambahTernak.php";

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            tempbmp.compress(Bitmap.CompressFormat.JPEG, 100, stream); 

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            byte[] byte_arr = stream.toByteArray();

            String strnama = nama.getText().toString();
            String image_str = Base64.encodeBytes(byte_arr);
            String image_name = "IMG_" + timeStamp + "_"+ strnama +".jpg";

            String strbreed = breed.getText().toString();
            String strjenis = jenis.getText().toString();


            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);

            nameValuePairs.add(new BasicNameValuePair("image",image_str));
            nameValuePairs.add(new BasicNameValuePair("image_name", image_name));
            nameValuePairs.add(new BasicNameValuePair("jenis",strjenis));
            nameValuePairs.add(new BasicNameValuePair("breed", strbreed));
            nameValuePairs.add(new BasicNameValuePair("name", strnama));
            return null;    


            }




        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dialog.dismiss();
            if(isDone){

                Intent i = new Intent(MainActivity.this, MainActivity.class);
                i.putExtra("next", "Menu Activity");
                startActivity(i);
                finish();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                // display it in image view
                cropCapturedImage(fileUri);
                isImageSet = true;

            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "Gagal mnyimpan gambar", Toast.LENGTH_SHORT)
                        .show();
                //finish();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "maaf gagal mengambil gambar", Toast.LENGTH_SHORT)
                        .show();
            }
        }

        if (requestCode == CROP_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Bundle extras = data.getExtras();

                tempbmp = extras.getParcelable("data");
                propic.setImageBitmap(tempbmp);

            }
        }

        if(requestCode == PICK_FROM_GALLERY){
            if (resultCode == RESULT_OK) {
                previewPickImage(data);
                isImageSet = true;
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
                //finish();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }

        }

    }

     private void selectImage() {

            final CharSequence[] options = { "Ambil Foto", "Pilih dari Gallery","Batal" };

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Tambah Foto!");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Ambil Foto"))
                    {
                      takePicture();
                    }
                    else if (options[item].equals("Pilih dari Gallery"))
                    {
                        openGallery();
                    }
                    else if (options[item].equals("Batal")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case android.R.id.home:
            Intent i = new Intent(MainActivity.this, MainActivity.class); //
            startActivity(i);
            finish();
            return true;


        }
        return super.onOptionsItemSelected(item);
    }

     private void previewPickImage(Intent data) {
            try {
                // hide video preview

                propic.setVisibility(View.VISIBLE);

                Bundle extras2 = data.getExtras();
                if (extras2 != null) {
                    tempbmp = extras2.getParcelable("data");
                    // bimatp factory
                    propic.setImageBitmap(tempbmp);

                }

            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

     public void cropCapturedImage(Uri picUri) {
            // call the standard crop action intent
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri of image
            cropIntent.setDataAndType(picUri, "image/*");
            // set crop properties
            cropIntent.putExtra("crop", "true");
            // indicate aspect of desired crop
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            // indicate output X and Y
            cropIntent.putExtra("outputX", 600); //600
            cropIntent.putExtra("outputY", 550); //550
            cropIntent.putExtra("scale", true);
            cropIntent.putExtra("scaleUpIfNeeded", true);
            // retrieve data on return
            cropIntent.putExtra("return-data", true);
            // start the activity - we handle returning in onActivityResult
            startActivityForResult(cropIntent, CROP_IMAGE_REQUEST_CODE);
        }

        public void takePicture(){
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            startActivityForResult(intent,
                    CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
        }

        public void openGallery(){

            Intent intent = new Intent();
            // call android default gallery
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);

            // ******** code for crop image
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 600);
            intent.putExtra("outputY", 550);
            intent.putExtra("scale", true);
            intent.putExtra("scaleUpIfNeeded", true);

            try {

                intent.putExtra("return-data", true);
                startActivityForResult(intent, PICK_FROM_GALLERY);

            } catch (ActivityNotFoundException e) {
                // Do nothing for now
            }
        }

  /*HELPER*/

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }

    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else {
            return null;
        }

        return mediaFile;
    }

}


Menampilkan 1-1 dari 1 hasil
handita okviyanto menjawab 4 tahun yang lalu :

Ini mau ngapain gan?


Anda harus login terlebih dahulu untuk memberikan komentar

Recent Tag

X 6
X 48
X 14
X 10
X 1
X 5
X 4
X 18
X 10

Bantuan

Help

Feedback

Help