我是编程的新手。我正在尝试组合两个活动,以便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
}
}
CreateNewProduct.java
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();
}
}
}
如何将工具CameraActivity
放到NewProductActivity
,以便我可以使用相同的布局?此外,我很难,因为这两个活动使用两个不同的urls
。我可以将两个urls
合并为一个,以便更容易,但我不知道如何替换CameraActivity中使用的网址。
我想在database
中插入名称,类型,位置,说明以及上传的图片。上传的图像链接仅在php
文件中已知。因此,如果我将两个活动结合起来,我可以使用一个php
文件来执行插入,因为只有php
文件具有图像链接。
答案 0 :(得分:0)
实际上,好的方法是将网络相关操作拆分为一个单独的类,并使用Activity中的Observer模式在网络操作完成时得到通知。
答案 1 :(得分:0)
我使用
解决了这个问题
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=mobile_no" + lineEnd); // name=mobile_no so you have to get PHP side using mobile_no
dos.writeBytes(lineEnd);
dos.writeBytes(mobile_number); // mobile_no is String variable
dos.writeBytes(lineEnd);
&#13;
这是我的最终代码,它将我的图像以及参数完美地插入到数据库中:)
NewProductActivity.java
package sp.com;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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.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.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class NewProductActivity extends Activity implements OnClickListener {
private EditText inputName;
private EditText inputLocation;
private EditText inputDesc;
String reportType;
private RadioGroup reportTypeGroup;
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
//String userId, profileDisplayName, gender, cityId, mobile,
// isMobileVerified;
private String upLoadServerUri = null;
private String imagepath = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
uploadButton = (Button) findViewById(R.id.btnCreateReport);
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.105/incidentreport2/create_product.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(NewProductActivity.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 {
// 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 = "";
switch (reportTypeGroup.getCheckedRadioButtonId()) {
case R.id.hazard:
reportType = "Hazard";
break;
case R.id.incident:
reportType = "Incident";
break;
default:
reportType = "Unknown";
break;
}
// 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=\"name\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(inputName.getText().toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=location"
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(inputLocation.getText().toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=description"
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(inputDesc.getText().toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=type"
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(reportType.toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("Content-Type: image/jpeg" + 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();
InputStream urlInputStream = conn.getInputStream();
String json = null;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(urlInputStream, "iso-8859-1"),
8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
urlInputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error",
"Error converting result " + e.toString());
}
JSONObject jObj;
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Log.d("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
Log.d("content",
"HTTP Response content is : " + json.toString() + ": "
+ 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(NewProductActivity.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// 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(NewProductActivity.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(NewProductActivity.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
}
}
&#13;