如何使用AsyncTask方法将文件从android内部存储和信息上传到php mysql服务器?
我正在尝试编写一些代码,以便将文件和图片以及有关它们的一些信息一起上载,但我的尝试不起作用,并且总是如何使用AsyncTask方法将文件从android内部存储和信息上传到php mysql服务器?,php,android,mysql,android-asynctask,upload,Php,Android,Mysql,Android Asynctask,Upload,我正在尝试编写一些代码,以便将文件和图片以及有关它们的一些信息一起上载,但我的尝试不起作用,并且总是doInBackground返回空结果 以下是我的尝试: public class RegBookActivity extends Activity { private static final int SELECT_FILE_DIALOG = 1; private static final int SELECT_IMAGE_DIALOG = 302;
doInBackground
返回空结果
以下是我的尝试:
public class RegBookActivity extends Activity {
private static final int SELECT_FILE_DIALOG = 1;
private static final int SELECT_IMAGE_DIALOG = 302;
String sourceFileUri, sourceImgUri;
String[] sp1;
TextView uptxt, pathfiletxt, pathpictxt, regbookerrtxt;
Button chfilebtn, chpicbtn, regbookbtn;
EditText namketabedt, nevisandeedt, hajmedt;
ImageView upimage;
Spinner s1;
int serverResponseCode = 0;
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE_DIALOG) {
if (null == result) return;
Uri data = result.getData();
if(data.getLastPathSegment().endsWith("pdf") || data.getLastPathSegment().endsWith("mp3")){
sourceFileUri = data.getPath();
SharedPreferences upload = getSharedPreferences("uploadPrefs", 0);
SharedPreferences.Editor setedt = upload.edit();
setedt.putString("filepath", data.getPath());
setedt.commit();
pathfiletxt.setText(upload.getString("filepath", "").toString());
} else {
Toast.makeText(RegBookActivity.this, "نوع فایل انتخابی قابل قبول نیست", Toast.LENGTH_SHORT).show();
}
}
if(requestCode == SELECT_IMAGE_DIALOG){
if (null == result) return;
try {
Uri originalUri = result.getData();
String pathsegment[] = originalUri.getLastPathSegment().split(":");
String id = pathsegment[0];
final String[] imageColumns = { MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri uri = getUri();
Cursor imageCursor = RegBookActivity.this.getContentResolver().query(uri, imageColumns,
MediaStore.Images.Media._ID + "=" + id, null, null);
if (imageCursor.moveToFirst()) {
String value = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
if(value.contains("jpg") || value.contains("png")){
sourceImgUri = value;
Bitmap bitmap = BitmapFactory.decodeFile(value);
upimage.setImageBitmap(bitmap);
SharedPreferences upload = getSharedPreferences("uploadPrefs", 0);
SharedPreferences.Editor setedt = upload.edit();
setedt.putString("picpath", value);
setedt.commit();
pathpictxt.setText(upload.getString("picpath", "").toString());
} else {
Toast.makeText(RegBookActivity.this, "نوع فایل انتخابی قابل قبول نیست", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(RegBookActivity.this, "نوع فایل انتخابی قابل قبول نیست", Toast.LENGTH_LONG).show();
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_book);
namketabedt = (EditText) findViewById(R.id.editText1);
nevisandeedt = (EditText) findViewById(R.id.editText2);
hajmedt = (EditText) findViewById(R.id.editText3);
chfilebtn = (Button) findViewById(R.id.btn_chosfile);
chpicbtn = (Button) findViewById(R.id.btn_chospic);
regbookbtn = (Button) findViewById(R.id.button1);
uptxt = (TextView) findViewById(R.id.txt_uplodkonande);
regbookerrtxt = (TextView) findViewById(R.id.txt_regbookerr);
pathfiletxt = (TextView) findViewById(R.id.txt_pathfile);
pathpictxt = (TextView) findViewById(R.id.txt_pathpic);
upimage = (ImageView) findViewById(R.id.imageView1);
sp1=getResources().getStringArray(R.array.books);
s1= (Spinner) findViewById(R.id.sp_mozoo);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sp1);
s1.setAdapter(adapter1);
chfilebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "فایل مورد نظر خود را انتخاب کنید:"), SELECT_FILE_DIALOG);
}
});
chpicbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "فایل مورد نظر خود را انتخاب کنید:"), SELECT_IMAGE_DIALOG);
}
});
SharedPreferences settings = getSharedPreferences("userPrefs", 0);
uptxt.setText(settings.getString("username", "").toString());
regbookbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (( !namketabedt.getText().toString().equals("")) && ( !nevisandeedt.getText().toString().equals(""))
&& ( !hajmedt.getText().toString().equals("")) && ( !uptxt.getText().toString().equals(""))
&& ( !s1.getSelectedItem().toString().equals(""))
&& ( !pathfiletxt.getText().toString().equals("")) && ( !pathpictxt.getText().toString().equals(""))
){
new regbook().execute();
} else{
regbookerrtxt.setText("یکی یا چندتا از فیلدهای موجود خالی است");
}
}
});
}
insertData()
函数:
public static final String firstURL = "http://192.168.152.1/ketabha/";
private static final String URL = firstURL + "services.php?op=";
public static ArrayList<String> insertData(ArrayList<NameValuePair> params, String string) {
String result = JSONParser.readURL(URL + string, params);
ArrayList<String> ret = new ArrayList<String>();
if (result != null) {
try {
Log.i("LOG", result);
JSONArray errors = new JSONArray(result);
for (int i = 0; i < errors.length(); i++) {
ret.add(errors.getString(i));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
return ret;
}
public静态最终字符串firstURL=”http://192.168.152.1/ketabha/";
私有静态最终字符串URL=firstURL+“services.php?op=”;
公共静态ArrayList insertData(ArrayList参数,字符串){
String result=JSONParser.readURL(URL+String,params);
ArrayList ret=新的ArrayList();
如果(结果!=null){
试一试{
Log.i(“Log”,结果);
JSONArray错误=新JSONArray(结果);
对于(int i=0;i
有没有人能帮我解决这个问题,帮助我更好地理解 如果res为null并由doInBackground返回,那么在onPostExecute中,If(res.isEmpty())语句上会有一个NullPointerException。您现在知道了吗?upload()没有读取服务器的响应。insertData()在做什么?所以它返回null。insertData对POST结果一无所知。@greenapps否否我的意思是res为空。doInBackground返回总是空的。我用insertData()函数编辑了我的问题。看一看。谢谢。请发布完整的insertData函数。我们还想查看使用过的参数。抱歉,我现在看到它已完成。
function insertBook(){
$con = db_connect();
$response = array();
$namketab = $_REQUEST['namketab'];
$nevisande = $_REQUEST['nevisande'];
$mozoo = $_REQUEST['mozoo'];
$uplodkonande = $_REQUEST['uplodkonande'];
$hajm = $_REQUEST['hajm'];
$tasvir = "images/";
$tasvir = $tasvir . basename( $_FILES['tasvir']['name']);
if(move_uploaded_file($_FILES['tasvir']['tmp_name'], $tasvir)) {
empty($response);
}else{
$response[] = "book pic failed to store";
}
$tasvir = str_replace(' ', '%20', $tasvir);
$fileketab = "uploads/";
$fileketab = $fileketab . basename( $_FILES['fileketab']['name']);
if(move_uploaded_file($_FILES['fileketab']['tmp_name'], $fileketab)) {
empty($response);
}else{
$response[] = "book file failed to store";
}
$fileketab = str_replace(' ', '%20', $fileketab);
if(empty($response)){
mysqli_query($con, "INSERT INTO tbl_books (namketab, nevisande, mozoo, uplodkonande, tasvir, fileketab, hajm, status)
VALUES ('$namketab', '$nevisande', '$mozoo', '$uplodkonande', '$tasvir', '$fileketab', '$hajm', 'uploaded')");
$response[] = "book stored successfully";
}
echo json_encode($response);
mysqli_close($con);
}
public static final String firstURL = "http://192.168.152.1/ketabha/";
private static final String URL = firstURL + "services.php?op=";
public static ArrayList<String> insertData(ArrayList<NameValuePair> params, String string) {
String result = JSONParser.readURL(URL + string, params);
ArrayList<String> ret = new ArrayList<String>();
if (result != null) {
try {
Log.i("LOG", result);
JSONArray errors = new JSONArray(result);
for (int i = 0; i < errors.length(); i++) {
ret.add(errors.getString(i));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
return ret;
}