Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何组合2个Java类?_Java_Php_Android_Database_Android Activity - Fatal编程技术网

如何组合2个Java类?

如何组合2个Java类?,java,php,android,database,android-activity,Java,Php,Android,Database,Android Activity,我是个编程新手。我正在尝试合并两个活动,以便NewProductActivity将执行CameraActivity中的功能。两者都使用一个链接将其指向php页面,以将数据上载到服务器数据库中。请帮忙 CameraActivity.java package sp.com; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.HttpURLConn

我是个编程新手。我正在尝试合并两个活动,以便NewProductActivity将执行CameraActivity中的功能。两者都使用一个链接将其指向php页面,以将数据上载到服务器数据库中。请帮忙

CameraActivity.java

package sp.com;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CameraActivity extends Activity implements OnClickListener{

    private TextView messageText;
    private Button uploadButton, btnselectpic;
    private ImageView imageview;
    private int serverResponseCode = 0;
    private ProgressDialog dialog = null;
    public static final String cameraUrl = "android.intent.extra.CAMERA_URL";

    private String upLoadServerUri = null;
    private String imagepath=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_activity);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);
        btnselectpic = (Button)findViewById(R.id.button_selectpic);
        imageview = (ImageView)findViewById(R.id.imageView_pic);

        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        //upLoadServerUri = "http://192.168.0.100/incidentreport2/UploadToServer.php";
        upLoadServerUri = "http://172.20.10.3/incidentreport2/UploadtoServer.php";

    }


    @Override
    public void onClick(View arg0) {
        if(arg0==btnselectpic)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
        }
        else if (arg0==uploadButton) {

             dialog = ProgressDialog.show(CameraActivity.this, "", "Uploading file...", true);
             messageText.setText("uploading started.....");
             new Thread(new Runnable() {
                 public void run() {

                      uploadFile(imagepath);

                 }
               }).start();     
        }

    } 

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
            messageText.setText("Uploading file path:" +imagepath);

        }
    }
         public String getPath(Uri uri) {
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }

    public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;

          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 

          if (!sourceFile.isFile()) {

               dialog.dismiss(); 

               Log.e("uploadFile", "Source File not exist :"+imagepath);

               runOnUiThread(new Runnable() {
                   public void run() {
                       messageText.setText("Source File not exist :"+ imagepath);
                   }
               }); 

               return 0;

          }
          else
          {
               try { 

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection(); 
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("uploaded_file", fileName); 

                   dos = new DataOutputStream(conn.getOutputStream());

                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                             + fileName + "\"" + lineEnd);

                   dos.writeBytes(lineEnd);

                   // create a buffer of  maximum size
                   bytesAvailable = fileInputStream.available(); 

                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   buffer = new byte[bufferSize];

                   // read file and write it into form...
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                   while (bytesRead > 0) {

                     dos.write(buffer, 0, bufferSize);
                     bytesAvailable = fileInputStream.available();
                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                    }

                   // send multipart form data necesssary after file data...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                   // Responses from the server (code and message)
                   serverResponseCode = conn.getResponseCode();
                   String serverResponseMessage = conn.getResponseMessage();

                   Log.i("uploadFile", "HTTP Response is : "
                           + serverResponseMessage + ": " + serverResponseCode);

                   if(serverResponseCode == 200){

                       runOnUiThread(new Runnable() {
                            public void run() {
                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                      +" F:/wamp/wamp/www/uploads";
                                messageText.setText(msg);
                                Toast.makeText(CameraActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();

                                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                                i.putExtra(cameraUrl, imagepath);
                                startActivity(i);
                            }
                        });                
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch (MalformedURLException ex) {

                  dialog.dismiss();  
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(CameraActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {

                  dialog.dismiss();  
                  e.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(CameraActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
              }
              dialog.dismiss();       
              return serverResponseCode; 

           } // End else block 
         }


}
package sp.com;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputLocation;
    EditText inputDesc;
    String reportType;
    RadioGroup reportTypeGroup;

    public static final String cameraUrl = "android.intent.extra.CAMERA_URL";
    static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    public static final int MEDIA_TYPE_IMAGE = 1;
    static final String IMAGE_DIRECTORY_NAME = "Test";
    Uri fileUri;
    ImageView ImagePreview;
    Button btnCapturePicture;
    String cameraIMG;

    // url to create new product
    private static String url_create_product = "http://172.20.10.3/incidentreport2/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            cameraIMG = extras.getString(cameraUrl);
        }

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputLocation = (EditText) findViewById(R.id.inputLocation);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        //Radio Button
        reportTypeGroup = (RadioGroup) findViewById(R.id.typeOfReport);
//      reportType = (RadioButton) reportTypeGroup.findViewById(reportTypeGroup.getCheckedRadioButtonId()); 
        reportType = "";

        //Camera
        ImagePreview = (ImageView) findViewById(R.id.ImagePreview);
        btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });     

        btnCapturePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), CameraActivity.class);
                startActivity(i);

                finish();           

                //captureImage();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
        class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Report..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {

            switch (reportTypeGroup.getCheckedRadioButtonId()) {

            case R.id.hazard:
                reportType = "Hazard";
                break;

            case R.id.incident:
                reportType = "Incident";
                break;

            default:
                reportType = "Unknown";
                break;
            }

            String name = inputName.getText().toString();
            String location = inputLocation.getText().toString();
            String description = inputDesc.getText().toString();
            String type = reportType.toString();
            String image = cameraIMG.toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("location", location));
            params.add(new BasicNameValuePair("description", description));
            params.add(new BasicNameValuePair("type", type));
            params.add(new BasicNameValuePair("image", image));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat for response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}
