【问题标题】:I cant post data & image in localhost server using json我无法使用 json 在 localhost 服务器中发布数据和图像
【发布时间】:2013-10-13 14:44:31
【问题描述】:

我使用此代码并添加了我的完整代码。我找不到我所做的错误..我想在服务器中发布我的数据和图像。

public class MainActivity extends Activity {
String name, price;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
String profilepic;
ProgressDialog pDialog;
private static int RESULT_LOAD_IMAGE = 1;
FileBody cbFile;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EditText name1 = (EditText) findViewById(R.id.editText1);
    EditText pwd = (EditText) findViewById(R.id.editText2);
    Button img = (Button) findViewById(R.id.button1);
    Button signup = (Button) findViewById(R.id.button2);
    name = name1.getText().toString();
    price = pwd.getText().toString();
    img.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);

        }
    });
    signup.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new PostPicture().execute();

        }
    });
}

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
            && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.imageView1);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            Toast.makeText(getApplicationContext(), "" + selectedImagePath,
                    1000).show();
            // System.out.println("Image Path : " + selectedImagePath);

        }
    }

}

private 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);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

class PostPicture extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Uploading Picture");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://192.168.1.50/android_connect/create_product.php");

        try {

            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            File file = new File(
                    "/mnt/sdcard/stock-vector-a-golden-soccer-ball-122478970.jpg");
            cbFile = new FileBody(file, "image/jpeg");
            StringBody sb1 = new StringBody("some text goes here");
            StringBody sb2 = new StringBody("some text goes here too");
            Log.d("sending picture", "guest name is " + name);
            Log.d("Sending picture", "guest code is " + price);
            // entity.addPart("name",tjh);
            entity.addPart("name", sb1);
            entity.addPart("price", sb2);
            // entity.addPart("description", cbFile);
            post.setEntity(entity);

            HttpResponse response1 = client.execute(post);
            HttpEntity resEntity = response1.getEntity();
            String Response = EntityUtils.toString(resEntity);
            Log.d("Response", Response);

        } catch (IOException e) {
            Log.e("asdf", e.getMessage(), e);

        }
        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG)
                    .show();
        }

    }

}

}

还有我的 php 文件

$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {

$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
 } else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

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

// echoing JSON response
echo json_encode($response);

} ?>

我的 logcat 错误 10-13 20:13:12.373: W/IInputConnectionWrapper(26253): showStatusIcon on inactive InputConnection 10-13 20:13:28.292: D/dalvikvm(26253): GC_CONCURRENT 释放 215K,5% 释放 7050K/7367K,暂停 302ms+30ms 10-13 20:13:33.713: D/发送图片(26253): 客人姓名是 10-13 20:13:33.713:D/发送图片(26253):客人代码是 10-13 20:13:34.976: D/Response(26253): {"success":0,"message":"必填字段缺失"}

【问题讨论】:

  • 您的 PHP 脚本需要名为 namepricedescription 的字段,但您似乎没有发送 description 字段。
  • @MikeW 现在我添加描述..但我得到相同的输出
  • 您找到解决方案了吗? @karthik

标签: php android mysql json multipartentity


【解决方案1】:

您收到此错误是因为您的“if”函数检查 php 文件中的 post 函数返回 false,您应该检查您的 java 代码,因为缺少某些字段可能是描述...

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 1970-01-01
    • 2016-04-14
    • 2015-04-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多