简体   繁体   中英

sending data to localserver sql from android application

Hey i have been stuck on a problem for long time.. i am submitting the android (eclipse) main1.java, the php code and the php output with the hope that some1 could help

PHP OUTPUT


[{"0":"1","id":"1","1":"James","firstName":"James","2":"Smith","lastName":"Smith","3":"111111111","telephone":"111111111","4":"js@functionaldomain.com","email":"js@functionaldomain.com"},{"0":"2","id":"2","1":"Jon","firstName":"Jon","2":"Johnson","lastName":"Johnson","3":"222222222","telephone":"222222222","4":"jj@functionaldomain.com","email":"jj@functionaldomain.com"}]
Notice: Undefined index: firstName in C:\xampp\htdocs\food.php on line 14

Notice: Undefined index: lastName in C:\xampp\htdocs\food.php on line 15

Notice: Trying to get property of non-object in C:\xampp\htdocs\food.php on line 20
NULL test

MAIN1>JAVA


**public class Main1 extends Activity {
InputStream is;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String result = "";

    //Connection

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/test.php");

    //http post
    try{

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("log_tag", "connection success ");
            Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            Toast.makeText(getApplicationContext(), "fail0", Toast.LENGTH_SHORT).show();
    }

    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                    Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
            }
            is.close();
            result=sb.toString();
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    }catch(Exception e){
           Log.e("log_tag", "Error converting result "+e.toString());
        Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    String col_id = json_data.getString("firstName");
                    Toast.makeText(getApplicationContext(), col_id, Toast.LENGTH_SHORT).show();
           }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
            Toast.makeText(getApplicationContext(), "fail1", Toast.LENGTH_SHORT).show();
    }

    JSONObject json = new JSONObject();

    //Sending data to php
    try{
         // Add your data
        String fname = "john";
        String lname = "smith";
        nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("firstName", fname.trim()));
        nameValuePairs.add(new BasicNameValuePair("lastName", lname.trim()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        Toast.makeText(getApplicationContext(), "finalpass", Toast.LENGTH_SHORT).show();
    }
     catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    }
}

TEST.PHP

<?php
mysql_connect("127.0.0.1","root","password");
mysql_select_db("addressbook");
$sql = mysql_query("SELECT * FROM colleague");
while($row=mysql_fetch_array($sql))
{
    $output[]=$row;
}
print(json_encode($output));

$fname = $_POST['firstName'];
$telephone = $_POST['telephone'];
$fnam = (String)$fname;
//$lname = (isset($_POST['lastName'])) ? $_POST['lastName'] : null;
//$email = (isset($_POST['email'])) ? $_POST['email'] : null;

mysql_query("INSERT INTO colleague(firstName, lastName, telephone, email)
VALUES ($fnam, 'Smith', $telephone, 'stfu@vib')");

mysql_free_result($sql);
mysql_close();

?>

if i could get rid of the errors in the php output and get fname printed... it would be great

The output you posted seems to refer to a food.php and doesn't relate to the code you posted?

Edit try this:

$fname = (isset($_POST['firstName'])) ? $_POST['firstName']: null;
$lname = (isset($_POST['lastName'])) ? $_POST['lastName'] : null;

To send data to server you could do this:

private void sendData(ArrayList<NameValuePair> data)
{
     // 1) Connect via HTTP. 2) Encode data. 3) Send data.
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new      
        HttpPost("http://www.blah.com/AddAccelerationData.php");
        httppost.setEntity(new UrlEncodedFormEntity(data));
        HttpResponse response = httpclient.execute(httppost);
        Log.i("postData", response.getStatusLine().toString());
            //Could do something better with response.
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error:  "+e.toString());
    }  
}

then to send lets say:

private void sendAccelerationData(String userIDArg, String dateArg, String timeArg,
        String timeStamp, String accelX, String accelY, String accelZ)
{
    fileName = "AddAccelerationData.php";

    //Add data to be send.
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
    nameValuePairs.add(new BasicNameValuePair("userID", userIDArg));
    nameValuePairs.add(new BasicNameValuePair("date",dateArg));
    nameValuePairs.add(new BasicNameValuePair("time",timeArg));
    nameValuePairs.add(new BasicNameValuePair("timeStamp",timeStamp));

    nameValuePairs.add(new BasicNameValuePair("accelX",accelX));
    nameValuePairs.add(new BasicNameValuePair("accelY",accelY));
    nameValuePairs.add(new BasicNameValuePair("accelZ",accelZ));

    this.sendData(nameValuePairs);
}

so then the AddAccelerationData.php file on server is:

<?php
/*
 * What this file does is it:
 * 1) Creates connection to database.
 * 2) Retrieve the data being send.
 * 3) Add the retrieved data to database 'Data'.
 * 4) Close database connection.
 */
require_once '../Connection.php'; //connect to a database/disconnect handler.
require_once '../SendAPI.php'; //deals with sending querys.

$server = new Connection();
$send = new Send();

//Connect to database.
$server->connectDB();

//Retrieve the data.
$userID = $_POST['userID'];
$date = $_POST['date'];
$time = $_POST['time'];

$accelX = $_POST['accelX'];
$accelY = $_POST['accelY'];
$accelZ = $_POST['accelZ'];

//Add data to database 'Data'. //Personal method to query and add to database.
$send->sendAccelerationData($userID, $date, $time, $timeStamp, $accelX, $accelY, $accelZ);


//Disconnect from database.
$server->disconnectDB();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM