Pages

SharedPreferences Android

Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.


MainActivity.java


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

public class MainActivity extends AppCompatActivity {

    EditText user, pass;

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

        user = (EditText) findViewById(R.id.editText);
        pass = (EditText) findViewById(R.id.editText2);

    }

    public void save(View view) {

        SharedPreferences sharedPreferences =getSharedPreferences("MyData",MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putString("name",user.getText().toString());
        editor.putString("pass",pass.getText().toString());

        editor.commit();

        Toast.makeText(this, "Data was Saved successfully", Toast.LENGTH_SHORT).show();

    }

    public void next(View view) {

        Toast.makeText(this, "Next", Toast.LENGTH_SHORT).show();
        Intent in = new Intent(getApplicationContext(), Another.class);
        startActivity(in);


    }
}

Another.java

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

public class Another extends AppCompatActivity {
 
    public static final String DEFAULT="N/A";
      EditText user, passTv;

    @Override    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another);
        user = (EditText) findViewById(R.id.editText3);
        passTv = (EditText) findViewById(R.id.editText4);
    }

    public void load(View view) {

        SharedPreferences sharedPreferences=getSharedPreferences("MyData",
                                                         Context.MODE_PRIVATE);

        String name =sharedPreferences.getString("name", DEFAULT);
        String pass =sharedPreferences.getString("pass", DEFAULT);

        if(name.equals(DEFAULT) || pass.equals(DEFAULT)) {

            Toast.makeText(this, "No Data was Found", Toast.LENGTH_SHORT).show();

        }

        else {

            Toast.makeText(this, "Data Loaded successfully", Toast.LENGTH_SHORT).show();

            user.setText(name);
            passTv.setText(pass);

        }

    }

    public void back(View view) {

        Toast.makeText(this, "Back", Toast.LENGTH_SHORT).show();

        Intent in = new Intent(getApplicationContext(), MainActivity.class);

        startActivity(in);
    }

}
main.xml

<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:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">



    <EditText

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/editText"

        android:layout_alignParentTop="true"

        android:layout_marginTop="63dp"

        android:layout_alignParentRight="true"

        android:layout_alignParentEnd="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:hint="Username" />



    <EditText

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:inputType="textPassword"

        android:ems="10"

        android:id="@+id/editText2"

        android:layout_below="@+id/editText"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_alignRight="@+id/editText"

        android:layout_alignEnd="@+id/editText"

        android:hint="Password" />



    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="save"

        android:id="@+id/saveBtn"

        android:onClick="save"

        android:layout_centerVertical="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true" />



    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Another"

        android:id="@+id/button"

        android:layout_centerVertical="true"

        android:onClick="next"

        android:layout_alignRight="@+id/editText2"

        android:layout_alignEnd="@+id/editText2" />

</RelativeLayout>

activity_another.xml

 <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.blogspot.help2computer.shared.Another">

        <button
            android:id="@+id/loadBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignparentleft="true"
            android:layout_alignparentstart="true"
            android:layout_alignparenttop="true"
            android:layout_margintop="73dp"
            android:onclick="load"
            android:text="Load">

        </button>

        <button
            android:id="@+id/backBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignbottom="@+id/loadBtn"
            android:layout_alignparentend="true"
            android:layout_alignparentright="true"
            android:onclick="back"
            android:text="back">

            <edittext
                android:id="@+id/editText3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignend="@+id/backBtn"
                android:layout_alignparentleft="true"
                android:layout_alignparentstart="true"
                android:layout_alignright="@+id/backBtn"
                android:layout_below="@+id/loadBtn"
                android:layout_margintop="46dp"
                android:hint="Username">

                <edittext
                    android:id="@+id/editText4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignend="@+id/editText3"
                    android:layout_alignparentleft="true"
                    android:layout_alignparentstart="true"
                    android:layout_alignright="@+id/editText3"
                    android:layout_below="@+id/editText3"
                    android:ems="10"
                    android:hint="Password"
                    android:inputtype="textPassword"></edittext>
            </edittext>
        </button>
    </relativelayout>


Listview Example

ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.
For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter.

list.xml

<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:paddingLeft="@dimen/activity_horizontal_margin"    
    android:paddingRight="@dimen/activity_horizontal_margin"    
    android:paddingTop="@dimen/activity_vertical_margin"    
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.blogspot.help2computer.test.List">

    <ListView       
      android:layout_width="wrap_content"        
      android:layout_height="wrap_content"        
      android:id="@+id/listView"        
      android:layout_alignParentTop="true"        
      android:layout_alignParentLeft="true"        
      android:layout_alignParentStart="true"        
      android:layout_marginTop="68dp" />
</RelativeLayout>

List.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class List extends AppCompatActivity {

    ListView listView;

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

        listView = (ListView) findViewById(R.id.listView);

        // Defined Array values to show in ListView  

        String[] values = new String[]{"Android List View",
                "Adapter implementation",
                "Simple List View In Android",
                "Create List View Android",
                "Android Example",
                "List View Source Code",
                "List View Array Adapter",
                "Android Example List View"        };

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);

        listView.setAdapter(adapter) ;
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // ListView Clicked item index                
              int itemPosition     = position;
                   // ListView Clicked item value      
             String  itemValue    = (String) listView.getItemAtPosition(position);
                // Show Alert    
           Toast.makeText(getApplicationContext(),itemValue , Toast.LENGTH_LONG)
                        .show();
            }
        });


    }
}

Alert Example in android

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.





MainActivity.xml

<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=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="151dp"
        android:clickable="true"
        android:onClick="open"
        android:text="Alert" />

</RelativeLayout>


MainActivity.java

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override  
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void open(View view){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure,You wanted to make decision");

        alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override           
   public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(MainActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
            }
        });

        alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
}

Splash screen - Android Example

splash screen is a graphical control element consisting of window containing an image, a logo and the current version of the software. A splash screen usually appears while a game or program is launching.
Image result for Splash screen

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainSplashScreen extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_splash_screen);
         
// METHOD 1    
         
        /****** Create Thread that will sleep for 5 seconds *************/        
        Thread background = new Thread() {
            public void run() {
                
               try {
                    // Thread will sleep for 5 seconds
                    sleep(5*1000);
                     
                    // After 5 seconds redirect to another intent
                    Intent i=new Intent(getBaseContext(),FirstScreen.class);
                    startActivity(i);
                     
                    //Remove activity
                    finish();
                     
                } catch (Exception e) {              
                }
            }
        };
         
        // start thread
        background.start();
         
//METHOD 2 
         
        /*
        new Handler().postDelayed(new Runnable() {
              
            // Using handler with postDelayed called runnable run method
            @Override
            public void run() {
                Intent i = new Intent(MainSplashScreen.this, FirstScreen.class);
                startActivity(i);
  
                // close this activity
                finish();
            }
        }, 5*1000); // wait for 5 seconds
        */
    }
     
    @Override
    protected void onDestroy() {
         
        super.onDestroy();
         
    }
}