用json android更新在线数据库

时间:2018-04-29 13:13:09

标签: php android sql json android-volley

我正在尝试使用JSON从我的Android应用更新我的在线数据库。如果我尝试这样做,SQL输出表示所有字段都是空的,因此它不会更新任何内容。我尝试更改在线代码,让它测试名称而不是ID,但由于它们都没有填写,所以没有用。希望你能帮忙吗?这是代码(你对saveTask()函数最感兴趣):

EditActivity:

package com.somthing.somepackage;

some imports...

public class EditActivity extends AppCompatActivity {

    EditText mNameEditText;
    EditText mReminderDateEditText;
    EditText mReminderTimeEditText;
    Bundle mCurrentTask;
    Intent intent;
    private static final String URL_POST = "https://my_site/json_put_data.php";
    private static final String URL_UPDATE = "https://my_site/json_update_data.php";
    private static final String URL_DELETE = "https://my_site/json_delete_data.php";

    private boolean mTaskHasChanged = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        intent = getIntent();
        mCurrentTask = intent.getExtras();

        if (mCurrentTask == null) {
            setTitle(getString(R.string.editor_activity_title_new_task));

            invalidateOptionsMenu();
        } else {
            setTitle(getString(R.string.editor_activity_title_edit_task));
        }

        mNameEditText = (EditText) findViewById(R.id.edit_task_name);
        mReminderDateEditText = (EditText) findViewById(R.id.edit_task_reminder_date);
        mReminderTimeEditText = (EditText) findViewById(R.id.edit_task_reminder_time);

        mNameEditText.setOnTouchListener(mTouchListener);
        mReminderDateEditText.setOnTouchListener(mTouchListener);
        mReminderTimeEditText.setOnTouchListener(mTouchListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_edit, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        if (mCurrentTask == null) {
            MenuItem menuItem = menu.findItem(R.id.action_delete);
            menuItem.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                postData();
                finish();
                return true;
            case R.id.action_delete:
                showDeleteConfirmationDialog();
                return true;
            case android.R.id.home:
                if (!mTaskHasChanged) {
                    NavUtils.navigateUpFromSameTask(EditActivity.this);
                    return true;
                }

                DialogInterface.OnClickListener discardButtonClickListener =
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            NavUtils.navigateUpFromSameTask(EditActivity.this);
                        }
                    };

            showUnsavedChangesDialog(discardButtonClickListener);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    if (!mTaskHasChanged) {
        super.onBackPressed();
        return;
    }

    DialogInterface.OnClickListener discardButtonClickListener =
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            };

    showUnsavedChangesDialog(discardButtonClickListener);
}

private void showUnsavedChangesDialog(
    DialogInterface.OnClickListener discardButtonClickListener) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(R.string.unsaved_changes_dialog_msg);
    builder.setPositiveButton(R.string.discard, discardButtonClickListener);
    builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    });

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

private void showDeleteConfirmationDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(R.string.delete_dialog_msg);
    builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            deleteTask();
        }
    });
    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    });

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

private void deleteTask() {
    if (mCurrentTask != null) {
        RequestQueue queue = Volley.newRequestQueue(this);  

        StringRequest dr = new StringRequest(Request.Method.DELETE,
                URL_DELETE,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        Log.i("delete: ", response);
                        Toast.makeText(EditActivity.this, getString(R.string.editor_delete_task_successful),
                                Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(EditActivity.this, getString(R.string.editor_delete_task_failed),
                                Toast.LENGTH_SHORT).show();
                    }
                }
        );
        queue.add(dr);

        finish();
    }
}

@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    if (mCurrentTask == null) {
        return;
    }

    String name = intent.getExtras().getString("NAME");
    String remDate = intent.getExtras().getString("REMINDERDATE");
    String remTime = intent.getExtras().getString("REMINDERTIME");

    mNameEditText.setText(name);
    mReminderDateEditText.setText(remDate);
    mReminderTimeEditText.setText(remTime);

    saveTask();
}

private void saveTask() {
    String nameString = mNameEditText.getText().toString().trim();
    String dateString = mReminderDateEditText.getText().toString().trim();
    String timeString = mReminderTimeEditText.getText().toString().trim();

    if (TextUtils.isEmpty(nameString) && TextUtils.isEmpty(dateString) &&
            TextUtils.isEmpty(timeString)) {
        return;
    }

    RequestQueue queue = Volley.newRequestQueue(this);  // this = context

    StringRequest putRequest = new StringRequest(Request.Method.PUT,
        URL_UPDATE,
        new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                Log.d("Response", response);
            }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("Error.Response", String.valueOf(error));
            }
        }
    )
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String> ();
                params.put("id", String.valueOf(getIntent().getExtras().getInt("id")));
                params.put("name", "Android Test insert");

                return params;
            }
        };

        queue.add(putRequest);
    };

private void postData(){
    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest postRequest = new StringRequest(Request.Method.POST,
            URL_POST,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    Log.d("Response postData: ", response);
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("Error.Response", String.valueOf(error));
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("id", "null");
            params.put("name", "Android Test update");

            return params;
        }
    };
    queue.add(postRequest);
}

private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        mTaskHasChanged = true;
        return false;
    }
};
}

在线代码:

<?php

$host = "localhost";
$username = "my_un";
$password = "my_pw";
$db = "my_db";

$id = $_POST["id"];
$name = $_POST["name"];

$sql = "UPDATE table_name SET name = '$name' WHERE id = '$id';";

$con = mysqli_connect($host, $username, $password, $db);

$result = mysqli_query($con,$sql);

if($result){
    echo $sql;
}
else {
    echo "nok";
}

mysqli_close($con);

?>

输出SQL语句:

UPDATE items SET name = '' WHERE id = '';
//Here is the problem, name and id are empty

1 个答案:

答案 0 :(得分:1)

这里的问题是因为您的php服务器期望idname作为POST参数,但您的Android排球请求正在PUT请求中发送saveTask()请求1}}方法。将其更新为POST方法,如下所示

StringRequest putRequest = new StringRequest(Request.Method.POST,
        URL_UPDATE,
        new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                Log.d("Response", response);
            }
        },
        ....