Android Shared Preferences Guide
Android Shared Preferences Guide
Chapter 5
Method Description
getPreferences() This method is for activity level preferences and each activity will have it's
own preference file and by default this method retrieves a default shared
preference file that belongs to the activity.
getSharedPreferences() This method is useful to get the values from multiple shared preference files
by passing the name as parameter to identify the file. We can call this from
any Context in our app.
Following are the different ways to initialize the Shared Preferences in our application.
If we are using single shared preference file for our activity, then we need to initialize
the SharedPreferences object by using getPreferences() method like as shown below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
In case, if we are using multiple shared preference files, then we need to initialize the SharedPreferences object
by using getSharedPreferences() method like as shown below.
SharedPreferences sharedPref = getSharedPreferences("filename1",Context.MODE_PRIVATE);
Here, the name “filename1” is the preference file, which we want to read the values based on our requirements
and the context mode MODE_PRIVATE, will make sure that the file can be accessed only within our application.
SEng3035 Page 1
Mobile Programming
If you observe above code snippet, we are getting the values from shared preferences using a methods such
as getInt(), getFloat(), etc. by providing the key for the value which we want to get.
Deleting from Shared Preferences
To delete a value from Shared Preferences file, we need to call a remove() method by providing the key for the
value which we want to delete like as shown below.
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("keyname");editor.commit();
If you observe above code snippet, we are deleting the values from shared preferences using a method
called remove() by providing the key for the value which we want to delete and committing the changes to shared
preferences file using commit() method.
Clearing from Shared Preferences
We can clear all the data from Shared Preferences file using clear() method like as shown below.
SEng3035 Page 2
Mobile Programming
If you observe above code snippet, we are clearing all the values from shared preferences using a method
called clear() and committing the changes to shared preferences file using commit() method.
Now we will see how to store and retrieve primitive data type key-value pairs in shared preferences file
using SharedPreferences object in android application with examples.
Android Shared Preferences Example
Following is the example of storing and retrieving the primitive data type values from shared preferences file
using SharedPreferences.
Create a new android application using android studio and give names as SharedPreferencesExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like
as shown below.
activity_main.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">
<TextView
android:id="@+id/fstTxt" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:layout_marginTop="150dp" android:text="UserName" />
<EditText
android:id="@+id/txtName" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10"/>
<TextView
android:id="@+id/secTxt" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Password" android:layout_marginLeft="100dp" /
>
<EditText
android:id="@+id/txtPwd" android:inputType="textPassword"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="100dp" android:ems="10" />
<Button
android:id="@+id/btnLogin" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:text="Login" />
</LinearLayout>
Now we will create another layout resource file details.xml in \res\layout path to get the
first activity (activity_main.xml) details in second activity file for that right click on your layout folder Go
to New select Layout Resource File and give name as details.xml.
Once we create a new layout resource file details.xml, open it and write the code like as shown below
details.xml
SEng3035 Page 3
Mobile Programming
<?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">
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/resultView" android:layout_gravity="center"
android:layout_marginTop="170dp" android:textSize="20dp"/>
<Button
android:id="@+id/btnLogOut" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_gravity="center"
android:layout_marginTop="20dp" android:text="Log Out" />
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.example.sharedpreferencesexample path
and write the code like as shown below
MainActivity.java
import android.content.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
EditText uname, pwd;
Button loginBtn;
SharedPreferences pref;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
loginBtn = (Button)findViewById(R.id.btnLogin);
pref = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(MainActivity.this,DetailsActivity.class);
if(pref.contains("username") && pref.contains("password")){
startActivity(intent);
}
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getText().toString();
String password = pwd.getText().toString();
if(username.equals("abebe") && password.equals("abc123")){
SharedPreferences.Editor editor = pref.edit();
editor.putString("username",username);
editor.putString("password",password);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Successful",Toast.LENGTH_SHORT).show();
SEng3035 Page 4
Mobile Programming
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(),"Credentials are not
valid",Toast.LENGTH_SHORT).show();
} } });
}
}
If you observe above code, we are checking whether the entered username and password details matching or not
based on that we are saving the details in shared preferences file and redirecting the user to another activity.
Now we will create another activity file DetailsActivity.java in \java\
com.examplw.sharedpreferencesexample path to show the details from shared preference file for that right click
on your application folder Go to New select JavaClass and give name as DetailsActivity.java.
Once we create a new activity file DetailsActivity.java, open it and write the code like as shown below
DetailsActivity.java
import android.content.*;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.*;
public class DetailsActivity extends AppCompatActivity {
SharedPreferences prf;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button btnLogOut = (Button)findViewById(R.id.btnLogOut);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(DetailsActivity.this,MainActivity.class);
result.setText("Hello, "+prf.getString("username",null));
btnLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = prf.edit();
editor.clear();
editor.commit();
startActivity(intent);
}
});
}
}
Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.
AndroidManifest.xml
SEng3035 Page 5
Mobile Programming
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sharedpreferencesexample">
<application
android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DetailsActivity" android:label="Shared Preferences - Details"></activity>
</application>
</manifest>
If you observe above example, we are checking whether the entered user details matching or not based on that we
are saving the user details in shared preferences file and redirecting the user to another activity file
(DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.
SEng3035 Page 6
Mobile Programming
activity_main.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">
<TextView
android:id="@+id/fstTxt" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="100dp" android:layout_marginTop="150dp" android:text="UserName" />
<EditText
android:id="@+id/txtName" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10"/>
<TextView
android:id="@+id/secTxt" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Password" android:layout_marginLeft="100dp" /
>
<EditText
android:id="@+id/txtPwd" android:inputType="textPassword" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10" />
<Button
android:id="@+id/btnLogin" android:layout_width="wrap_content"ndroid:layout_height="wrap_content
"
android:layout_marginLeft="100dp" android:text="Login" />
</LinearLayout>
Now we will create another layout resource file details.xml in \res\layout path to get the
first activity (activity_main.xml) details in second activity file for that right click on your layout folder Go
to New select Layout Resource File and give name as details.xml.
Once we create a new layout resource file details.xml, open it and write the code like as shown below
details.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">
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"android:textSize="20dp"
android:id="@+id/resultView" android:layout_gravity="center" android:layout_marginTop="170dp"/>
<Button
android:id="@+id/btnLogOut" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_gravity="center"
android:layout_marginTop="20dp" android:text="Log Out" />
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.example.sharedpreferencesexample path
and write the code like as shown below
MainActivity.java
import android.content.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
SEng3035 Page 7
Mobile Programming
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
EditText uname, pwd;
Button loginBtn;
SharedPreferences pref;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
loginBtn = (Button)findViewById(R.id.btnLogin);
pref = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(MainActivity.this,DetailsActivity.class);
if(pref.contains("username") && pref.contains("password")){
startActivity(intent);
}
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getText().toString();
String password = pwd.getText().toString();
if(username.equals("abebe") && password.equals("abc123")){
SharedPreferences.Editor editor = pref.edit();
editor.putString("username",username);
editor.putString("password",password);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Successful",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(),"Credentials are not
valid",Toast.LENGTH_SHORT).show();
}
}
});
}
}
If you observe above code, we are checking whether the entered username and password details matching or not
based on that we are saving the details in shared preferences file and redirecting the user to another activity.Now
we will create another activity file DetailsActivity.java in \java\
com.example.sharedpreferencesexample path to show the details from shared preference file for that right
click on your application folder Go to New select JavaClass and give name as DetailsActivity.java.
Once we create a new activity file DetailsActivity.java, open it and write the code like as shown below
DetailsActivity.java
SEng3035 Page 8
Mobile Programming
import android.content.*;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.*;
public class DetailsActivity extends AppCompatActivity {
SharedPreferences prf;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button btnLogOut = (Button)findViewById(R.id.btnLogOut);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(DetailsActivity.this,MainActivity.class);
result.setText("Hello, "+prf.getString("username",null));
btnLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = prf.edit();
editor.clear();
editor.commit();
startActivity(intent);
}
});
}
}
Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sharedpreferencesexample">
<application
android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DetailsActivity" android:label="Shared Preferences - Details"></activity>
</application>
</manifest>
SEng3035 Page 9
Mobile Programming
If you observe above example, we are checking whether the entered user details matching or not based on that we
are saving the user details in shared preferences file and redirecting the user to another activity file
(DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.
In android, Internal Storage is useful to store the data files locally on the device’s internal memory
using FileOutputStream object. After storing the data files in device internal storage, we can read the data file
from device using FileInputStream object.
The data files saved in internal storage is managed by an android framework and it can be accessed anywhere
within the app to read or write data into the file, but it’s not possible to access the file from any other app so it’s
secured. When the user uninstall the app, automatically these data files will be removed from the device internal
storage.
Write a File to Internal Storage
By using android FileOutputStream object openFileOutput method, we can easily create and write a data to a
file in device’s internal storage.
Following is the code snippet to create and write a private file to the device internal memory.
String FILENAME = "user_details";
String name = "abebe";
FileOutputStream fstream = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fstream.write(name.getBytes());
fstream.close();
If you observe above code, we are creating and writing a file in device internal storage by
using FileOutputStreamobject openFileOutput method with file name and MODE_PRIVATE mode to make
the file private to our application. We used write() method to write the data in file and used close() method to
close the stream.In android, we have a different mode such
as MODE_APPEND, MODE_WORLD_READBLE, MODE_WORLD_WRITEABLE, etc. to use it in our application
based on your requirements.
Apart from above methods write() and close(), FileOutputStream object is having other methods, those are
Method Description
getChannel() It returns the unique FileChannel object associated with this file output
stream.
getFD() It returns the file descriptor which is associated with the stream.
write(byte[] b, int off, int len) It writes len bytes from the specified byte array starting at offset off to the
file output stream.
SEng3035 Page 10
Mobile Programming
If you observe above code, we are reading a file from device internal storage by using FileInputStream object
openFileInput method with file name. We used read() method to read one character at a time from the file and used
close() method to close the stream.
Apart from above methods read() and close(), FileInputStream object is having other methods, those are
Method Description
getChannel() It returns the unique FileChannel object associated with this file output stream.
getFD() It returns the file descriptor which is associated with the stream.
read(byte[] b, int off, int len) It reads len bytes of data from the specified file input stream into an array of bytes.
Now we will see how to save files directly on the device’s internal memory and read the data files from device
internal memory by using FileOutputStream and FileInputStream objects in android application with examples.
activity_main.xml
SEng3035 Page 11
Mobile Programming
<?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">
<TextView
android:id="@+id/fstTxt" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="100dp" android:layout_marginTop="150dp" android:text="UserName" />
<EditText
android:id="@+id/txtName" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10"/>
<TextView
android:id="@+id/secTxt" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Password" android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd" android:inputType="textPassword" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10" />
<Button
android:id="@+id/btnSave" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:text="Save" />
</LinearLayout>
Now we will create another layout resource file details.xml in \res\layout path to get the first activity
(activity_main.xml) details in second activity file for that right click on your layout folder Go
to New select Layout Resource File and give name as details.xml.
Once we create a new layout resource file details.xml, open it and write the code like as shown below
details.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">
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"android:textSize="20dp"
android:id="@+id/resultView" android:layout_gravity="center" android:layout_marginTop="170dp"/>
<Button
android:id="@+id/btnBack" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_gravity="center"
SEng3035 Page 12
Mobile Programming
android:layout_marginTop="20dp" android:text="Back" />
</LinearLayout>
SEng3035 Page 13
Mobile Programming
If you observe above code, we are taking entered username and password details and saving it in device local file
and redirecting the user to another activity.
Now we will create another activity file DetailsActivity.java in \java\
com.example.internalstorageexample path to show the details from device internal storage for that right click
on your application folder Go to New select Java Class and give name as DetailsActivity.java. Once we
create a new activity file DetailsActivity.java, open it and write the code like as shown below
DetailsActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class DetailsActivity extends AppCompatActivity {
FileInputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SEng3035 Page 14
Mobile Programming
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button back = (Button)findViewById(R.id.btnBack);
try {
fstream = openFileInput("user_details");
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
fstream.close();
String details[] = sbuffer.toString().split("\n");
result.setText("Name: "+ details[0]+"\nPassword: "+details[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(DetailsActivity.this,MainActivity.class);
startActivity(intent);
} }); }
}
Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.internalstorageexample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
SEng3035 Page 15
Mobile Programming
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DetailsActivity" android:label="Internal Storage - Details"></activity>
</application>
</manifest>
If you observe above example, we are saving entered details file and redirecting the user to another activity file
(DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.
In android, External Storage is useful to store the data files publicly on the shared external storage
using FileOutputStream object. After storing the data files on external storage, we can read the data file from
external storage media using FileInputStream object. The data files saved in external storage are world-readable
and can be modified by the user when they enable USB mass storage to transfer files on a computer.
SEng3035 Page 16
Mobile Programming
boolean Available= false;
boolean Readable= false;
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
// Both Read and write operations available
Available= true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
// Only Read operation available
Available= true;
Readable= true;
} else {
// SD card not mounted
Available = false;
}
If you observe above code snippet, we used getExternalStorageState() method to know the status of media
mounted to a computer, such as missing, read-only or in some other state.
In android, by using getExternalStoragePublicDirectory() method we can access the files from appropriate
public directory by passing the type of directory we want, such as DIRECTORY_MUSIC,
DIRECTORY_PICTURES, DIRECTORY_RINGTONES, etc. based on our requirements.
If we save our files to corresponding media-type public directory, the system's media scanner can properly
categorize our files in the system.
Following is the example to create a directory for new photo album in the public pictures directory.
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
In case, if we are handling the files that are not intended for other apps to use, then we should use a private storage
directory on the external storage by calling getExternalFilesDir().
SEng3035 Page 17
Mobile Programming
fstream.write(name.getBytes());
fstream.close();
If you observe above code, we are creating and writing a file in device public Downloads folder by
using getExternalStoragePublicDirectory method. We used write() method to write the data in file and
used close()method to close the stream.
SEng3035 Page 18
Mobile Programming
<?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">
<TextView
android:id="@+id/fstTxt" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="100dp" android:layout_marginTop="150dp" android:text="UserName" />
<EditText
android:id="@+id/txtName" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="100dp" android:ems="10"/>
<TextView
android:id="@+id/secTxt" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Password" android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd" android:inputType="textPassword" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10" />
<Button
android:id="@+id/btnSave" android:layout_width="wrap_content"android:layout_height="wrap_content"
android:layout_marginLeft="100dp" android:text="Save" />
</LinearLayout>
SEng3035 Page 19
Mobile Programming
android:layout_gravity="center" android:layout_marginTop="20dp" android:text="Back" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
EditText uname, pwd;
Button saveBtn;
FileOutputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
saveBtn = (Button)findViewById(R.id.btnSave);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getText().toString()+"\n";
String password = pwd.getText().toString();
SEng3035 Page 20
Mobile Programming
try {
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{android.Manifest.permission.READ_EXTERNAL_STORAGE},23);
File folder =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(folder,"user_details");
fstream = new FileOutputStream(myFile);
fstream.write(username.getBytes());
fstream.write(password.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), "Details Saved in
"+myFile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this,DetailsActivity.class);
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
If you observe above code, we are taking entered username and password details and saving it in device external
memory and redirecting the user to another activity.
Now we will create another activity file DetailsActivity.java in \java\com.example.externalstorageexample path to
show the details from external storage for that right click on your application folder Go to New select Java
Class and give name as DetailsActivity.java.
Once we create a new activity file DetailsActivity.java, open it and write the code like as shown below
DetailsActivity.java
package com.example.externalstorageexample;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
SEng3035 Page 21
Mobile Programming
import android.view.View;
import android.widget.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DetailsActivity extends AppCompatActivity {
FileInputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button back = (Button)findViewById(R.id.btnBack);
try {
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(folder,"user_details");
fstream = new FileInputStream(myFile);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
fstream.close();
String details[] = sbuffer.toString().split("\n");
result.setText("Name: "+ details[0]+"\nPassword: "+details[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
back.setOnClickListener(new View.OnClickListener() {
@Override
SEng3035 Page 22
Mobile Programming
public void onClick(View v) {
intent = new Intent(DetailsActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
}
Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.externalstorageexample">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DetailsActivity" android:label="External Storage - Details"></activity>
</application>
</manifest>
If you observe above example, we are saving entered details file and redirecting the user to another activity file
(DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.
SEng3035 Page 23
Mobile Programming
5.4. SQLite
SQLite is an open source light weight relational database management system (RDBMS) used to perform database
operations, such as storing, updating, retrieving data from database. In our android applications Shared
Preferences, Internal Storage and External Storage options are useful to store and maintain the small amount of
data. In case, if we want to deal with large amount of data, then SQLite database is the preferable option to store
and maintain the data in structured format.
By default, Android comes with built-in SQLite Database support so we don’t need to do any configurations.
Just like we save the files on device’s internal storage, Android stores our database in a private disk space that’s
associated to our application and the data is secure, because by default this area is not accessible to other
applications.
The package android.database.sqlite contains all the required API’s to use SQLite database in our android
applications.
Now we will see how to create database and required tables in SQLite and perform CRUD (insert, update, delete
and select) operations in android applications.
Method Description
onCreate() This method is called only once throughout the application after database is created and the table
creation statements can be written in this method.
onUpgrade( This method is called whenever there is an updation in database like modifying the table
) structure, adding constraints to database, etc.
Now we will see how to perform CRUD (create, read, delete and update) operations in android applications.
If you observe above code, we are getting the data repository in write mode and adding required values to columns
and inserting into database.
Read the Data from SQLite Database
In android, we can read the data from SQLite database using query() method.The following code snippet shows
how to read the data from SQLite Database using query() method.
SEng3035 Page 25
Mobile Programming
If you observe above code, we are getting the details from required table using query() method based on our
requirements.
Update Data in SQLite Database
In android, we can update the data in SQLite database using update() method in android applications.The
following code snippet shows how to update the data in SQLite database using update() method.
//Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cVals = new ContentValues();
cVals.put(KEY_LOC, location);
cVals.put(KEY_DESG, designation);
int count = db.update(TABLE_Users, cVals, KEY_ID+" = ?",new String[]{String.valueOf(id)});
If you observe above code, we are updating the details using update() method based on our requirements.
Delete Data from SQLite Database
In android, we can delete data from SQLite database using delete() method.The following code snippet shows
how to delete the data from SQLite database using delete() method.
//Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Users, KEY_ID+" = ?",new String[]{String.valueOf(userid)});
If you observe above code, we are deleting the details using delete() method based on our requirements.Now we
will see how to create SQLite database and perform CRUD (insert, update, delete, select) operations on SQLite
Database in android application with examples.
SEng3035 Page 26
Mobile Programming
Once we create a new class file DbHandler.java, open it and write the code like as shown below
DbHandler.java
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
public class DbHandler extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "usersdb";
private static final String TABLE_Users = "userdetails";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LOC = "location";
private static final String KEY_DESG = "designation";
public DbHandler(Context context){
super(context,DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
String CREATE_TABLE = "CREATE TABLE " + TABLE_Users + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ KEY_LOC + " TEXT,"
+ KEY_DESG + " TEXT"+ ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Drop older table if exist
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Users);
// Create tables again
onCreate(db);
}
// **** CRUD (Create, Read, Update, Delete) Operations ***** //
SEng3035 Page 28
Mobile Programming
If you observe above code, we implemented all SQLite Database related activities to perform CRUD operations in
android application.Now open activity_main.xml file from \res\layout folder path and write the code like as
shown below.
activity_main.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">
<TextView
android:id="@+id/fstTxt" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp"
android:layout_marginTop="150dp" android:text="Name" />
<EditText
android:id="@+id/txtName" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10"/>
<TextView
android:id="@+id/secTxt" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Location" android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtLocation" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10" />
<TextView
android:id="@+id/thirdTxt" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Designation" android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtDesignation" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:ems="10" />
<Button
android:id="@+id/btnSave" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:text="Save" />
</LinearLayout>
Now we will create another layout resource file details.xml in \res\layout path to show the details in custom
listviewfrom SQLite Database for that right click on your layout folder Go to New select Layout Resource
File and give name as details.xml.Once we create a new layout resource file details.xml, open it and write the
code like as shown below
details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/user_list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:dividerHeight="1dp" />
<Button
android:id="@+id/btnBack" android:layout_width="wrap_content"android:text="Back"
SEng3035 Page 29
Mobile Programming
android:layout_height="wrap_content" android:layout_gravity="center"android:layout_marginTop="20dp"/>
</LinearLayout>
Create an another layout file (list_row.xml) in /res/layout folder to show the data in listview, for that right click
on layout folder add new Layout resource file Give name as list_row.xml and write the code like as
shown below.
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal" android:padding="5dip" >
<TextView
android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textStyle="bold" android:textSize="17dp" />
<TextView
android:id="@+id/designation" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@id/name"
android:layout_marginTop="7dp" android:textColor="#343434" android:textSize="14dp" />
<TextView
android:id="@+id/location" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignBaseline="@+id/designation"
android:layout_alignBottom="@+id/designation" android:layout_alignParentRight="true"
android:textColor="#343434" android:textSize="14dp" />
</RelativeLayout>
Now open your main activity file MainActivity.java from \java\com.example.sqliteexample path and write
the code like as shown below
MainActivity.java
package com.example.sqliteexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name, loc, desig;
Button saveBtn;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.txtName);
loc = (EditText)findViewById(R.id.txtLocation);
desig = (EditText)findViewById(R.id.txtDesignation);
saveBtn = (Button)findViewById(R.id.btnSave);
SEng3035 Page 30
Mobile Programming
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = name.getText().toString()+"\n";
String location = loc.getText().toString();
String designation = desig.getText().toString();
DbHandler dbHandler = new DbHandler(MainActivity.this);
dbHandler.insertUserDetails(username,location,designation);
intent = new Intent(MainActivity.this,DetailsActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Details Inserted Successfully",Toast.LENGTH_SHORT).show();
}
});
}
}
If you observe above code, we are taking entered user details and inserting into SQLite database and redirecting
the user to another activity.Now we will create another activity file DetailsActivity.java in \java\
com.example.sqliteexample path to show the details from SQLite database for that right click on your
application folder Go to New select Java Class and give name as DetailsActivity.java.Once we create a
new activity file DetailsActivity.java, open it and write the code like as shown below
DetailsActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.*;
import java.util.ArrayList;
import java.util.HashMap;
public class DetailsActivity extends AppCompatActivity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
DbHandler db = new DbHandler(this);
ArrayList<HashMap<String, String>> userList = db.GetUsers();
ListView lv = (ListView) findViewById(R.id.user_list);
ListAdapter adapter = new SimpleAdapter(DetailsActivity.this, userList, R.layout.list_row,new String[]
{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
lv.setAdapter(adapter);
Button back = (Button)findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(DetailsActivity.this,MainActivity.class);
startActivity(intent);
SEng3035 Page 31
Mobile Programming
}
});
}
}
If you observe above code, we are getting the details from SQLite database and binding the details to android
listview. Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sqliteexample">
<application
android:allowBackup="true" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DetailsActivity" android:label="SQLite Example - Details"></activity>
</application>
</manifest>
If you observe above example, we are saving entered details in SQLite database and redirecting the user to
another activity file (DetailsActivity.java) to show the users details and added all the activities
in AndroidManifest.xml file
rates, world news, stock market quotation are examples of applications that can be modeledaround the notion of a
remote data-services provider surrounded bycountless consumers tapping on the server’s resources.
Remote DB hit made simple: DB residing remotely can be hit from inside Android applications
through Web Service calls. Making Web Service call from Android applications allows us to add
functionality outside the scope of a DB like caching data, applying business rules over the data
etc.,
SEng3035 Page 34
Mobile Programming
This model has a simple invocation mode and little overhead. Service calls rely on a URL which may also carry
arguments. Sender & receiver must understand how they pass data items from one another. As an example: Google
Maps API uses the REST model.
Remote Procedure Call (RPC).
Remote services are seen as coherent collections of discoverable functions (or method calls) stored and exposed by
EndPoint providers. Some implementations of this category include: Simple Object Access Protocol (SOAP),
Common Object Request Broker Architecture (CORBA), Microsoft's Distributed Component Object Model
(DCOM) and Sun Microsystems's Java/Remote Method Invocation (RMI).
REST vs. SOAP
Although SOAP and REST technologies accomplish the same final goal, that is request and receive a service, there
are various differences between them.
REST users refer to their remote services through a conventional URL that commonly includes the
location of the (stateless ) server, the service name, the function to be executed and the parameters needed
by the function to operate (if any). Data is transported using HTTP/HTTPS.
SOAP requires some scripting effort to create an XML envelop in which data travels. An additional
overhead on the receiving end is needed to extract data from the XML envelope. SOAP accepts a variety
of transport
mechanisms, among them HTTP, HTTPS, FTP, SMTP, etc. SOAP uses WSDL (Web Service Description
Language) for exposing the format and operation of the services. REST lacks an equivalent exploratory tool.
Example 1:Android User Registration with PHP and MySQL (RESTful Web Service)
1. Create the backend web server. Download xampp or wamp.
SEng3035 Page 35
Mobile Programming
2. Test your server by opening http://localhost and check mysql database server by
opening http://localhost/phpmyadmin
3. Open the mysql database server and create a database called androidtest and table called users.
4. Create a project folder named as test-android under xampp root directory i.e. c:\xampp\htdocs and create
the following php file under your project folder
a. Create database connection using php and save it as db-connect.php
<?php
$host="localhost";
$user="root";
$password='';
$db="androidtest";
$con=mysqli_connect($host,$user,$password,$db);
if(!$con) {
echo '<h1>MySQL Server is not connected</h1>';
}
?>
b. Create a php file that allow you to insert data to users table and name it register.php.
<?php
include("db-connect.php");
if(!$con) {
echo '<h1>MySQL Server is not connected</h1>'.mysqli_connect_error($con);
}else{
$name = $_POST["name"];
$fname = $_POST["fname"];
$email = $_POST["email"];
$password = $_POST["password"];
// Registration
if(!empty($name) && !empty($fname) && !empty($email)&& !empty($password)){
$json_registration=createNewRegisterUser($name,$fname,$email,$password);
echo json_encode($json_registration);
}
}
function createNewRegisterUser($name,$fname,$email,$password){
SEng3035 Page 36
Mobile Programming
include("db-connect.php");
$isExisting=isEmailExist($email);
if($isExisting){
$json['success'] = 0;
$json['message'] = "Error in registering. Probably the username/email already exists";
}else{
$query="insert into users(name,fname,email,password) values ('$name', '$fname',
'$email','$password')";
$inserted = mysqli_query($con, $query);
if($inserted == 1){
$json['success'] = 1;
$json['message'] = "Successfully registered the user";
}else{
$json['success'] = 0;
$json['message'] = "Unable to register the user";
}
mysqli_close($con);
}
return $json;
}
function isEmailExist($email){
include("db-connect.php");
$query="select * from users where email='$email'";
$result=mysqli_query($con, $query);
if(mysqli_num_rows($result) >0){
mysqli_close($con);
return true;
}
return false;
}
?>
5. Open Android Studio and add the following to your app’s build gradle file
android{
…
useLibrary 'org.apache.http.legacy'
}
dependencies{ …
compile "org.apache.httpcomponents:httpcore:4.3.2"
}
6. Allow remote connection permission in AndroidManifest.xml file.
SEng3035 Page 37
Mobile Programming
<manifest ...>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/dbresultmysql"/>
<EditText
android:id="@+id/usernameidmysql"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Name" />
<EditText
android:id="@+id/userfathernameidmysql"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Father Name" />
<EditText
android:id="@+id/useremailidmysql"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textEmailAddress"
android:hint="Email"/>
<EditText
android:id="@+id/userpasswordidmysql"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="PAssword"/>
<Button
android:id="@+id/registeruseridmysql"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register User"
tools:layout_editor_absoluteX="81dp"
tools:layout_editor_absoluteY="73dp" />
<Button
android:id="@+id/viewuseridmysql"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View User Profile"
tools:layout_editor_absoluteX="81dp"
tools:layout_editor_absoluteY="151dp" />
<Button
android:id="@+id/updateuseridmysql"
SEng3035 Page 38
Mobile Programming
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update User Profile"
tools:layout_editor_absoluteX="81dp"
tools:layout_editor_absoluteY="151dp" />
<Button
android:id="@+id/deleteuseridmysql"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete User Profile"
tools:layout_editor_absoluteX="81dp"
tools:layout_editor_absoluteY="151dp" />
</LinearLayout>
JSONREgistration.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsonregistration);
registerbtn = findViewById(R.id.registeruseridmysql);
emailmysql = findViewById(R.id.useremailidmysql);
namemysql = findViewById(R.id.usernameidmysql);
fnamemysql = findViewById(R.id.userfathernameidmysql);
passwordmysql = findViewById(R.id.userpasswordidmysql);
registerbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = namemysql.getText().toString();
fname = fnamemysql.getText().toString();
email = emailmysql.getText().toString();
password = passwordmysql.getText().toString();
AttemptRegistration attemptRegistration= new AttemptRegistration();
attemptRegistration.execute(name,fname,email,password);
});
}
private class AttemptRegistration extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
SEng3035 Page 39
Mobile Programming
}
@Override
protected JSONObject doInBackground(String... args) {
String name = args[0];
String fname=args[1];
String email= args[2];
String password= args[3];
ArrayList params = new ArrayList();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("fname", fname));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null) {
Toast.makeText(getApplicationContext(),result.getString("message"),Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(JSONRegistration.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
public class JSONParser {
// constructor
public JSONParser() {
SEng3035 Page 40
Mobile Programming
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("API123",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/dbresultmysqlnophp"/>
<EditText
android:id="@+id/usernameidmysqlnophp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Name" />
<EditText
android:id="@+id/userfathernameidmysqlnophp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
SEng3035 Page 42
Mobile Programming
android:ems="10"
android:inputType="textPersonName"
android:hint="Father Name" />
<EditText
android:id="@+id/useremailidmysqlnophp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textEmailAddress"
android:hint="Email"/>
<EditText
android:id="@+id/userpasswordidmysqlnophp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="Password"/>
<Button
android:id="@+id/registeruseridmysqlnophp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register User"
tools:layout_editor_absoluteX="81dp"
tools:layout_editor_absoluteY="73dp" />
</LinearLayout>
UserRegistrationWithoutWebService.java
import android.os.AsyncTask;
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.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
@Override
SEng3035 Page 43
Mobile Programming
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "Please wait...",
Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(String... params) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
System.out.println("Database Connected!");
String result = "Database Connection Successful\n";
String sql="insert into users values(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.setString(2,fname);
pstmt.setString(3,email);
pstmt.setString(4,password);
if(pstmt.executeUpdate()>0)
res="User Registered Successfully";
else
res="User not registered!";
} catch (Exception e) {
e.printStackTrace();
res = e.toString();
}
return res;
}
@Override
protected void onPostExecute(String result) {
resulttv.setText(result);
}
}
SEng3035 Page 44