Menus

Showing posts with label Android Programming. Show all posts
Showing posts with label Android Programming. Show all posts

Monday, 4 May 2020

How to add custom notification in android app


Create and Display Notification on Android with Example






import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.app.NotificationCompat; import android.view.View; import android.widget.Button; public class NotficationtestActivity extends AppCompatActivity { NotificationCompat.Builder notification; private static final int appuniqueID = 10012; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notficationtest); notification = new NotificationCompat.Builder(this); notification.setAutoCancel(true); Button btnNotification = (Button) findViewById(R.id.btnNotificationttest); btnNotification.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Build the notification notification.setSmallIcon(R.drawable.photo); notification.setTicker("Ticker"); notification.setWhen(System.currentTimeMillis()); notification.setContentTitle("TechProgrammingIdeas"); notification.setContentText("Added new video. Subscribe my channel"); Intent intent = new Intent(NotficationtestActivity.this,NotficationtestActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(NotficationtestActivity.this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT); notification.setContentIntent(pendingIntent); //Builds notification and issue it NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.notify(appuniqueID,notification.build()); } }); } }








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






Wednesday, 20 February 2019

How To Make Splash Screen in Android Studio



How to make Splash Screen in your android project.



Steps

Create new project to give application name as SplashScreen


Keeping minimum SDK 


Add on Activity and then finish to open new project.


Then add to EmptyActivity activity in your project.

Select EmptyActivity and give name SplashScreen




For display image copy to drawable folder.

Add to image view in activity_splash.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"    tools:context="com.example.root.splashscreen.SplashActivity">

    <ImageView        
          android:layout_width="match_parent"        
          android:layout_height="match_parent"        
          android:src="@drawable/logo"        />

</RelativeLayout>


Then change theme to select NoTitlebar.


Then go to our main job as three minutes display  splash screen.

Open SplashActivity.java to add this codes

package com.example.root.splashscreen;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashActivity extends AppCompatActivity {

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

        Thread myThread = new Thread(){
            @Override
            public void run() {
                try {
                    sleep(3000);
                    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                    startActivity(intent);
                    finish();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        myThread.start();


        
    }
}


Then set Splash Screen to start activity.


Go to open manifest file

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

    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">

        <activity android:name=".SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity android:name=".MainActivity"></activity>
    </application>

</manifest>



Code that hides title bar of activity

  1. requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title   
  2. getSupportActionBar().hide(); //hide the title bar  

The setFlags() method of Window class is used to display content in full screen mode. You need to pass theWindowManager.LayoutParams.FLAG_FULLSCREEN constant in the setFlags method.







Wednesday, 7 February 2018

Android Menu

Menus

Menus are a common user interface component in many types of applications.

This guide shows how to create the three fundamental types of menus or action presentations on all versions of Android:

Options menu and app bar
The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings."

Context menu and contextual action mode
A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.

Popup menu
A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu.


Android Option Menu Example

Defining a Menu in XML


It contains three items as show below. It is created automatically inside the res/menu directory.


menu with the following elements:

<menu>
Defines a Menu, which is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and<group> elements.
<item>
Creates a MenuItem, which represents a single item in a menu. This element may contain a nested <menu> element in order to create a submenu.
<group>
An optional, invisible container for <item> elements. It allows you to categorize menu items so they share properties such as active state and visibility. For more information, see the section about Creating Menu Groups.

<menu xmlns:androclass="http://schemas.android.com/apk/res/android" >      <item  android:id="@+id/item1"  
        android:title="Item 1"/> 
   <item  android:id="@+id/item2"  
        android:title="Item 2"/>  
    <item  android:id="@+id/item3"  
        android:title="Item 3"/>  
</menu>  


More Details

Write a Program to create menu with three menu items


Example





activity_main.xml

<?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.myapplication.MainActivity">

    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Menu Program" />
</RelativeLayout>


main.xml   //main.xml file in res/menu

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

<item android:id="@+id/item1"    android:title="item1" />
<item android:id="@+id/item2"    android:title="item2" />
<item android:id="@+id/item3"    android:title="item3" />

</menu>


MainActivity.java


package com.example.root.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    @Override    public boolean onCreateOptionsMenu(Menu menu){

        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.item1) {
            Toast.makeText(getApplicationContext(), "First Item Selected!",
                    Toast.LENGTH_SHORT).show();
        }
        if (id == R.id.item2) {
            Toast.makeText(getApplicationContext(), "Second Item Selected!", Toast.LENGTH_SHORT).show();
        }
        if (id == R.id.item3) {
            Toast.makeText(getApplicationContext(), "Third Item Selected!",
                    Toast.LENGTH_SHORT).show();
        }
        return true;
    }


}



Problem - res/menu and res/xml are not there


If it is in android studio 2.1.1, to create a res/menu folder follow these steps.
right click on res -> new -> Android resource directory -> change the resource type to 'menu' in the dropdown menu -> click ok
to create menu file in menu folder right click on menu folder -> new -> menu resource file ->give the file name -> click ok.