Я пытаюсь написать несколько кодов, чтобы загрузить файл и изображение, а также некоторую информацию о них вместе, но моя попытка не работает и всегда 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("یکی یا چندتا از فیلدهای موجود خالی است");
}
}
});
}
и вот мой класс загрузки файлов в RegBookActivity:
private class regbook extends AsyncTask<String, String, ArrayList<String>> {private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegBookActivity.this);
pDialog.setMessage("درحال آپلود فایل، لطفا منتظر بمانيد...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
public String upload(String suri)
{
int count;
File sourceFile = new File(suri);
if (!sourceFile.isFile()) {
pDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(RegBookActivity.this)
.setTitle("خطا در آپلود فایل")
.setMessage("فایل انتخابی وجود ندارد!");
builder.create().show();
}
else{
try{
// URL url = new URL(JSONCommands.firstURL + "services.php?op=insertBook");
// HttpURLConnection conection = (HttpURLConnection) url.openConnection();
// conection.connect();
URL url = new URL(JSONCommands.firstURL + "services.php?op=insertBook");
URLConnection conection = url.openConnection();
conection.connect();
// FileInputStream fileInputStream = new FileInputStream(sourceFile);
InputStream input = new FileInputStream(sourceFile);
// dos = new DataOutputStream(conection.getOutputStream());
OutputStream output = new BufferedOutputStream(conection.getOutputStream());
// create a buffer of maximum size
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
//publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
}
return null;
}
@Override
protected ArrayList<String> doInBackground(String... response) {
final String bookfilename = sourceFileUri.substring(sourceFileUri.lastIndexOf("/") + 1);
final String bookimgname = sourceImgUri.substring(sourceImgUri.lastIndexOf("/") + 1);
MainActivity.params.add(new BasicNameValuePair("namketab", namketabedt.getText().toString()));
MainActivity.params.add(new BasicNameValuePair("nevisande", nevisandeedt.getText().toString()));
MainActivity.params.add(new BasicNameValuePair("mozoo", s1.getSelectedItem().toString()));
MainActivity.params.add(new BasicNameValuePair("hajm", hajmedt.getText().toString()));
MainActivity.params.add(new BasicNameValuePair("uplodkonande", uptxt.getText().toString()));
MainActivity.params.add(new BasicNameValuePair("fileketab", bookfilename));
upload(sourceFileUri);
MainActivity.params.add(new BasicNameValuePair("tasvir", bookimgname));
upload(sourceImgUri);
ArrayList<String> res = JSONCommands.insertData(MainActivity.params,"insertBook");
return res;
}
@Override
protected void onPostExecute(ArrayList<String> res) {
if (res.isEmpty()) {
pDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(RegBookActivity.this)
.setTitle("خطا در برقراری ارتباط با سرور")
.setMessage("ثبت کتاب ناموفق :( اتصالات را بررسی کنید.");
builder.create().show();
}else if (res.get(0).equals("book stored successfully")) {
pDialog.dismiss();
regbookerrtxt.setText("");
AlertDialog.Builder builder = new AlertDialog.Builder(RegBookActivity.this)
.setTitle("آپلود کتاب با موفقیت انجام شد")
.setMessage("و پس از تایید به نمایش گذاشته خواهد شد. از آپلود شما سپاسگذاریم.");
builder.create().show();
}else if (res.get(0).equals("book pic failed to store")){
pDialog.dismiss();
regbookerrtxt.setText("ذخیرهی عکس کتاب ناموفق");
}else if (res.get(0).equals("book file failed to store")){
pDialog.dismiss();
regbookerrtxt.setText("ذخیرهی فایل کتاب ناموفق");
}else{
pDialog.dismiss();
regbookerrtxt.setText("ذخیرهی کتاب ناموفق");
}
}
}
и это мой PHP-код на стороне сервера:
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);
}
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;
}
Кто-нибудь может мне помочь с этой проблемой и помочь мне лучше понять ?!
Задача ещё не решена.
Других решений пока нет …