Android – Session Management Session help you when want to store user data outside your application, so that when the next time user use your application, you can easily get back his details and perform accordingly. This can be done in many ways. But the most easiest and nicest way of doing this is through Shared Preferences. Shared Preferences Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences. SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will receive it in an editor object. Its syntax is − Editor editor = sharedpreferences.edit(); editor.putString(“key”, “value”); editor.commit(); Apart from the putString method, there are methods available in the editor class that allows manipulation of data inside shared preferences. They are listed as follows − Sr.No Mode & description 1 apply() It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling 2 clear() It will remove all values from the editor 3 remove(String key) It will remove the value whose key has been passed as a parameter 4 putLong(String key, long value) It will save a long value in a preference editor 5 putInt(String key, int value) It will save a integer value in a preference editor 6 putFloat(String key, float value) It will save a float value in a preference editor Session Management through Shared Preferences In order to perform session management from shared preferences, we need to check the values or data stored in shared preferences in the onResume method. If we don”t have the data, we will start the application from the beginning as it is newly installed. But if we got the data, we will start from the where the user left it. It is demonstrated in the example below − Example The below example demonstrates the use of Session Management. It crates a basic application that allows you to login for the first time. And then when you exit the application without logging out, you will be brought back to the same place if you start the application again. But if you logout from the application, you will be brought back to the main login screen. To experiment with this example, you need to run this on an actual device or in an emulator. Steps Description 1 You will use android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add progress code to add session code. 3 Create New Activity and it name as second.java.Edit this file to add progress code to add session code. 4 Modify res/layout/activity_main.xml file to add respective XML code. 5 Modify res/layout/second_main.xml file to add respective XML code. 7 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of MainActivity.java. package com.example.sairamkrishna.myapplication; 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.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText ed1,ed2,ed3; Button b1; Intent in; public static final String MyPREFERENCES = “MyPrefs” ; public static final String Name = “nameKey”; public static final String Phone = “phoneKey”; public static final String Email = “emailKey”; SharedPreferences sharedpreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1=(EditText)findViewById(R.id.editText); ed2=(EditText)findViewById(R.id.editText2); ed3=(EditText)findViewById(R.id.editText3); b1=(Button)findViewById(R.id.button); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String n = ed1.getText().toString(); String ph = ed2.getText().toString(); String e = ed3.getText().toString(); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Name, n); editor.putString(Phone, ph); editor.putString(Email, e); editor.commit(); in = new Intent(MainActivity.this,second_main.class); startActivity(in); } }); } } Here is the content of second_main.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; public class second_main extends Activity { Button bu=null; Button bu2=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_main); bu=(Button)findViewById(R.id.button2); bu2=(Button)findViewById(R.id.button3); } public void logout(View view){ SharedPreferences sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.clear(); editor.commit(); } public void close(View view){ finish(); } } Here is the content of 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: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”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Shared Preference” android:id=”@+id/textView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”35dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:textSize=”35dp” android:textColor=”#ff16ff01″ /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:layout_below=”@+id/textView2″ android:layout_marginTop=”67dp” android:hint=”Name” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText2″ android:layout_below=”@+id/editText” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:hint=”Pass” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText3″ android:layout_below=”@+id/editText2″ android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:hint=”Email” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”login” android:id=”@+id/button” android:layout_below=”@+id/editText3″ android:layout_centerHorizontal=”true” android:layout_marginTop=”50dp” /> </RelativeLayout> Here is the content of second_main.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”vertical” android:layout_width=”match_parent” android:layout_height=”match_parent”> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Logout” android:onClick=”logout” android:id=”@+id/button2″ android:layout_gravity=”center_horizontal” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:layout_marginTop=”191dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Close” android:onClick=”close” android:id=”@+id/button3″ android:layout_below=”@+id/button2″ android:layout_centerHorizontal=”true” android:layout_marginTop=”69dp” /> </RelativeLayout> Here is the content of Strings.xml. <resources> <string name=”app_name”>My Application</string> </resources> Here is the content of AndroidManifest.xml. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <activity android:name=”.second”></activity> </application> </manifest> Let”s try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window − Type in your username and password (type anything you like, but remember what you type), and click on login button. It is shown in the image below − As soon as you click on login button, you will be brought to this Welcome screen. Now your login information is stored in shared preferences. Now click on Exit without logout button and you will
Category: Android
Android – Navigation In this chapter, we will see that how you can provide navigation forward and backward between an application. We will first look at how to provide up navigation in an application. Providing Up Navigation The up navigation will allow our application to move to previous activity from the next activity. It can be done like this. To implement Up navigation, the first step is to declare which activity is the appropriate parent for each activity. You can do it by specifying parentActivityName attribute in an activity. Its syntax is given below − android:parentActivityName = “com.example.test.MainActivity” After that you need to call setDisplayHomeAsUpEnabled method of getActionBar() in the onCreate method of the activity. This will enable the back button in the top action bar. getActionBar().setDisplayHomeAsUpEnabled(true); The last thing you need to do is to override onOptionsItemSelected method. when the user presses it, your activity receives a call to onOptionsItemSelected(). The ID for the action is android.R.id.home.Its syntax is given below − public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } } Handling device back button Since you have enabled your back button to navigate within your application, you might want to put the application close function in the device back button. It can be done by overriding onBackPressed and then calling moveTaskToBack and finish method. Its syntax is given below − @Override public void onBackPressed() { moveTaskToBack(true); MainActivity2.this.finish(); } Apart from this setDisplayHomeAsUpEnabled method, there are other methods available in ActionBar API class. They are listed below − Sr.No Method & description 1 addTab(ActionBar.Tab tab, boolean setSelected) This method adds a tab for use in tabbed navigation mode 2 getSelectedTab() This method returns the currently selected tab if in tabbed navigation mode and there is at least one tab present 3 hide() This method hide the ActionBar if it is currently showing 4 removeAllTabs() This method remove all tabs from the action bar and deselect the current tab 5 selectTab(ActionBar.Tab tab) This method select the specified tab Example The below example demonstrates the use of Navigation. It crates a basic application that allows you to navigate within your application. To experiment with this example, you need to run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add Activity code. 3 Create a new activity with the name of second_main.java and edit it to add activity code. 4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 5 Modify layout XML file res/layout/second.xml add any GUI component if required. 6 Modify AndroidManifest.xml to add necessary code. 7 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in=new Intent(MainActivity.this,second_main.class); startActivity(in); } }); } } Here is the content of src/second_main.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Created by Sairamkrishna on 4/6/2015. */ public class second_main extends Activity { WebView wv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_activity2); wv = (WebView) findViewById(R.id.webView); wv.setWebViewClient(new MyBrowser()); wv.getSettings().setLoadsImagesAutomatically(true); wv.getSettings().setJavaScriptEnabled(true); wv.loadUrl(“https://www.tutorialspoint.com”); } private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } } Here is the content of activity_main.xml. In the below code abcindicates the logo of tutorialspoint.com <?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: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” android:transitionGroup=”true”> <TextView android:text=”Navigation example” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:theme=”@style/Base.TextAppearance.AppCompat” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”first page” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:layout_marginTop=”61dp” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” /> </RelativeLayout> Here is the content of activity_main_activity2.xml. <?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” android:weightSum=”1″> <WebView android:layout_width=”match_parent” android:layout_height=”wrap_content” android:id=”@+id/webView” android:layout_gravity=”center_horizontal” android:layout_weight=”1.03″ /> </LinearLayout> Here is the content of Strings.xml. <resources> <string name=”app_name”>My Application</string> </resources> Here is the content of AndroidManifest.xml. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <uses-permission android:name=”android.permission.INTERNET”></uses-permission> <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <activity android:name=”.second_main”></activity> </application> </manifest> Let”s try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window− Now just press on button and the following screen will be shown to you. Second activity contains webview, it has redirected to tutorialspoint.com as shown below Learn online work project make money
Android – Wi-Fi Android allows applications to access to view the access the state of the wireless connections at very low level. Application can access almost all the information of a wifi connection. The information that an application can access includes connected network”s link speed,IP address, negotiation state, other networks information. Applications can also scan, add, save, terminate and initiate Wi-Fi connections. Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this class by calling getSystemService method. Its syntax is given below − WifiManager mainWifiObj; mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE); In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can be registered using registerReceiver method with argument of your receiver class object. Its syntax is given below − class WifiScanReceiver extends BroadcastReceiver { public void onReceive(Context c, Intent intent) { } } WifiScanReceiver wifiReciever = new WifiScanReceiver(); registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); The wifi scan can be start by calling the startScan method of the WifiManager class. This method returns a list of ScanResult objects. You can access any object by calling the get method of list. Its syntax is given below − List<ScanResult> wifiScanList = mainWifiObj.getScanResults(); String data = wifiScanList.get(0).toString(); Apart from just Scanning, you can have more control over your WIFI by using the methods defined in WifiManager class. They are listed as follows − Sr.No Method & Description 1 addNetwork(WifiConfiguration config) This method add a new network description to the set of configured networks. 2 createWifiLock(String tag) This method creates a new WifiLock. 3 disconnect() This method disassociate from the currently active access point. 4 enableNetwork(int netId, boolean disableOthers) This method allow a previously configured network to be associated with. 5 getWifiState() This method gets the Wi-Fi enabled state 6 isWifiEnabled() This method return whether Wi-Fi is enabled or disabled. 7 setWifiEnabled(boolean enabled) This method enable or disable Wi-Fi. 8 updateNetwork(WifiConfiguration config) This method update the network description of an existing configured network. Example Here is an example demonstrating the use of WIFI. It creates a basic application that open your wifi and close your wifi To experiment with this example, you need to run this on an actual device on which wifi is turned on. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add WebView code. 3 Modify the res/layout/activity_main to add respective XML components 4 Modify the AndroidManifest.xml to add the necessary permissions 5 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.net.wifi.WifiManager; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { Button enableButton,disableButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); enableButton=(Button)findViewById(R.id.button1); disableButton=(Button)findViewById(R.id.button2); enableButton.setOnClickListener(new OnClickListener(){ public void onClick(View v){ WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(true); } }); disableButton.setOnClickListener(new OnClickListener(){ public void onClick(View v){ WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(false); } }); } } Following is the modified content of the xml res/layout/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: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”> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <Button android:id=”@+id/button1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_marginLeft=”76dp” android:text=”Enable Wifi” android:layout_centerVertical=”true” android:layout_alignEnd=”@+id/imageView” /> <Button android:id=”@+id/button2″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Disable Wifi” android:layout_marginBottom=”93dp” android:layout_alignParentBottom=”true” android:layout_alignStart=”@+id/imageView” /> </RelativeLayout> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” /> <uses-permission android:name=”android.permission.CHANGE_WIFI_STATE” /> <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and It will shows the following image− Now click on disable wifi button.then the sample output should be like this − Learn online work project make money
Android – SQLite Database SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don”t need to establish any kind of connections for it like JDBC,ODBC e.t.c Database – Package The main package is android.database.sqlite that contains the classes to manage your own databases Database – Creation In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below SQLiteDatabase mydatabase = openOrCreateDatabase(“your database name”,MODE_PRIVATE,null); Apart from this , there are other functions available in the database package , that does this job. They are listed below Sr.No Method & Description 1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler) This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY 2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags) It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases 3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory) It not only opens but create the database if it not exists. This method is equivalent to openDatabase method. 4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory) This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to file.getPath() Database – Insertion we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below mydatabase.execSQL(“CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);”); mydatabase.execSQL(“INSERT INTO TutorialsPoint VALUES(”admin”,”admin”);”); This will insert some values into our table in our database. Another method that also does the same job but take some additional parameter is given below Sr.No Method & Description 1 execSQL(String sql, Object[] bindArgs) This method not only insert data , but also used to update or modify already existing data in database using bind arguments Database – Fetching We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. Cursor resultSet = mydatbase.rawQuery(“Select * from TutorialsPoint”,null); resultSet.moveToFirst(); String username = resultSet.getString(0); String password = resultSet.getString(1); There are other functions available in the Cursor class that allows us to effectively retrieve the data. That includes Sr.No Method & Description 1 getColumnCount() This method return the total number of columns of the table. 2 getColumnIndex(String columnName) This method returns the index number of a column by specifying the name of the column 3 getColumnName(int columnIndex) This method returns the name of the column by specifying the index of the column 4 getColumnNames() This method returns the array of all the column names of the table. 5 getCount() This method returns the total number of rows in the cursor 6 getPosition() This method returns the current position of the cursor in the table 7 isClosed() This method returns true if the cursor is closed and return false otherwise Database – Helper class For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is given below public class DBHelper extends SQLiteOpenHelper { public DBHelper(){ super(context,DATABASE_NAME,null,1); } public void onCreate(SQLiteDatabase db) {} public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {} } Example Here is an example demonstrating the use of SQLite Database. It creates a basic contacts applications that allows insertion, deletion and modification of contacts. To experiment with this example, you need to run this on an actual device on which camera is supported. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to get references of all the XML components and populate the contacts on listView. 3 Create new src/DBHelper.java that will manage the database work 4 Create a new Activity as DisplayContact.java that will display the contact on the screen 5 Modify the res/layout/activity_main to add respective XML components 6 Modify the res/layout/activity_display_contact.xml to add respective XML components 7 Modify the res/values/string.xml to add necessary string components 8 Modify the res/menu/display_contact.xml to add necessary menu components 9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option 10 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { public final static String EXTRA_MESSAGE = “MESSAGE”; private ListView obj; DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DBHelper(this); ArrayList array_list = mydb.getAllCotacts(); ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list); obj = (ListView)findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); obj.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { // TODO Auto-generated method stub int id_To_Search = arg2 + 1; Bundle dataBundle = new Bundle(); dataBundle.putInt(“id”, id_To_Search); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.item1:Bundle dataBundle = new Bundle(); dataBundle.putInt(“id”, 0); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } public boolean onKeyDown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); } return super.onKeyDown(keycode, event); } } Following is the modified content of display contact activity
Android – Sensors Most of the android devices have built-in sensors that measure motion, orientation, and various environmental condition. The android platform supports three broad categories of sensors. Motion Sensors Environmental sensors Position sensors Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is, android allows us to get the raw data from these sensors and use it in our application. For this android provides us with some classes. Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as follows. SensorManager sMgr; sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE); The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor() method of the SensorManager class. Its syntax is given below − Sensor light; light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT); Once that sensor is declared , you need to register its listener and override two methods which are onAccuracyChanged and onSensorChanged. Its syntax is as follows − sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL); public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { } Getting list of sensors supported You can get a list of sensors supported by your device by calling the getSensorList method, which will return a list of sensors containing their name and version number and much more information. You can then iterate the list to get the information. Its syntax is given below − sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE); List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL); for(Sensor sensor: list){ } Apart from the these methods, there are other methods provided by the SensorManager class for managing sensors framework. These methods are listed below − Sr.No Method & description 1 getDefaultSensor(int type) This method get the default sensor for a given type. 2 getInclination(float[] I) This method computes the geomagnetic inclination angle in radians from the inclination matrix. 3 registerListener(SensorListener listener, int sensors, int rate) This method registers a listener for the sensor 4 unregisterListener(SensorEventListener listener, Sensor sensor) This method unregisters a listener for the sensors with which it is registered. 5 getOrientation(float[] R, float[] values) This method computes the device”s orientation based on the rotation matrix. 6 getAltitude(float p0, float p) This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level. Example Here is an example demonstrating the use of SensorManager class. It creates a basic application that allows you to view the list of sensors on your device. To experiment with this example , you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components. 4 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import java.util.List; import android.hardware.Sensor; import android.hardware.SensorManager; public class MainActivity extends Activity { TextView tv1=null; private SensorManager mSensorManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv1 = (TextView) findViewById(R.id.textView2); tv1.setVisibility(View.GONE); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); List<Sensor> mList= mSensorManager.getSensorList(Sensor.TYPE_ALL); for (int i = 1; i < mList.size(); i++) { tv1.setVisibility(View.VISIBLE); tv1.append(“n” + mList.get(i).getName() + “n” + mList.get(i).getVendor() + “n” + mList.get(i).getVersion()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } Following is the modified content of the xml activity_main.xml. In the below code abc indicates about the logo of tutorialspoint.com <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” android:transitionGroup=”true”> <TextView android:text=”Sensor ” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:theme=”@style/Base.TextAppearance.AppCompat” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”New Text” android:id=”@+id/textView2″ android:layout_below=”@+id/imageView” android:layout_alignParentBottom=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> <string name=”hello_world”>Hello world!</string> <string name=”action_settings”>Settings</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Now if you will look at your device screen, you will see the list of sensors supported by your device along with their name and version and other information. If you would run this application on different devices, the output would be different because the output depends upon the number of sensors supported by your device. Learn online work project make money
Android – Login Screen A login application is the screen asking your credentials to login to some particular application. You might have seen it when logging into facebook,twitter e.t.c This chapter explains, how to create a login screen and how to manage security when false attempts are made. First you have to define two TextView asking username and password of the user. The password TextView must have inputType set to password. Its syntax is given below − <EditText android:id = “@+id/editText2” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:inputType = “textPassword” /> <EditText android:id = “@+id/editText1” android:layout_width = “wrap_content” android:layout_height = “wrap_content” /> Define a button with login text and set its onClick Property. After that define the function mentioned in the onClick property in the java file. <Button android:id = “@+id/button1” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:onClick = “login” android:text = “@string/Login” /> In the java file, inside the method of onClick get the username and passwords text using getText() and toString() method and match it with the text using equals() function. EditText username = (EditText)findViewById(R.id.editText1); EditText password = (EditText)findViewById(R.id.editText2); public void login(View view){ if(username.getText().toString().equals(“admin”) && password.getText().toString().equals(“admin”)){ //correcct password }else{ //wrong password } The last thing you need to do is to provide a security mechanism, so that unwanted attempts should be avoided. For this initialize a variable and on each false attempt, decrement it. And when it reaches to 0, disable the login button. int counter = 3; counter–; if(counter==0){ //disble the button, close the application e.t.c } Example Here is an example demonstrating a login application. It creates a basic application that gives you only three attempts to login to an application. To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 3 Modify src/MainActivity.java file to add necessary code. 4 Modify the res/layout/activity_main to add respective XML components 5 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { Button b1,b2; EditText ed1,ed2; TextView tx1; int counter = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button)findViewById(R.id.button); ed1 = (EditText)findViewById(R.id.editText); ed2 = (EditText)findViewById(R.id.editText2); b2 = (Button)findViewById(R.id.button2); tx1 = (TextView)findViewById(R.id.textView3); tx1.setVisibility(View.GONE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(ed1.getText().toString().equals(“admin”) && ed2.getText().toString().equals(“admin”)) { Toast.makeText(getApplicationContext(), “Redirecting…”,Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), “Wrong Credentials”,Toast.LENGTH_SHORT).show(); tx1.setVisibility(View.VISIBLE); tx1.setBackgroundColor(Color.RED); counter–; tx1.setText(Integer.toString(counter)); if (counter == 0) { b1.setEnabled(false); } } } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. In the following code abc indicates about logo of tutorialspoint.com <?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: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”> <TextView android:text = “Login” android:layout_width=”wrap_content” android:layout_height = “wrap_content” android:id = “@+id/textview” android:textSize = “35dp” android:layout_alignParentTop = “true” android:layout_centerHorizontal = “true” /> <TextView android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:text = “Tutorials point” android:id = “@+id/textView” android:layout_below = “@+id/textview” android:layout_centerHorizontal = “true” android:textColor = “#ff7aff24” android:textSize = “35dp” /> <EditText android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:id = “@+id/editText” android:hint = “Enter Name” android:focusable = “true” android:textColorHighlight = “#ff7eff15” android:textColorHint = “#ffff25e6” android:layout_marginTop = “46dp” android:layout_below = “@+id/imageView” android:layout_alignParentLeft = “true” android:layout_alignParentStart = “true” android:layout_alignParentRight = “true” android:layout_alignParentEnd = “true” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <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:textColorHint=”#ffff299f” android:hint=”Password” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Attempts Left:” android:id=”@+id/textView2″ android:layout_below=”@+id/editText2″ android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:textSize=”25dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”New Text” android:id=”@+id/textView3″ android:layout_alignTop=”@+id/textView2″ android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:layout_alignBottom=”@+id/textView2″ android:layout_toEndOf=”@+id/textview” android:textSize=”25dp” android:layout_toRightOf=”@+id/textview” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”login” android:id=”@+id/button” android:layout_alignParentBottom=”true” android:layout_toLeftOf=”@+id/textview” android:layout_toStartOf=”@+id/textview” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Cancel” android:id=”@+id/button2″ android:layout_alignParentBottom=”true” android:layout_toRightOf=”@+id/textview” android:layout_toEndOf=”@+id/textview” /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Type anything in the username and password field, and then press the login button. I put abc in the username field and abc in the password field. I got failed attempt. This is shown below − Do this two more time, and you will see that you have 0 login attempts left and your login button is disabled. Now open the application again, and this time enter correct username as admin and password as admin and click on login. You will be successfully login. If user press on cancel button, it will close an application of login screen. Learn online work project make money
Android – PHP/MYSQL In this chapter , we are going to explain, how you can integrate PHP and MYSQL with your android application. This is very useful in case you have a webserver, and you want to access its data on your android application. MYSQL is used as a database at the webserver and PHP is used to fetch data from the database. Our application will communicate with the PHP page with necessary parameters and PHP will contact MYSQL database and will fetch the result and return the results to us. PHP – MYSQL Creating Database MYSQL database can be created easily using this simple script. The CREATE DATABASE statement creates the database. <?php $con=mysqli_connect(“example.com”,”username”,”password”); $sql=”CREATE DATABASE my_db”; if (mysqli_query($con,$sql)) { echo “Database my_db created successfully”; } ?> Creating Tables Once database is created, its time to create some tables in the database. The CREATE TABLE statement creates the database. <?php $con=mysqli_connect(“example.com”,”username”,”password”,”my_db”); $sql=”CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role CHAR(30))”; if (mysqli_query($con,$sql)) { echo “Table have been created successfully”; } ?> Inserting Values in tables When the database and tables are created. Now its time to insert some data into the tables. The Insert Into statement creates the database. <?php $con=mysqli_connect(“example.com”,”username”,”password”,”my_db”); $sql=”INSERT INTO table1 (FirstName, LastName, Age) VALUES (”admin”, ”admin”,”adminstrator”)”; if (mysqli_query($con,$sql)) { echo “Values have been inserted successfully”; } ?> PHP – GET and POST methods PHP is also used to fetch the record from the mysql database once it is created. In order to fetch record some information must be passed to PHP page regarding what record to be fetched. The first method to pass information is through GET method in which $_GET command is used. The variables are passed in the url and the record is fetched. Its syntax is given below − <?php $con=mysqli_connect(“example.com”,”username”,”password”,”database name”); if (mysqli_connect_errno($con)) { echo “Failed to connect to MySQL: ” . mysqli_connect_error(); } $username = $_GET[”username”]; $password = $_GET[”password”]; $result = mysqli_query($con,”SELECT Role FROM table1 where Username=”$username” and Password=”$password””); $row = mysqli_fetch_array($result); $data = $row[0]; if($data){ echo $data; } mysqli_close($con); ?> The second method is to use POST method. The only change in the above script is to replace $_GET with $_POST. In Post method, the variables are not passed through URL. Android – Connecting MYSQL Connecting Via Get Method There are two ways to connect to MYSQL via PHP page. The first one is called Get method. We will use HttpGet and HttpClient class to connect. Their syntax is given below − URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link)); After that you need to call execute method of HttpClient class and receive it in a HttpResponse object. After that you need to open streams to receive the data. HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); Connecting Via Post Method In the Post method, the URLEncoder,URLConnection class will be used. The urlencoder will encode the information of the passing variables. It”s syntax is given below − URL url = new URL(link); String data = URLEncoder.encode(“username”, “UTF-8”) + “=” + URLEncoder.encode(username, “UTF-8”); data += “&” + URLEncoder.encode(“password”, “UTF-8”) + “=” + URLEncoder.encode(password, “UTF-8″); URLConnection conn = url.openConnection(); The last thing you need to do is to write this data to the link. After writing, you need to open stream to receive the responded data. OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); Example The below example is a complete example of connecting your android application with MYSQL database via PHP page. It creates a basic application that allows you to login using GET and POST method. PHP – MYSQL part In this example a database with the name of temp has been created at 000webhost.com. In that database, a table has been created with the name of table1. This table has three fields. (Username, Password, Role). The table has only one record which is (“admin”,”admin”,”administrator”). The php page has been given below which takes parameters by post method. <?php $con=mysqli_connect(“mysql10.000webhost.com”,”username”,”password”,”db_name”); if (mysqli_connect_errno($con)) { echo “Failed to connect to MySQL: ” . mysqli_connect_error(); } $username = $_POST[”username”]; $password = $_POST[”password”]; $result = mysqli_query($con,”SELECT Role FROM table1 where Username=”$username” and Password=”$password””); $row = mysqli_fetch_array($result); $data = $row[0]; if($data){ echo $data; } mysqli_close($con); ?> Android Part To experiment with this example , you need to run this on an actual device on which wifi internet is connected. Steps Description 1 You will use Android studio IDE to create an Android application and name it as PHPMYSQL under a package com.example.phpmysql. 2 Modify src/MainActivity.java file to add Activity code. 3 Create src/SiginActivity.java file to add PHPMYSQL code. 4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 5 Modify res/values/string.xml file and add necessary string components. 6 Modify AndroidManifest.xml to add necessary permissions. 7 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of src/com.example.phpmysql/MainActivity.java. package com.example.phpmysql; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private EditText usernameField,passwordField; private TextView status,role,method; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); usernameField = (EditText)findViewById(R.id.editText1); passwordField = (EditText)findViewById(R.id.editText2); status = (TextView)findViewById(R.id.textView6); role = (TextView)findViewById(R.id.textView7); method = (TextView)findViewById(R.id.textView9); } public void login(View view){ String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); method.setText(“Get Method”); new SigninActivity(this,status,role,0).execute(username,password); } public void loginPost(View view){ String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); method.setText(“Post Method”); new SigninActivity(this,status,role,1).execute(username,password); } } Here is the content of src/com.example.phpmysql/SigninActivity.java. package com.example.phpmysql; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.os.AsyncTask; import android.widget.TextView; public class SigninActivity extends AsyncTask{ private TextView statusField,roleField; private Context context; private int byGetOrPost = 0; //flag 0 means get and 1 means post.(By default it is get.) public SigninActivity(Context context,TextView statusField,TextView roleField,int flag) { this.context = context; this.statusField = statusField; this.roleField = roleField; byGetOrPost = flag; } protected void onPreExecute(){ } @Override protected String doInBackground(String… arg0)
Android – Shared Preferences Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences. SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); The first parameter is the key and the second parameter is the MODE. Apart from private there are other modes available that are listed below − Sr.No Mode & description 1 MODE_APPEND This will append the new preferences with the already existing preferences 2 MODE_ENABLE_WRITE_AHEAD_LOGGING Database open flag. When it is set , it would enable write ahead logging by default 3 MODE_MULTI_PROCESS This method will check for modification of preferences even if the sharedpreference instance has already been loaded 4 MODE_PRIVATE By setting this mode, the file can only be accessed using calling application 5 MODE_WORLD_READABLE This mode allow other application to read the preferences 6 MODE_WORLD_WRITEABLE This mode allow other application to write the preferences You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will receive it in an editor object. Its syntax is − Editor editor = sharedpreferences.edit(); editor.putString(“key”, “value”); editor.commit(); Apart from the putString method , there are methods available in the editor class that allows manipulation of data inside shared preferences. They are listed as follows − Sr. NO Mode & description 1 apply() It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling 2 clear() It will remove all values from the editor 3 remove(String key) It will remove the value whose key has been passed as a parameter 4 putLong(String key, long value) It will save a long value in a preference editor 5 putInt(String key, int value) It will save a integer value in a preference editor 6 putFloat(String key, float value) It will save a float value in a preference editor Example This example demonstrates the use of the Shared Preferences. It display a screen with some text fields, whose value are saved when the application is closed and brought back when it is opened again. To experiment with this example, you need to run this on an actual device on after developing the application according to the steps below − Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add progress code to display the spinning progress dialog. 3 Modify res/layout/activity_main.xml file to add respective XML code. 4 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Context; 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 ed1,ed2,ed3; Button b1; public static final String MyPREFERENCES = “MyPrefs” ; public static final String Name = “nameKey”; public static final String Phone = “phoneKey”; public static final String Email = “emailKey”; SharedPreferences sharedpreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1=(EditText)findViewById(R.id.editText); ed2=(EditText)findViewById(R.id.editText2); ed3=(EditText)findViewById(R.id.editText3); b1=(Button)findViewById(R.id.button); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String n = ed1.getText().toString(); String ph = ed2.getText().toString(); String e = ed3.getText().toString(); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Name, n); editor.putString(Phone, ph); editor.putString(Email, e); editor.commit(); Toast.makeText(MainActivity.this,”Thanks”,Toast.LENGTH_LONG).show(); } }); } } Following is the content of the modified main activity fileres/layout/activiy_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: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”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Shared Preference ” android:id=”@+id/textView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”35dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:textSize=”35dp” android:textColor=”#ff16ff01″ /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:layout_below=”@+id/textView2″ android:layout_marginTop=”67dp” android:hint=”Name” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText2″ android:layout_below=”@+id/editText” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:hint=”Pass” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText3″ android:layout_below=”@+id/editText2″ android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:hint=”Email” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Save” android:id=”@+id/button” android:layout_below=”@+id/editText3″ android:layout_centerHorizontal=”true” android:layout_marginTop=”50dp” /> </RelativeLayout> Following is the content of the modified content of file res/values/strings.xml. <resources> <string name=”app_name”>My Application</string> </resources> Following is the content default file AndroidManifest.xml. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display following screen − Now just put in some text in the field. Like i put some random name and other information and click on save button. Now when you press save button, the text will be saved in the shared preferences. Now press back button and exit the application. Now open it again and you will see all the text you have written back in your application. Learn online work project make money
Learn online work project make money
Android – LinkedIn Integration ”; Previous Next Android allows your application to connect to Linkedin and share data or any kind of updates on Linkedin. This chapter is about integrating Linkedin into your application. There are two ways through which you can integrate Linkedin and share something from your application. These ways are listed below. Linkedin SDK (Scribe) Intent Share Integrating Linkedin SDK This is the first way of connecting with Linkedin. You have to register your application and then receive some Application Id , and then you have to download the Linkedin SDK and add it to your project. The steps are listed below. Registering your application Create a new Linkedin application at https://www.linkedin.com/secure/developer. Click on add new application. It is shown below − Now fill in your application name , description and your website url. It is shown below − If everything works fine, you will receive an API key with the secret. Just copy the API key and save it somewhere. It is shown in the image below − Downloading SDK and integrating it Download Linkedin sdk here. Copy the scribe-1.3.0.jar jar into your project libs folder. Posting updates on Linkedin application Once everything is complete, you can run the Linkedin samples which can be found here. Intent share Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the Linkedin application handles it. We will simply call the Linkedin application and pass the data to share. This way, we can share something on Linkedin. Android provides intent library to share data between activities and applications. In order to use it as share intent, we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below − Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); Next thing you need to is to define the type of data to pass , and then pass the data. Its syntax is given below − shareIntent.setType(“text/plain”); shareIntent.putExtra(Intent.EXTRA_TEXT, “Hello, from tutorialspoint”); startActivity(Intent.createChooser(shareIntent, “Share your thoughts”)); Apart from the these methods , there are other methods available that allows intent handling. They are listed below − Sr.No Method & description 1 addCategory(String category) This method add a new category to the intent. 2 createChooser(Intent target, CharSequence title) Convenience function for creating a ACTION_CHOOSER Intent 3 getAction() This method retrieve the general action to be performed, such as ACTION_VIEW 4 getCategories() This method return the set of all categories in the intent.nt and the current scaling event 5 putExtra(String name, int value) This method add extended data to the intent. 6 toString() This method returns a string containing a concise, human-readable description of this object Example Here is an example demonstrating the use of IntentShare to share data on Linkedin. It creates a basic application that allows you to share some text on Linkedin. To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.FileNotFoundException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private ImageView img; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = (ImageView) findViewById(R.id.imageView); Button b1 = (Button) findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.parse(“android. resource://comexample.sairamkrishna.myapplication/*”); try { InputStream stream = getContentResolver().openInputStream(screenshotUri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } sharingIntent.setType(“image/jpeg”); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); startActivity(Intent.createChooser(sharingIntent, “Share image using”)); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. In the below code abc indicates the logo of tutorialspoint.com <?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: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”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”30dp” android:text=”Linkedin Share” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:textSize=”35dp” android:textColor=”#ff16ff01″ /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” android:src=”@drawable/logo”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Share” android:id=”@+id/button” android:layout_marginTop=”61dp” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” /> </RelativeLayout> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display your default screen − Now just tap on the image logo and you will see a list of share providers. Now just select Linkedin from that list and then write any message. It is shown in the image below − Now it shows updating information Print Page Previous Next Advertisements ”;