radityakurnianto

image

Jul 24th, 2013
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.60 KB | None | 0 0
  1. package com.psn.asset;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.util.HashMap;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Vector;
  9.  
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.message.BasicNameValuePair;
  12. import org.json.JSONObject;
  13. import org.json.JSONArray;
  14. import org.json.JSONException;
  15.  
  16. import android.os.Bundle;
  17. import android.os.AsyncTask;
  18. import android.util.Log;
  19. import android.app.Activity;
  20. import android.app.ProgressDialog;
  21. import android.view.Menu;
  22. import android.view.View;
  23. import android.widget.AdapterView;
  24. import android.widget.ArrayAdapter;
  25. import android.net.Uri;
  26. import android.widget.EditText;
  27. import android.widget.AutoCompleteTextView;
  28. import android.widget.Button;
  29. import android.widget.ToggleButton;
  30. import android.widget.Spinner;
  31. import android.widget.Toast;
  32. import android.widget.ImageView;
  33. import android.content.Context;
  34. import android.content.Intent;
  35. import android.net.ConnectivityManager;
  36. import android.net.NetworkInfo;
  37. import android.location.Location;
  38. import android.location.LocationManager;
  39. import android.location.LocationListener;
  40. import android.provider.MediaStore;
  41. import android.graphics.Bitmap;
  42. import android.graphics.BitmapFactory;
  43. import android.database.Cursor;
  44.  
  45.  
  46. /**
  47.  * PSN Mobile Asset
  48.  * Copyright (c) 2013
  49.  * @author Raditya Kurnianto
  50.  */
  51.  
  52. public class Asset extends Activity {
  53.  
  54.     String sn, mn, loc, cond, notes, pht, toast, selected, type, image_name, encoded_image;
  55.     int code;
  56.     int[] imageArray = {R.id.image, R.id.image2, R.id.image3};
  57.     String[] encoded_imageArray = {};
  58.     Vector<String> vector;
  59.     Button save, browse;
  60.     ToggleButton toggle_loc;
  61.     Spinner condition;
  62.     AutoCompleteTextView material_name;
  63.     EditText serial_number, location, note, photo;
  64.     ProgressDialog pDialog;
  65.     ConnectivityManager connMgr;
  66.     NetworkInfo networkInfo;
  67.     LocationManager locManager;
  68.     LocationListener locListener;
  69.     File file;
  70.     Intent intent;
  71.     Uri selected_image;
  72.     Cursor cursor;
  73.     ImageView image, image2, image3;
  74.     ByteArrayOutputStream baos;
  75.     Bitmap imageUpload, new_image;
  76.     ArrayList<HashMap<String, String>> material;
  77.     List<String> list = null;
  78.    
  79.     private static final String url = "http://192.168.7.124/psn_asset_oracle/insert_asset.php";
  80.     private static final String url_photo = "http://192.168.7.124/psn_asset_oracle/base.php";
  81.     private static final String url_material = "http://192.168.7.124/psn_asset_oracle/getAllLocation.php";
  82.     private static final String TAG_CODE = "code";
  83.     private static final String TAG_MATERIAL_ARRAY = "material_array";
  84.     private static final String TAG_MAT_NAME = "MAT_NAME";
  85.     private static int RESULT_LOAD_IMAGE = 1;
  86.    
  87.     JSONObject json_query, json_photo;
  88.     JSONParser jsonParser = new JSONParser();
  89.    
  90.     @Override
  91.     protected void onCreate(Bundle savedInstanceState) {
  92.         super.onCreate(savedInstanceState);
  93.         setContentView(R.layout.activity_asset);
  94.         save = (Button)findViewById(R.id.save);
  95.         browse = (Button)findViewById(R.id.browse);
  96.         serial_number = (EditText)findViewById(R.id.serial_number);
  97.         material_name = (AutoCompleteTextView)findViewById(R.id.material_name);
  98.         location = (EditText)findViewById(R.id.location);
  99.         condition = (Spinner)findViewById(R.id.condition);
  100.         note = (EditText)findViewById(R.id.note);
  101.         photo = (EditText)findViewById(R.id.photo);
  102.         image = (ImageView)findViewById(R.id.image);
  103.         image2 = (ImageView)findViewById(R.id.image2);
  104.         image3 = (ImageView)findViewById(R.id.image3);
  105.        
  106.         locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  107.         locListener = new GetLocation();
  108.         locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locListener);
  109.        
  110.         /*executing new background task the application is first launch*/
  111.         new fetch_material().execute();
  112.        
  113.        
  114.         /*array adapter for spinner condition*/
  115.         ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.condition, android.R.layout.simple_spinner_item);
  116.         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  117.         condition.setAdapter(adapter);
  118.        
  119.         /*detect changes listener on spinner*/
  120.         condition.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
  121.         {
  122.             @Override
  123.             public void onItemSelected(AdapterView<?> parent, View v, int pos, long id)
  124.             {
  125.                 Object item = parent.getItemAtPosition(pos);
  126.                 selected = item.toString();
  127.             }
  128.            
  129.             @Override
  130.             public void onNothingSelected(AdapterView<?> parent)
  131.             {
  132.                 /*do nothing*/
  133.             }
  134.         });
  135.        
  136.         /*button to save*/
  137.         save.setOnClickListener(new View.OnClickListener()
  138.         {
  139.             @Override
  140.             public void onClick(View v)
  141.             {
  142.                 sn = serial_number.getText().toString();
  143.                 mn = material_name.getText().toString();
  144.                 loc = location.getText().toString();
  145.                 cond = selected;
  146.                 notes = note.getText().toString();
  147.                 pht = photo.getText().toString();
  148.                
  149.                 /*check internet connectivity*/
  150.                 connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
  151.                 networkInfo = connMgr.getActiveNetworkInfo();
  152.                 if(networkInfo != null && networkInfo.isConnected())
  153.                 {
  154.                     new addAsset().execute();
  155.                 }
  156.                 else
  157.                 {
  158.                     Toast.makeText(getApplicationContext(), "Failed! Internet Connection is needed.", Toast.LENGTH_SHORT).show();
  159.                 }
  160.             }
  161.         });
  162.        
  163.         /*this button will be remove*/
  164.         browse.setOnClickListener(new View.OnClickListener()
  165.         {
  166.             @Override
  167.             public void onClick(View v)
  168.             {
  169.                 intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  170.                 startActivityForResult(intent, RESULT_LOAD_IMAGE);
  171.             }
  172.         });
  173.     }
  174.    
  175.     /*set image view and decode to byte array stream*/
  176.     @Override
  177.     protected void onActivityResult(int requestCode, int resultCode, Intent data)
  178.     {
  179.         super.onActivityResult(requestCode, resultCode, data);
  180.         if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
  181.         {
  182.             selected_image = data.getData();
  183.             String[] filePath= {MediaStore.Images.Media.DATA};
  184.             cursor = getContentResolver().query(selected_image, filePath, null, null, null);
  185.             cursor.moveToFirst();
  186.            
  187.             int columnIndex = cursor.getColumnIndex(filePath[0]);
  188.             String picturePath = cursor.getString(columnIndex);
  189.             cursor.close();
  190.            
  191.             /*naming image to ex : psn_asset_112344215.jpg*/
  192.             image_name = "psn_asset_" + serial_number.getText().toString() + ".jpg";
  193.             photo.setText(image_name);
  194.            
  195.             /*get width and height to rescaled*/
  196.             Bitmap original_image = BitmapFactory.decodeFile(picturePath);
  197.             int width = original_image.getWidth();
  198.             int height = original_image.getHeight();
  199.             int newWidth = width / 3;
  200.             int newHeight = height / 3;
  201.             original_image.recycle();
  202.             Log.i("Before Scale", "Width = " + width + ", Height = " + height);
  203.             Log.i("After Scale", "Width = " + newWidth + ", Height = " + newHeight);
  204.            
  205.             /*scaling image*/
  206.             BitmapFactory.Options image_size = new BitmapFactory.Options();
  207.             image_size.inSampleSize = 4;
  208.             imageUpload = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(picturePath, image_size), newWidth, newHeight, false);
  209.             if(image.getDrawable() == null)
  210.             {
  211.                 image.setImageBitmap(imageUpload);
  212.             }
  213.             else if(image2.getDrawable() == null)
  214.             {
  215.                 image2.setImageBitmap(imageUpload);
  216.             }
  217.             else if(image3.getDrawable() == null)
  218.             {
  219.                 image3.setImageBitmap(imageUpload);
  220.             }
  221.         }
  222.     }
  223.    
  224.     public String[] encodeImage()
  225.     {
  226.         /*convert to byte array output stream*/
  227.         vector = new Vector<String>();
  228.         baos = new ByteArrayOutputStream();
  229.         for(int i = 1; i < imageArray.length; i++)
  230.         {
  231.             imageUpload.compress(Bitmap.CompressFormat.JPEG, 100, baos);
  232.             byte[] image_data = baos.toByteArray();
  233.             vector.add(Base64.encodeBytes(image_data));
  234.         }
  235.         for(int i = 0; i < encoded_imageArray.length ; i++){
  236.         Log.i("Encoded Image", encoded_imageArray[i]);}
  237.         return vector.toArray(encoded_imageArray);
  238.     }
  239.     /*detect selected toggle state
  240.     public void onToggleClick(View view)
  241.     {
  242.         boolean on = ((ToggleButton)view).isChecked();
  243.         if(on)
  244.         {
  245.             locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  246.             locListener = new GetLocation();
  247.             locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locListener);
  248.             Toast.makeText(getApplicationContext(), "Automatic location turning on.", Toast.LENGTH_LONG).show();
  249.         }
  250.         else
  251.         {
  252.             Toast.makeText(getApplicationContext(), "Warning. You're not turning on automatic location. Toggle the location buttoon ON to turn on.", Toast.LENGTH_LONG).show();
  253.         }
  254.     }*/
  255.    
  256.     /*async task to insert new aseet record*/
  257.     class addAsset extends AsyncTask<String, String, String>
  258.     {
  259.         @Override
  260.         protected void onPreExecute()
  261.         {
  262.             pDialog = new ProgressDialog(Asset.this);
  263.             pDialog.setMessage("Inserting..");
  264.             pDialog.setCancelable(false);
  265.             pDialog.setIndeterminate(false);
  266.             pDialog.show();
  267.         }
  268.        
  269.         @Override
  270.         protected String doInBackground(String... args)
  271.         {
  272.             Log.i("Do In Background", "Background Task Started");
  273.             try
  274.             {
  275.                 locManager.removeUpdates(locListener);
  276.                 List<NameValuePair> params = new ArrayList<NameValuePair>();
  277.                 params.add(new BasicNameValuePair("SERIAL_NUMBER", sn));
  278.                 params.add(new BasicNameValuePair("MATERIAL_NAME", mn));
  279.                 params.add(new BasicNameValuePair("LOCATION", loc));
  280.                 params.add(new BasicNameValuePair("CONDITION", cond));
  281.                 params.add(new BasicNameValuePair("NOTE", notes));
  282.                 params.add(new BasicNameValuePair("PHOTO", pht));
  283.                 json_query = jsonParser.makeHttpRequest(url, "POST", params);/*send all field to database*/
  284.                
  285.                 encodeImage();
  286.                 //ArrayList<NameValuePair> params_p = new ArrayList<NameValuePair>();
  287.                 //params_p.add(new BasicNameValuePair("image_name", image_name));/*title*/
  288.                 //params_p.add(new BasicNameValuePair("image", encoded_imageArray[0]));
  289.                 //params_p.add(new BasicNameValuePair("image", encoded_imageArray[1]));
  290.                 //params_p.add(new BasicNameValuePair("image", encoded_imageArray[2]));/*image*/
  291.                 //json_photo = jsonParser.makeHttpRequest(url_photo, "POST",params_p);/*upload image to server as binary*/
  292.                 Log.d("Create Response", json_query.toString());
  293.                 //code = json_photo.getInt(TAG_CODE);
  294.                 if(code == 1)
  295.                 {
  296.                     toast = "Success!";
  297.                 }
  298.                 else if(code == 10)
  299.                 {
  300.                     toast = "No parameter";
  301.                 }
  302.                 else if(code == 11)
  303.                 {
  304.                     toast = "Can't insert query";
  305.                 }
  306.             }
  307.             catch(Exception e)
  308.             {
  309.                 e.printStackTrace();
  310.             }
  311.             Log.i("Do In Background", "Background Task Finished");
  312.             return toast;
  313.         }
  314.        
  315.         @Override
  316.         protected void onPostExecute(String message)
  317.         {
  318.             message = toast;
  319.             Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
  320.             pDialog.dismiss();
  321.             /*clear all field*/
  322.             serial_number.setText("");
  323.             material_name.setText("");
  324.             note.setText("");
  325.             photo.setText("");
  326.             image.setImageDrawable(getResources().getDrawable(R.drawable.default_preview));
  327.         }
  328.     }
  329.  
  330.     /*get current location based on gps*/
  331.     public class GetLocation implements LocationListener
  332.     {
  333.         @Override
  334.         public void onLocationChanged(Location loc)
  335.         {
  336.             location.setText(String.valueOf(loc.getLatitude()) + ", " + String.valueOf(loc.getLongitude()));
  337.         }
  338.        
  339.         @Override
  340.         public void onProviderDisabled(String provider)
  341.         {
  342.             Toast.makeText(getApplicationContext(), "Please Enable your GPS and WiFi to improve your location accuracy", Toast.LENGTH_LONG).show();
  343.         }
  344.        
  345.         @Override
  346.         public void onProviderEnabled(String provider)
  347.         {
  348.             Toast.makeText(getApplicationContext(), "GPS Enabled\n To improve your location accuracy please enabled Wifi", Toast.LENGTH_LONG).show();
  349.         }
  350.        
  351.         @Override
  352.         public void onStatusChanged(String provider, int status, Bundle extras)
  353.         {
  354.            
  355.         }
  356.     }
  357.    
  358.     /*fetching material name from database. this class execute on every first launch*/
  359.     class fetch_material extends AsyncTask<String, String, String>
  360.     {
  361.         @Override
  362.         protected void onPreExecute()
  363.         {
  364.             pDialog = new ProgressDialog(Asset.this);
  365.             pDialog.setIndeterminate(false);
  366.             pDialog.setCancelable(false);
  367.             pDialog.setMessage("Fetching material name. Please wait..");
  368.             pDialog.show();
  369.         }
  370.        
  371.         @Override
  372.         protected String doInBackground(String... args)
  373.         {
  374.             List<NameValuePair> params = new ArrayList<NameValuePair>();
  375.             JSONObject a = jsonParser.makeHttpRequest(url_material, "GET", params);
  376.            
  377.             Log.i("Fetching Material Name", a.toString());
  378.             try
  379.             {
  380.                 int code = a.getInt(TAG_CODE);
  381.                 if(code == 1)
  382.                 {
  383.                    
  384.                     JSONArray material_array = a.getJSONArray(TAG_MATERIAL_ARRAY);
  385.                     final String[] sFinalResult = new String[material_array.length()];
  386.                     for (int i = 0;i < material_array.length();i++)
  387.                     {
  388.                         a = material_array.getJSONObject(i);
  389.                         sFinalResult[i] = a.getString(TAG_MAT_NAME);
  390.                     }
  391.                    
  392.                     list = new ArrayList<String>();
  393.                     for(int i = 0; i < sFinalResult.length;i++)
  394.                     {
  395.                         list.add(sFinalResult[i]);
  396.                     }
  397.                     toast = "Success";
  398.                 }
  399.                 else if(code == 11)
  400.                 {
  401.                     toast = "Failed";
  402.                 }
  403.             }
  404.             catch(JSONException ex)
  405.             {
  406.                 ex.printStackTrace();
  407.             }
  408.             return toast;
  409.         }
  410.        
  411.         @Override
  412.         protected void onPostExecute(String message)
  413.         {
  414.             pDialog.dismiss();
  415.             ArrayAdapter<String> adapter = new ArrayAdapter<String>(Asset.this, android.R.layout.simple_list_item_1, list);
  416.             material_name.setAdapter(adapter);
  417.             Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
  418.         }
  419.     }
  420.    
  421.     @Override
  422.     public boolean onCreateOptionsMenu(Menu menu) {
  423.         // Inflate the menu; this adds items to the action bar if it is present.
  424.         getMenuInflater().inflate(R.menu.asset, menu);
  425.         return true;
  426.     }
  427.  
  428. }
Advertisement
Add Comment
Please, Sign In to add comment