Menus

Tuesday, 4 June 2019

Android Drop Down List Tutorial



Spinner in Android application is equivalent of ComboBox

Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.


You can add a spinner to your layout with the spinner.

For example

    <Spinner
        android:id="@+id/spnCountry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </Spinner>



List of Items in Spinner

Open “res/values/strings.xml” file, define the list of items that will display in Spinner 

File : res/values/strings.xml
<resources>
    <string name="app_name">Layouts</string>

    <string name="prompt_country">Select a Country</string>

    <string-array name="country_list">
        <item>India</item>
        <item>United States</item>
        <item>Singapore</item>
        <item>Malaysia</item>>
        <item>France</item>
        <item>Italy</item>
        <item>New Zealand</item>
    </string-array>

</resources>


Spinner  selection items will be defined in xml file


<Spinner
        android:id="@+id/spnCountry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/country_list"
         >
</Spinner>

Other method :

<Spinner
        android:id="@+id/spnCountry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/prompt_country"
        android:entries="@array/country_list"
        android:spinnerMode="dialog"
         >

 </Spinner>

Spinner selection items will be defined in code

add code in onCreate method

public class MainActivity extends AppCompatActivity {

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

        Spinner spnCountry = (Spinner) findViewById(R.id.spnCountry);

        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.country_list));
        myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spnCountry.setAdapter(myAdapter);


    }
}


Video





How to set selected item of Spinner programmatically in Android

Get spinner selected items text?

This example enplane value display on button click 

Java code
       Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                         Toast.makeText(TestActivity.this,String.valueOf(spnCountry.getSelectedItem()),Toast.LENGTH_LONG).show();
            }

        });

Example 2


Spinner spnCountry = (Spinner)findViewById(R.id.spnCountry);
String text = spnCountry.getSelectedItem().toString();


Handle spinner click event 


Spinner setOnItemSelectedListener


           spnCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(TestActivity.this,parent.getItemAtPosition(position) + " Selected",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


Set Key and Value in spinner

SpinnerCountry.java

package com.example.root.spinner;

/**
 * Created by root on 8/6/19.
 */
public class SpinnerCountry {

    public String id;
    public String country;

    public SpinnerCountry(String id,String country) {
        this.country = country;
        this.id = id;
    }

    @Override
    public String toString() {
        return country;
    }

}


MainActivity.java


package com.example.root.spinner;
import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {

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

        Spinner spnCountry = (Spinner) findViewById(R.id.spnCountry);

        ArrayList<SpinnerCountry> countryList = new ArrayList<SpinnerCountry>();
        //add coutries        countryList.add(new SpinnerCountry("1","India"));
        countryList.add(new SpinnerCountry("2","France"));
        countryList.add(new SpinnerCountry("3","United States"));

        //fill data in spinner
        ArrayAdapter<SpinnerCountry> spinnerAdapter = new ArrayAdapter<SpinnerCountry>(MainActivity.this,
                android.R.layout.simple_spinner_dropdown_item,countryList);
        spnCountry.setAdapter(spinnerAdapter);

// And this is how we can retrieve it upon item selection

        spnCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                SpinnerCountry spn = (SpinnerCountry) parent.getItemAtPosition(position);

                Toast.makeText(MainActivity.this,spn.id,Toast.LENGTH_LONG).show();
        
            }

            @Override            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


    }
}


Video





Sunday, 19 May 2019

Android date picker dialog



Android App to Choosing a date from Datepicker dialog

How to popup datepicker when click on edittext




XML file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.root.datedialogpopup.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Birthday" />

        <EditText
            android:id="@+id/edtBirthday"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Click to enter Birthday"
            />

    </LinearLayout>


</RelativeLayout>


Java Code:

package com.example.root.datedialogpopup;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


    private EditText edtBirthday;
    private DatePickerDialog.OnDateSetListener dateSetListener;

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

        edtBirthday = (EditText)findViewById(R.id.edtBirthday);

        edtBirthday.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {

                Calendar cal = Calendar.getInstance();
                //get current date and to set popup date picker

                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog = new DatePickerDialog(
                        MainActivity.this,
                        android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                        dateSetListener,
                        year,month,day
                );

                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();

            }
        });


        dateSetListener = new DatePickerDialog.OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {

                month=month+1;
                String date = month + "/" + day + "/" + year;

                edtBirthday.setText(date);

            }
        };


    }
}







Wednesday, 15 May 2019

Android App to Add Two Numbers



Create simple application for Add or Subtract two numbers using android studio.

User Interface




Layout File

activity_add.xml
Here is the XML code for the design.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.root.layouts.AddActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#fadcdc"
        android:layout_centerVertical="true"
        >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:orientation="horizontal"
            >

            <TextView
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Number 1"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#000"
                android:textSize="20sp"
                />
            <EditText
                android:id="@+id/edtNumber1"
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textSize="20sp"
                />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:orientation="horizontal"
            >

            <TextView
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Number 2"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#000"
                android:textSize="20sp"
                />
            <EditText
                android:id="@+id/edtNumber2"
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textSize="20sp"
                />
        </LinearLayout>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal"
            >

            <Button
                android:id="@+id/btnPlus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="+"
                android:textColor="#000"
                />

            <Button
                android:id="@+id/btnMinus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="-"
                android:textColor="#000"
                />

        </LinearLayout>


        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:orientation="horizontal"
            >

            <TextView
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Result"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#000"
                android:textSize="20sp"
                />
            <EditText
                android:id="@+id/edtResult"
                android:layout_width="130dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textSize="20sp"
                android:focusable="false"
                />
        </LinearLayout>


    </LinearLayout>