CreateNewProduct.java

package sp.com;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CameraActivity extends Activity implements OnClickListener{

    private TextView messageText;
    private Button uploadButton, btnselectpic;
    private ImageView imageview;
    private int serverResponseCode = 0;
    private ProgressDialog dialog = null;
    public static final String cameraUrl = "android.intent.extra.CAMERA_URL";

    private String upLoadServerUri = null;
    private String imagepath=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_activity);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);
        btnselectpic = (Button)findViewById(R.id.button_selectpic);
        imageview = (ImageView)findViewById(R.id.imageView_pic);

        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        //upLoadServerUri = "http://192.168.0.100/incidentreport2/UploadToServer.php";
        upLoadServerUri = "http://172.20.10.3/incidentreport2/UploadtoServer.php";

    }


    @Override
    public void onClick(View arg0) {
        if(arg0==btnselectpic)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
        }
        else if (arg0==uploadButton) {

             dialog = ProgressDialog.show(CameraActivity.this, "", "Uploading file...", true);
             messageText.setText("uploading started.....");
             new Thread(new Runnable() {
                 public void run() {

                      uploadFile(imagepath);

                 }
               }).start();     
        }

    } 

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
            messageText.setText("Uploading file path:" +imagepath);

        }
    }
         public String getPath(Uri uri) {
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }

    public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;

          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 

          if (!sourceFile.isFile()) {

               dialog.dismiss(); 

               Log.e("uploadFile", "Source File not exist :"+imagepath);

               runOnUiThread(new Runnable() {
                   public void run() {
                       messageText.setText("Source File not exist :"+ imagepath);
                   }
               }); 

               return 0;

          }
          else
          {
               try { 

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection(); 
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("uploaded_file", fileName); 

                   dos = new DataOutputStream(conn.getOutputStream());

                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                             + fileName + "\"" + lineEnd);

                   dos.writeBytes(lineEnd);

                   // create a buffer of  maximum size
                   bytesAvailable = fileInputStream.available(); 

                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   buffer = new byte[bufferSize];

                   // read file and write it into form...
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                   while (bytesRead > 0) {

                     dos.write(buffer, 0, bufferSize);
                     bytesAvailable = fileInputStream.available();
                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                    }

                   // send multipart form data necesssary after file data...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                   // Responses from the server (code and message)
                   serverResponseCode = conn.getResponseCode();
                   String serverResponseMessage = conn.getResponseMessage();

                   Log.i("uploadFile", "HTTP Response is : "
                           + serverResponseMessage + ": " + serverResponseCode);

                   if(serverResponseCode == 200){

                       runOnUiThread(new Runnable() {
                            public void run() {
                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                      +" F:/wamp/wamp/www/uploads";
                                messageText.setText(msg);
                                Toast.makeText(CameraActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();

                                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                                i.putExtra(cameraUrl, imagepath);
                                startActivity(i);
                            }
                        });                
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch (MalformedURLException ex) {

                  dialog.dismiss();  
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(CameraActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {

                  dialog.dismiss();  
                  e.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(CameraActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
              }
              dialog.dismiss();       
              return serverResponseCode; 

           } // End else block 
         }


}
package sp.com;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputLocation;
    EditText inputDesc;
    String reportType;
    RadioGroup reportTypeGroup;

    public static final String cameraUrl = "android.intent.extra.CAMERA_URL";
    static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    public static final int MEDIA_TYPE_IMAGE = 1;
    static final String IMAGE_DIRECTORY_NAME = "Test";
    Uri fileUri;
    ImageView ImagePreview;
    Button btnCapturePicture;
    String cameraIMG;

    // url to create new product
    private static String url_create_product = "http://172.20.10.3/incidentreport2/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            cameraIMG = extras.getString(cameraUrl);
        }

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputLocation = (EditText) findViewById(R.id.inputLocation);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        //Radio Button
        reportTypeGroup = (RadioGroup) findViewById(R.id.typeOfReport);
//      reportType = (RadioButton) reportTypeGroup.findViewById(reportTypeGroup.getCheckedRadioButtonId()); 
        reportType = "";

        //Camera
        ImagePreview = (ImageView) findViewById(R.id.ImagePreview);
        btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });     

        btnCapturePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), CameraActivity.class);
                startActivity(i);

                finish();           

                //captureImage();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
        class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Report..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {

            switch (reportTypeGroup.getCheckedRadioButtonId()) {

            case R.id.hazard:
                reportType = "Hazard";
                break;

            case R.id.incident:
                reportType = "Incident";
                break;

            default:
                reportType = "Unknown";
                break;
            }

            String name = inputName.getText().toString();
            String location = inputLocation.getText().toString();
            String description = inputDesc.getText().toString();
            String type = reportType.toString();
            String image = cameraIMG.toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("location", location));
            params.add(new BasicNameValuePair("description", description));
            params.add(new BasicNameValuePair("type", type));
            params.add(new BasicNameValuePair("image", image));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat for response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}
