从Android发送到数据库

时间:2014-04-09 19:50:19

标签: android json database android-studio

我正在尝试使用PHP和android将数据发送到数据库。下面是android代码:

package com.android.movies;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {
    String title;
    String rating;
    TextView show;
    InputStream is = null;
    String result = null;
    String line = null;
    int code;

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

        Button showDBbutton = (Button) findViewById(R.id.button);

        showDBbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ShowDBActivity.class);
                startActivity(intent);
            }
        });

        final EditText e_title = (EditText) findViewById(R.id.title);
        final EditText e_rating = (EditText) findViewById(R.id.rating);
        Button insert = (Button) findViewById(R.id.button2);

        insert.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                title = e_title.getText().toString();
                rating = e_rating.getText().toString();

                new SendToDB().execute();
            }
        });

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    //method for sending to the DB

    private class SendToDB extends AsyncTask<Void, Void, Void>{
            protected Void doInBackground(Void... voids){
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("title", title));
                nameValuePairs.add(new BasicNameValuePair("rating", rating));

                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("removed....insert.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    Log.e("pass 1", "connection success ");
                } catch (Exception e) {
                    Log.e("Fail 1", e.toString());
                    Toast.makeText(getApplicationContext(), "Invalid IP Address",
                            Toast.LENGTH_LONG).show();
                }

                try {
                    BufferedReader reader = new BufferedReader
                            (new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                    Log.e("pass 2", "connection success ");
                } catch (Exception e) {
                    Log.e("Fail 2", e.toString());
                }


                try {
                    JSONObject json_data = new JSONObject(result);
                    //json_data.put("code", Integer.valueOf(result));
                    code = (json_data.getInt("code"));

                    if (code == 1) {
                        Toast.makeText(getBaseContext(), "Inserted Successfully",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getBaseContext(), "Sorry, Try Again",
                                Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Log.e("Fail 3", e.toString());
                }
                return null;
            }
    }

这是PHP代码:

<?php

    $con=mysqli_connect("localhost","removed","removed,"removed");


    if(mysqli_connect_errno())
        {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        mysqli_select_db("COMP4302tlong3", $con);

        //$sql=mysqli_query($con, "SELECT * FROM appmovies");

        mysqli_query($con, "INSERT INTO appmovies SET title=" . $_POST['title']);
        mysqli_query($con, "INSERT INTO appmovies SET rating=" . $_POST['rating']);

        //while($row=mysqli_fetch_array($sql)){
        //  $output[]=$row;
        //  }
        //print(json_encode($output));
        // this will print the output in json

mysqli_close($con);
?>

尝试添加时出现此错误。

04-09 14:49:05.357 22738-23167 / com.android.movi​​es E / pass 1:连接成功

04-09 14:49:05.367 22738-23167 / com.android.movi​​es E / pass 2:连接成功

04-09 14:49:05.367 22738-23167 / com.android.movi​​es E / Fail 3:org.json.JSONException:类型java.lang.String的值失败无法转换为JSONObject

在解析JSON时,我觉得这是一个错误。

0 个答案:

没有答案