</RelativeLayout>


Activity java file

AddActivity.java


package com.example.root.layouts;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AddActivity extends AppCompatActivity {

    EditText edtNumber1;
    EditText edtNumber2;
    EditText edtResult;
    Double num1,num2,result;

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


        edtNumber1 = (EditText)findViewById(R.id.edtNumber1);
        edtNumber2 = (EditText)findViewById(R.id.edtNumber2);
        edtResult = (EditText)findViewById(R.id.edtResult);




        Button btnPlus = (Button)findViewById(R.id.btnPlus);
        btnPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                num1=Double.parseDouble(edtNumber1.getText().toString());
                num2=Double.parseDouble(edtNumber2.getText().toString());

                result = num1+num2;

                edtResult.setText(Double.toString(result));


            }
        });

        Button btnMinus = (Button)findViewById(R.id.btnMinus);
        btnMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num1=Double.parseDouble(edtNumber1.getText().toString());
                num2=Double.parseDouble(edtNumber2.getText().toString());

                result = num1-num2;

                edtResult.setText(Double.toString(result));
            }
        });

    }
}


Video for this tutorials






Thursday, 9 May 2019

Android Activity



Calling one activity from another in android

Intent intent = new Intent(context, YourActivityClass.class);
startActivity(intent);
intent = new Intent(getApplicationContext(),CoursesActivity.class);
startActivity(intent);


How to start Activity in adapter?


holder.linearLayout.setOnClickListener(new View.OnClickListener(){
    @Override    public void onClick(View view) {

        Intent intent= new Intent(context, CoursedetailsActivity.class);
        
        context.startActivity(intent);

        
    }
});



How to Pass a Data from One Activity to Another in Android

* Passing data from one activity to other in android

Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);

holder.linearLayout.setOnClickListener(new View.OnClickListener(){
    @Override    public void onClick(View view) {

        Intent intent= new Intent(context, CoursedetailsActivity.class);
        intent.putExtra("courseid", listCourse.getCourseid());
        intent.putExtra("course",listCourse.getCourse());

        context.startActivity(intent);

    }
});


* Retrieving bundle data from android activity

Intent intent = getIntent();
if (null != intent) {
    String courseid= intent.getStringExtra("courseid");
    String course= intent.getStringExtra("course");
    Toast.makeText(this,courseid+"-"+course, Toast.LENGTH_LONG).show();
}



Wednesday, 8 May 2019

Android AsyncTask HTTP GET request Tutorial


More details about Android Asynchronous Http Client

Here is simple HttpsURLConnection in ASyncTask class for Https GET web-API calling along with packet-header and JSONObject in body.


Get JSON value show in RecyclerView.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_courses);

        recyclerCourse = (RecyclerView) findViewById(R.id.recyclerCourse);
        recyclerCourse.setHasFixedSize(true);
        recyclerCourse.setLayoutManager(new LinearLayoutManager(this));

        listCourses = new ArrayList<>();

        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Please Wait....");
        progressDialog.show();

        client.get(Config.URL_COURSEDIPLAY, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                try {
                    JSONArray arr = new JSONArray(new String(responseBody));

                    for(int i=0; i<arr.length();i++){
                        JSONObject obj = (JSONObject)arr.get(i);


                        ListCourse listCourse = new ListCourse(
                                obj.get("course").toString(),
                                obj.get("slid").toString()
                        );
                        listCourses.add(listCourse);

                    } //for int=0

                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "Loading Complete", Toast.LENGTH_LONG).show();


                } catch (JSONException e){
                    progressDialog.dismiss();
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                progressDialog.dismiss();
                // TODO Auto-generated method stub
                if(statusCode == 404){
                    Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                }else if(statusCode == 500){
                    Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                }

            }
        });

        adapter = new CourseAdapter(listCourses,this);
        recyclerCourse.setAdapter(adapter);

    }


URL defined in Config class
private static final String ROOT_URL = "http://10.42.0.1/dsms/android/";
public static final String URL_COURSEDIPLAY = ROOT_URL + "displaycourse.php";


In Android Studio, use the Gradle entry as:

compile 'com.loopj.android:android-async-http:1.4.9'compile 'com.google.code.gson:gson:2.2.+'







Friday, 26 April 2019

Android user registration interface create


Android Layout Design




Layout design script below here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.root.layouts.UserregistrationActivity">
   
    <LinearLayout

        android:id="@+id/Linearlayout"
        android:layout_centerVertical="true"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">



        <TextView
            android:text="Username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/Txtusername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Username"/>

        <TextView
            android:text="Password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/Txtpassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:hint="Enter Password"/>

        <TextView
            android:text="Email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/Txtemail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Email"/>

        <Button
            android:id="@+id/Btnregister"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register User"/>

    </LinearLayout>


    <TextView
        android:layout_below="@+id/Linearlayout"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAlignment="center"
        android:text="Alreay Registerd ? \n Click Here to Login"
        />

</RelativeLayout>






Android - SQLite Database Tutorial




Tuesday, 26 February 2019

Control Statements in Android



Switch Statement


HOW TO USE SWITCH STATEMENT IN ANDROID/JAVA?


Switch case statements are a substitute for long if statements that compare a variable to several integral values
  • The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
  • Switch is a control statement that allows a value to change control of execution.

SYNTAX

switch(index){
    case 0:
        //Do this and this        break;
    case 1:
        //Do this and this        break;
    case 2:
        //Do this and this:        break;
    default: //For all other cases, do this        break;
}