package sp.com;
导入java.util.ArrayList;
导入java.util.List;
导入org.apache.http.NameValuePair;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.*;
公共类NewProductActivity扩展了活动{
//进度对话框
私人对话;
JSONParser JSONParser=新的JSONParser();
编辑文本输入名;
编辑文本输入位置;
编辑文本输入描述;
字符串报告类型;
放射组报告类型组;
公共静态最终字符串cameraUrl=“android.intent.extra.CAMERA\u URL”;
静态最终int摄像机捕捉图像请求代码=100;
公共静态最终int媒体类型图像=1;
静态最终字符串IMAGE\u DIRECTORY\u NAME=“Test”;
urifileuri;
图像预览;
按钮btnCapturePicture;
字符串cameraIMG;
//创建新产品的url
私有静态字符串url\u创建\u产品=”http://172.20.10.3/incidentreport2/create_product.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add_产品);
Bundle extras=getIntent().getExtras();
如果(附加值!=null){
cameraIMG=extras.getString(cameraUrl);
}
//编辑文本
inputName=(EditText)findViewById(R.id.inputName);
inputLocation=(EditText)findViewById(R.id.inputLocation);
inputDesc=(EditText)findViewById(R.id.inputDesc);
//单选按钮
reportTypeGroup=(放射组)findViewById(R.id.typeOfReport);
//reportType=(RadioButton)reportTypeGroup.findViewById(reportTypeGroup.getCheckedRadioButtonId());
reportType=“”;
//摄像机
ImagePreview=(ImageView)findViewById(R.id.ImagePreview);
btnCapturePicture=(按钮)findViewById(R.id.btnCapturePicture);
//创建按钮
按钮btnCreateProduct=(按钮)findViewById(R.id.btnCreateProduct);
//按钮点击事件
btnCreateProduct.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//在后台线程中创建新产品
新建CreateNewProduct().execute();
}
});     
btnCapturePicture.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Intent i=新的Intent(getApplicationContext(),CameraActivity.class);
星触觉(i);
完成();
//captureImage();
}
});
}
/**
*创建新产品的后台异步任务
* */
类CreateNewProduct扩展了AsyncTask{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(NewProductActivity.this);
pDialog.setMessage(“创建报告…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*创造产品
* */
受保护的字符串doInBackground(字符串…args){
开关(reportTypeGroup.getCheckedRadioButtonId()){
案例R.id.危险:
reportType=“危险”;
打破
案例R.id.事件:
reportType=“事件”;
打破
违约:
reportType=“未知”;
打破
}
字符串名称=inputName.getText().toString();
字符串位置=inputLocation.getText().toString();
字符串描述=inputDesc.getText().toString();
字符串类型=reportType.toString();
字符串image=cameraIMG.toString();
//建筑参数
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“名称”),名称);
参数添加(新的BasicNameValuePair(“位置”,位置));
参数添加(新的BasicNameValuePair(“说明”,说明));
参数添加(新的BasicNameValuePair(“类型”,类型));
添加(新的BasicNameValuePair(“图像”,图像));
//获取JSON对象
//请注意,创建产品url接受POST方法
JSONObject json=jsonParser.makeHttpRequest(url\u create\u product,
“POST”,params);
//检查cat日志以获取响应
d(“创建响应”,json.toString());
//检查成功标签
试一试{
int success=json.getInt(TAG_success);
如果(成功==1){
//已成功创建产品
Intent i=新Intent(getApplicationContext(),AllProductsActivity.class);
星触觉(i);
//关闭此屏幕
完成();
}否则{
//未能创建产品
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回