如何使用PHP mysql将Android映像上传到服务器

时间:2014-06-07 04:44:26

标签: java php android mysql android-asynctask

我有一个关于将图像从android上传到服务器的问题,问题是关于android版本,我的应用程序可以在Android版本2.3上运行但不能在版本>上运行2.3。这些是我的代码

   function TambahLokasi()
{
$base = $_REQUEST["gambar"];

if (isset($base)){

$suffix = createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";

$binary = base64_decode($base);

header("Content-Type: bitmap; charset=utf-8");

$file = fopen("gambar/" . $image_name, "wb");

fwrite($file, $binary);

fclose($file);




$username = $_POST['USERNAME'];
$loc_name = $_POST['LOCATION_NAME'];
$category = $_POST['CATEGORY'];
$address = $_POST['ADDRESS'];
$city = $_POST['CITY'];
$descript = $_POST['DESCRIPTION'];
$own = $_POST['OWNER'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];


$query = "insert into location (USERNAME,LOCATION_NAME,CATEGORY,ADDRESS,CITY,DESCRIPTION,OWNER,lat,lng,gambar)values ('$username', '$loc_name', '$category', '$address','$city','$descript','$own','$lat','$lng','$image_name')";

//$query = "insert into pasien values ('','n', 'n', 'n', 'n','bar','','','n','n','n')";


$hasil = mysql_query($query);

if($hasil)
    {
    $respon["success"] = "1";
    $respon["pesan"] = "Data berhasil diinput";
    echo json_encode($respon);
    }
    else
    {
    $respon["success"] = "0";
    $respon["pesan"] = "Data gagal diinput. Mohon cek kembali.";
    echo json_encode($respon);
    die($image_name);

} 
}else {

die("No POST");
}
}

function createRandomID() {

$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";
//srand((double) microtime() * 1000000);

$i = 0;

$pass = "";

while ($i <= 5) {

$num = rand() % 33;

$tmp = substr($chars, $num, 1);

$pass = $pass . $tmp;

$i++;
}
return $pass;

} 

这是java代码

package com.adi.lib;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.adi.peta.AddLocation;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.Button;

public class HttpUploader extends AsyncTask<String, Void, String> 
{
    String ba1;
    Base64 base;
    ProgressDialog pDialog;
    Intent intent;
    AddLocation add;

    @SuppressWarnings("static-access")
    protected String doInBackground(String... path) 
    {
        String output = null;

        for(String sdPath : path)
        {

        Bitmap bmp = BitmapFactory.decodeFile(sdPath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        double width = bmp.getWidth();
        double height = bmp.getHeight();
        double ratio = 400/width;
        int newHeight = (int)(ratio*height);

        bmp = Bitmap.createScaledBitmap(bmp, 400, newHeight, true);

        bmp.compress(CompressFormat.JPEG, 90, bao);

        byte[] ba= bao.toByteArray();
        ba1 = base.encodeToString(ba, 0);

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("USERNAME", add.strUsername));
        params.add(new BasicNameValuePair("LOCATION_NAME", add.strLocName));
        params.add(new BasicNameValuePair("CATEGORY", add.strCategory));
        params.add(new BasicNameValuePair("ADDRESS", add.strAddress));
        params.add(new BasicNameValuePair("CITY", add.strCity));
        params.add(new BasicNameValuePair("DESCRIPTION", add.strDesc));
        params.add(new BasicNameValuePair("OWNER", add.strowner));
        params.add(new BasicNameValuePair("lat", add.strlat));
        params.add(new BasicNameValuePair("lng", add.strLng));
          params.add(new BasicNameValuePair("gambar", ba1));



          try
          {
              HttpClient httpclient = new DefaultHttpClient();
              HttpPost httppost = new HttpPost("http://batiktour.adi-hidayat.com/Android/AddLocation.php");

              httppost.setEntity(new UrlEncodedFormEntity(params));
              HttpResponse response = httpclient.execute(httppost);
              HttpEntity entity = response.getEntity();

              output = EntityUtils.toString(entity);
              Log.i("GET RESPONSE--",output);
              Log.e("log_tag ******", "good connection");
              bmp.recycle();
          }
          catch (Exception e)
          {
              Log.e("log_tag ******",
                        "Error in http connection " + e.toString());
          }
        }
        return output;
    }

}

AddLocation.java

package com.adi.peta;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.ErrorManager;
import android.widget.AdapterView.OnItemSelectedListener;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.w3c.dom.Text;

import com.adi.lib.HttpUploader;
import com.adi.lib.JSONParser;
import com.adi.lib.SessionManager;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.R.string;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.widget.AdapterView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddLocation extends FragmentActivity implements LocationListener
        {

    Uri currImageURI;
    GoogleMap googlemap;
    ProgressDialog pDialog;
    SessionManager session;
    JSONParser jsonParser = new JSONParser();
    EditText loc_name, address, city, desc, owner, latitude, longitude;
    Spinner category;
    Button submit, browse, gps;
    String[] items = { "Tulis", "Cap", "Campuran" };
    String id_user, tempcate, email, name, phone;
    TextView path,status;
    String image_name;
    private static String url = "http://batiktour.adi-hidayat.com/Android/AddLocation.php";
    public static String strUsername;
    public static String strLocName;
    public static String strCategory;
    public static String strAddress;
    public static String strCity;
    public static String strDesc;
    public static String strowner;
    public static String strlat;
    public static String strLng;


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

        session = new SessionManager(getApplicationContext());
        Toast.makeText(getApplicationContext(),
                "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
                .show();

        session.checkLogin();

        HashMap<String, String> user = session.getUserDetails();

        name = user.get(SessionManager.KEY_NAME);
        email = user.get(SessionManager.KEY_USER);
        // phone = user.get(SessionManager.KEY_PHONE);

        TextView status = (TextView) findViewById(R.id.status);
        status.setText(Html.fromHtml(email));

        loc_name = (EditText) findViewById(R.id.locName);
        address = (EditText) findViewById(R.id.address);
        city = (EditText) findViewById(R.id.city);
        desc = (EditText) findViewById(R.id.desc);
        owner = (EditText) findViewById(R.id.owner);
        latitude = (EditText) findViewById(R.id.tvLAT);
        longitude = (EditText) findViewById(R.id.tvLNG);
        category = (Spinner) findViewById(R.id.category);
        submit = (Button) findViewById(R.id.submit);
        browse = (Button) findViewById(R.id.browse);
        gps = (Button) findViewById(R.id.ubahGPS);
        path = (TextView) findViewById(R.id.path);
        category = (Spinner)findViewById(R.id.category);
        ArrayAdapter aa = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, items);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        category.setAdapter(aa);

        category.setOnItemSelectedListener(new OnItemSelectedListener() 
        {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {

                strCategory = items[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }

        });

        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapTambah);

        googlemap = fm.getMap();
        googlemap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
        ImageView img = new ImageView(this);

        browse.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(
                Intent.createChooser(intent, "Select Picture"), 1);
            }
        });



        gps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                double chgLat;
                double chgLng;

                chgLat = Double.parseDouble(latitude.getText().toString());
                chgLng = Double.parseDouble(longitude.getText().toString());

                LatLng latlng = new LatLng(chgLat, chgLng);

                googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));

                googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
                googlemap.addMarker(new MarkerOptions()
                        .position(latlng)
                        .title("POSISI")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
            }
        });

        googlemap.setOnMapClickListener(new OnMapClickListener()
        {

            @Override
            public void onMapClick(LatLng latlong) 
            {
                double lat = latlong.latitude;
                double lng = latlong.longitude;


                latitude.setText(String.valueOf(lat));
                longitude.setText(String.valueOf(lng));


                MarkerOptions markerOptions = new MarkerOptions();

                // Setting the position for the marker
                markerOptions.position(latlong);

                googlemap.clear();

                // Animating to the touched position
                googlemap.animateCamera(CameraUpdateFactory.newLatLng(latlong));

                // Placing a marker on the touched position
                googlemap.addMarker(markerOptions);


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

                if(loc_name.getText().toString().trim().length()>0 && 
                           address.getText().toString().trim().length()>0 &&
                           city.getText().toString().trim().length()>0 &&
                           owner.getText().toString().trim().length()>0 &&
                           desc.getText().toString().trim().length()>0 &&
                           latitude.getText().toString().trim().length()>0 &&
                           longitude.getText().toString().trim().length()>0
                           ){

                            if (path.getText().equals("")) {
                                Toast.makeText(getApplicationContext(),
                                        "Belum Pilih Gambar", Toast.LENGTH_LONG).show();
                            } else {


                                String idUser;
                                session = new SessionManager(getApplicationContext());
                                session.checkLogin();
                                HashMap<String, String> user = session.getUserDetails();


                                idUser = user.get(SessionManager.KEY_USER);


                                 strUsername = idUser;
                                 strLocName = loc_name.getText().toString();

                                 strAddress = address.getText().toString();
                                 strCity = city.getText().toString();
                                 strDesc = desc.getText().toString();
                                 strowner = owner.getText().toString();
                                 strlat = latitude.getText().toString();
                                 strLng = longitude.getText().toString();
                                new AddLoc().execute();
                            }

                        }

                        else
                        {
                            Toast.makeText(getApplicationContext(), "Isilah yang kosong", Toast.LENGTH_LONG).show();

                        }
                    }



        });

    }



    @Override
    public void onLocationChanged(Location location) {

        EditText tvLAT = (EditText) findViewById(R.id.tvLAT);
        EditText tvLNG = (EditText) findViewById(R.id.tvLNG);
        Button gps = (Button) findViewById(R.id.ubahGPS);

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        LatLng latLng = new LatLng(latitude, longitude);

        googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));

        googlemap.addMarker(new MarkerOptions().position(latLng)
                .title("You're Here"));

        tvLAT.setText(String.valueOf(latitude));
        tvLNG.setText(String.valueOf(longitude));

    }


    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }



    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                // currImageURI is the global variable I’m using to hold the
                // content:
                currImageURI = data.getData();
                path.setText(getRealPathFromURI(currImageURI));
            }
        }
    }

    // Convert the image URI to the direct file system path of the image file
    @SuppressWarnings("deprecation")
    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        android.database.Cursor cursor = managedQuery(contentUri, proj, 
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);

    }
    class AddLoc extends AsyncTask<String, String, String> {
        String hasil,success;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AddLocation.this);
            pDialog.setMessage("Menyimpan...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

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

            HttpUploader uploader = new HttpUploader();

            try {

                image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();

            } catch (InterruptedException e) {
                Log.e("note1", "upload");
                hasil="Interupasi terdapat kesalahan";
                Log.e("kesalahan", hasil);
                finish();

            } catch (ExecutionException e) {
                Log.e("note1", "upload2");
                hasil="Eksekusi terdapat kesalahan";
                Log.e("kesalahan", hasil);
                finish();
            }
            return image_name;
        }

        protected void onPostExecute(String notifikasi) {
            pDialog.dismiss();
            Intent dash = new Intent(AddLocation.this,Dashboard.class);
            startActivity(dash);

        }

    }







}

1 个答案:

答案 0 :(得分:0)

罪魁祸首很可能与这条线有关:

image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();

您从另一个AsyncTask内部开始AsyncTask,第一个阻止,直到第二个完成。但是,来自documentation

  

从HONEYCOMB开始,任务在单个线程上执行   避免因并行执行而导致的常见应用程序错误。

由于第二个任务永远不会开始(在Android&gt; = 3.0中),第一个任务永远不会完成。

可以使用executeOnExecutor(THREAD_POOL_EXECUTOR) ...

解决此问题

...但我建议您更改代码。由于第一个任务不需要(i / o,网络)需要后台线程,因此该代码可以在UI线程中运行。提供第二个(现在是唯一的)任务,其中包含一个回调函数,以便在onPostExecute()有结果时调用它。有关此模式的一个很好的示例,请参阅android asynctask sending callbacks to ui

在AsyncTasks上使用get()很少是一个好主意。