安卓系统:无法将值插入数据库


Android : Cannot insert values to database

我想将视频的路径及其缩略图都作为字符串插入到我的phpMyAdmin数据库中。问题是这些值没有存储在我的数据库中,并且我不断得到"成功":"0","消息":"缺少必需字段"。你知道为什么会发生这种事吗?

这是我使用的代码

安卓系统:

public class UploadActivity extends Activity {
        // LogCat tag
        private static final String TAG = MainActivity.class.getSimpleName();
        InputStream is =null;
        private ProgressBar progressBar;
        private String filePath = null;
        public String serverPath;
        private TextView txtPercentage;
        SQLiteDatabase db;
        private VideoView vidPreview;
        private Button btnUpload;
        long totalSize = 0;
        String thumb2string;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_upload);
            txtPercentage = (TextView) findViewById(R.id.txtPercentage);
            btnUpload = (Button) findViewById(R.id.btnUpload);
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            vidPreview = (VideoView) findViewById(R.id.videoPreview);
            // Receiving the data from previous activity
            Intent i = getIntent();
            // video path that is captured in previous activity
            filePath = i.getStringExtra("filePath");
            serverPath = i.getStringExtra("serverPath");

            if (filePath != null) {
                // Displaying video on the screen
                previewMedia();
            } else {
                Toast.makeText(getApplicationContext(),
                        "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
            }
            btnUpload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // uploading the file to server
                    new UploadFileToServer().execute();
                }
            });
        }
        /**
         * Displaying captured image/video on the screen
         * */
        private void previewMedia() {

                vidPreview.setVisibility(View.VISIBLE);
                vidPreview.setVideoPath(filePath);
                // start playing
                vidPreview.start();
        }
        /**
         * Uploading the file to server
         * */
        public class UploadFileToServer extends AsyncTask<Void, Integer, String> {
            @Override
            protected void onPreExecute() {
                // setting progress bar to zero
                progressBar.setProgress(0);
                super.onPreExecute();
            }
            @Override
            protected void onProgressUpdate(Integer... progress) {
                // Making progress bar visible
                progressBar.setVisibility(View.VISIBLE);
                // updating progress bar value
                progressBar.setProgress(progress[0]);
                // updating percentage value
                txtPercentage.setText(String.valueOf(progress[0]) + "%");
            }
            @Override
            protected String doInBackground(Void... params) {
                return uploadFile();
            }
            @SuppressWarnings("deprecation")
            public String uploadFile() {
                String responseString = null;
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
                try {
                    AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                            new AndroidMultiPartEntity.ProgressListener() {
                                @Override
                                public void transferred(long num) {
                                    publishProgress((int) ((num / (float) totalSize) * 100));
                                }
                            });
                    File sourceFile = new File(filePath);
                    // Adding file data to http body
                    entity.addPart("video", new FileBody(sourceFile));
                    totalSize = entity.getContentLength();
                    httppost.setEntity(entity);
                    // Making server call
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity r_entity = response.getEntity();
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        Bitmap thumb = ThumbnailUtils.createVideoThumbnail(filePath,
                                MediaStore.Images.Thumbnails.MINI_KIND);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        thumb.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                        byte[] thumbnailBitmapBytes = stream.toByteArray();
                        thumb2string = new String(thumbnailBitmapBytes);
                        /*db=openOrCreateDatabase("TwentyThree", Context.MODE_PRIVATE, null);
                        SQLiteStatement stmt = db.compileStatement("INSERT INTO videos (path, thumbnail) values (?, ?)");
                        stmt.bindString(1, serverPath);
                        stmt.bindBlob(2, thumbnailBitmapBytes);
                        stmt.executeInsert();*/
                        insertInto();
                        responseString = EntityUtils.toString(r_entity);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }
                } catch (ClientProtocolException e) {
                    responseString = e.toString();
                } catch (IOException e) {
                    responseString = e.toString();
                }
                return responseString;
            }
            private void insertInto() throws IOException {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("Path", "serverPath"));
                params.add(new BasicNameValuePair("Thumbnail", "thumb2string"));
                try{
                   HttpClient httpClient = new DefaultHttpClient();
                   HttpPost httpPost = new HttpPost("http://192.168.1.96:80/DBscripts/insertdb.php");
                   httpPost.setEntity(new UrlEncodedFormEntity(params));
                   HttpResponse response = httpClient.execute(httpPost);
                   HttpEntity entity = response.getEntity();
                   is = entity.getContent();
                }catch(ClientProtocolException e){
                    Log.e("ClientProtocol", "Log_tag");
                    e.printStackTrace();
                }
            }
            @Override
            protected void onPostExecute(String result) {
                Log.e(TAG, "Response from server: " + result);
                // showing the server response in an alert dialog
                showAlert(result);
                super.onPostExecute(result);
            }
        }
        /**
         * Method to show alert dialog
         * */
        private void showAlert(String message) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(message).setTitle("Response from Servers")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            UploadActivity.this.finish();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }

PHP脚本:

<?php
$con = mysqli_connect('127.0.0.1','root','pswd');
mysqli_select_db($con,"twentythree");
if (isset($_POST['Path']) && isset($_POST['Thumbnail'])) {
$path =$_POST['Path'];
$thumb =$_POST['Thumbnail'];
$query = "INSERT INTO videos(Path, Thumbnail) VALUES('".$path."','".$thumb."')";
// mysql inserting a new row
mysqli_query($con,$query);

}else{
// required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    // echoing JSON response
    echo json_encode($response);
}
?>

我设法找到了解决方案。问题出在我将字节数组编码为字符串的方式上。因此,我没有使用thumb2string = new String(thumbnailBitmapBytes);,而是使用Base64编码:thumb2string = Base64.encodeToString(thumbnailBitmapBytes, Base64.DEFAULT);