How to Send Data to Server through an Android Application?

Android | Sending Data to Server: In this tutorial, we will learn how to send data on a server through an Android application. Here, we will make a Login module to practically learn the CallHtttpRequest. By Manu Jemini Last updated : June 08, 2023

Sending Data to Server through an Android Application

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

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

Login Activity

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.