nawaab saab
nawaab saab

Reputation: 1902

How to send information from android app to server?

Hello everone I started studying webservices in android and I tried to save information from my android app to server

For this firstly I made a php file. I tried to insert code using that. I am succesful in inserting code using this php code file

<?php
$con=mysqli_connect("localhost","root","","abhi_DB");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);

$sql="INSERT INTO user_records (user_name, email)
VALUES ('$uname', '$email')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

After this I tried to send information from my app to server by hitting url. The code I used is

public class MainActivity extends Activity {


    TextView tv1;
    HttpClient httpclient;
    HttpPost httppost;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.tv1);
        httpclient = new DefaultHttpClient();
        httppost = new HttpPost("http://10.0.2.2/name.php");
        new getresult().execute();


    }

    @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;
    }

    public class getresult extends AsyncTask<Void, Void, Void>{


        String result = null;
        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("uname", "rocky"));
                nameValuePairs.add(new BasicNameValuePair("email", "rockss"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result1) {
            // TODO Auto-generated method stub
            super.onPostExecute(result1);
            tv1.setText("Data Inserted");
            //Log.i("My Response :: ", result);
        }

    }

}

In the textview I get this message i.e Data Inserted but the problem is the value is not inserted in database.

So if you people kindly tell what mistake I am making. It will be somuch helpful for me. Thanks in advance

Upvotes: 0

Views: 429

Answers (3)

nawaab saab
nawaab saab

Reputation: 1902

A small project for webservices beginners. I am a webservice beginner, So I did something and I would like to share for beginners so that they may know how to use webservices

Firstly I made 2 php files

1st one with this I am able to save data on abhi_db database, user_records table, with 2 columns user_name and email

because I am not having server. As I am using localhost So I used localhost, username is root, password i set nothing so I leave it blank

<?php
$con=mysqli_connect("localhost","root","","abhi_DB");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);

$sql="INSERT INTO user_records (user_name, email)
VALUES ('$uname', '$email')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

With this php code I am able to save the values in database by getting the values from my application Note: Dont forget to create database in phpmyadmin with the tablename that you use

2nd php file is

<?php
$con=mysqli_connect("localhost","root","","abhi_DB");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM user_records");

while($row = mysqli_fetch_array($result)) {
  echo $row['user_name'] . " " . $row['email'];
  echo "<br>";
}

mysqli_close($con);
?>

This second code is to get data saved in database

Now comes to android code:

Now from android we will hit hit the url

In the MainActivity class

public class MainActivity extends Activity {

    TextView tv1;
    HttpClient httpclient;
    HttpPost httppost;
    EditText edname, edemail;
    Button Submit, GetData;
    String geted1, geted2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.tv1);
        edname = (EditText) findViewById(R.id.editText1);
        edemail = (EditText) findViewById(R.id.editText2);
        Submit = (Button) findViewById(R.id.button1);
        GetData = (Button) findViewById(R.id.button2);
        httppost = new HttpPost("http://10.0.2.2/name.php");
        Submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                geted1 = edname.getText().toString();
                geted2 = edemail.getText().toString();
                Log.i("Name", geted1);
                Log.i("Email", geted2);
                new getresult().execute();
            }
        });

        GetData.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i = new Intent(MainActivity.this, GetNameDemo.class);
                startActivity(i);
            }
        });

    }


    public class getresult extends AsyncTask<Void, Void, Void> {

        String result = null;

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            try {
                HttpParams params = new BasicHttpParams();
                params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                        HttpVersion.HTTP_1_1);
                httpclient = new DefaultHttpClient(params);
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        2);
                nameValuePairs.add(new BasicNameValuePair("uname", geted1));
                nameValuePairs.add(new BasicNameValuePair("email", geted2));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
                        "utf-8"));
                result = httpclient.execute(httppost,
                        new BasicResponseHandler());

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result1) {
            // TODO Auto-generated method stub
            super.onPostExecute(result1);
            tv1.setText("" + result);
            // Log.i("My Response :: ", result);

        }

    }

}

In the MainActivity class I used two edittext one for name and 2 nd for email and on click of submit button I sent values to server and on Getdata Button click I started Activity class GetNameDemo in which I get all the rows that are saved

public class GetNameDemo extends Activity {
    
    
    TextView tv1,tv2;
    HttpClient httpclient;
    HttpPost httppost;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get);
        tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        httppost = new HttpPost("http://10.0.2.2/getname.php");
        new getresult().execute();
    
        
    }

    
    public class getresult extends AsyncTask<Void, Void, Void>{

        
        String name = "Names";
        String email = "    Emails";
        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            try {
                HttpParams params = new BasicHttpParams();
                params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                HttpVersion.HTTP_1_1);
                httpclient = new DefaultHttpClient(params);
                String resp = httpclient.execute(httppost, new BasicResponseHandler());

                String[] nameEmailPairs = resp.split("<br>");

                for(String pair : nameEmailPairs){
                    String[] par = pair.split(" ");
                    name = name + "  \n  " +par[0];
                    email = email + "\n    " +  par[1];
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("Exception", e.toString());
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(Void result1) {
            // TODO Auto-generated method stub
            super.onPostExecute(result1);
            tv1.setText("" +name );
            tv2.setText( "" +email);
            //Log.i("My Response :: ", result);
            
            
        }
        
    }

}

Note add the permission <uses-permission android:name="android.permission.INTERNET"/> and activity <activity android:name="GetNameDemo"></activity>

If you want xml files also check this link and if you still face any problem ask here

Upvotes: 0

Roman Black
Roman Black

Reputation: 3497

You need to execute Your HTTP POST request:

        try {
            HttpParams params = new BasicHttpParams();
            params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
            HttpVersion.HTTP_1_1);
            HttpClient httpClient = new DefaultHttpClient(params);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("uname", "rocky"));
            nameValuePairs.add(new BasicNameValuePair("email", "rockss"));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

            String resp = httpClient.execute(httpPost, new BasicResponseHandler());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("Exception", e.toString());
        }

To get data from server use below code:

        try {
            HttpParams params = new BasicHttpParams();
            params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
            HttpVersion.HTTP_1_1);
            HttpClient httpClient = new DefaultHttpClient(params);

            // put the parameters if needed

            String resp = httpClient.execute(httpPost, new BasicResponseHandler());

            String[] nameEmailPairs = resp.split("<br>");

            for(String pair : nameEmailPairs){
                String[] par = pair.split(" ");
                String name = par[0];
                String email = par[1];
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("Exception", e.toString());
        }

Upvotes: 1

mapodev
mapodev

Reputation: 988

You can use a simple made framework for http request. http://loopj.com/android-async-http/ is very simple to use and offers callbacks after sending the request, as success and as well failure. This is all automated.

Here an example

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {

@Override
public void onStart() {
    // called before request is started
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
    // called when response HTTP status is "200 OK"
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
    // called when response HTTP status is "4XX" (eg. 401, 403, 404)
}

@Override
public void onRetry(int retryNo) {
    // called when request is retried
}
 });

Upvotes: 0

Related Questions