Sending data on server through an Android Application

How to send data on server through an Android application? Here, we will make a Login module to practically learn the CallHtttpRequest.
Submitted by Manu Jemini, on January 13, 2018

First we need to make an activity and layout. The Activity will contain the reference of the Input field in the layout so when the user will hit enter it will take the data from the input fields and will make a URL. This URL will be used to store our string and we will set the method post.

User (give credential) → layout/activity (make url) → use CallHttpRequest

The CallhttpRequest for this particular:

package com.example.sandeepsappal.friendcircle;
import android.content.Context;

import android.os.AsyncTask;
import android.widget.Toast;


import java.io.DataInputStream;

import java.net.HttpURLConnection;
import java.net.URL;

public class CallHttpRequest extends AsyncTask<String,Void,String> {
    Context context;
    String process;


    public CallHttpRequest(Context ctx, String login) {
        this.context=context;
        this.process=process;
    }

    @Override
    protected String doInBackground(String... url) {
        if(process.equals("login")){
            String output= callRequest (url[0]);
            return output;
        }
        return  null;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s.equals("true")){
            Toast.makeText(context,"Login Successful", Toast.LENGTH_LONG).show();
        }
    }

    String callRequest(String Url) {
        try {
            URL url = new URL(Url);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setDoInput(true);
            DataInputStream in=new DataInputStream(con.getInputStream());
            StringBuffer output = new StringBuffer();
            String str;
            while ((str = in.readLine()) != null) {
                output.append(str);
            }
            in.close();
            return (output.toString());
        } catch (Exception e) {

        }
        return (null);
    }
}

The Login Activity File for this:

package includehelp.articles;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.sandeepsappal.friendcircle.CallHttpRequest;

public class LoginActivity extends AppCompatActivity {
    EditText username,password;
    Button btn;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new Btn_Click(this));
    }

    class Btn_Click implements View.OnClickListener
    { Context ctx;
       Btn_Click(Context ctx)
       { this.ctx=ctx;}

        @Override
        
        public void onClick(View view) {
        if(view==btn) {
            String qs = "?username=" + username.getText() + "&password=" + password.getText();
            CallHttpRequest C = new CallHttpRequest(ctx, "Login");
            // Change this url
            String url[] = {"http://" + ctx.getString(R.string.ip) + ":88/something/somefile" + qs};
            C.execute(url);
        }

        }
    }
}

And the last file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/username" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/password" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button" />
</LinearLayout>

Menifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="includehelp.articles">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity></application>

</manifest>

Here the important part is in java file where the URL is been made.

String qs = "?username=" + username.getText() + 
"&password=" + password.getText();

CallHttpRequest C = new CallHttpRequest(ctx, "Login");

// Change this url
String url[] = {"http://" + ctx.getString(R.string.ip) + 
":88/something/somefile" + qs};
C.execute(url);

As you can see the String qs is the part of the query which consists of username and password. The Username will be fetched from the Editbox of the layout file which have the id equal to username, similarly we take password.

String URL is equal to the first part of the URL which consist of the domain name and post. Here you should also specify the project name and the controller name if any.

If you are using the express or any other REST API server then give the listener’s path.

That’s all you have to take care of.


Related Tutorials

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




© https://www.includehelp.com some rights reserved.