Sie sind auf Seite 1von 97

70

APPENDICES





71

APPENDIX A: AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kk.project"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="16" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.kk.project.Index"
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="com.kk.project.Register"
android:label="@string/title_activity_register" >
</activity>
<activity
android:name="com.kk.project.Login"
android:label="@string/title_activity_login" >
</activity>
<activity
android:name="com.kk.project.CardInfoEntry"
android:label="@string/title_activity_card_info_entry" >
</activity>
<activity
android:name="com.kk.project.CardInfoEntryTwo"
android:label="@string/title_activity_card_info_entry_two" >
</activity>
<activity
android:name="com.kk.project.CardInfoEntryThree"
android:label="@string/title_activity_card_info_entry_three" >
</activity>
72

<activity
android:name="com.kk.project.Dashboard"
android:label="@string/title_activity_dashboard" >
</activity>
<activity
android:name="com.kk.project.RegisterPreview"
android:label="@string/title_activity_register_preview" >
</activity>
<activity
android:name="com.kk.project.parsing"
android:label="@string/title_activity_parsing" >
</activity>
<activity
android:name="com.kk.project.SendCard"
android:label="@string/title_activity_send_card" >
</activity>
<activity
android:name="com.kk.project.ReceivedCards"
android:label="@string/title_activity_received_cards" >
</activity>
<activity
android:name="com.kk.project.SearchResult"
android:label="@string/title_activity_search_result" >
</activity>
<activity
android:name="com.kk.project.Search"
android:label="@string/title_activity_search" >
</activity>
</application>

</manifest>









73

APPENDIX B: Project Code
7.1 FRONT END CODE
The following code was implemented using Android Studio.
i. JAVA CODE

BUILD CONFIG.JAVA

/**
* Automatically generated file. DO NOT MODIFY
*/
package com.kk.project;

public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String PACKAGE_NAME = "com.kk.project";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
}


AFTER REGISTER DIALOG.JAVA

package com.kk.project;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;


public class AfterRegisterDialog extends DialogFragment{

@Override
public Dialog onCreateDialog(Bundle savedInstance) {


AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Registered!")
.setMessage("Would you like to proceed with setting up your Business Card?")
.setPositiveButton("Sure", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
74


//User chose "Continue", proceed to CardInfoEntry
Intent goToCardInfoEntry = new Intent(getActivity(), CardInfoEntry.class);
startActivity(goToCardInfoEntry);

}
})

.setNegativeButton("Later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
Intent goToDashboard = new Intent(getActivity(), Dashboard.class);
startActivity(goToDashboard);
getActivity().finish();

}
});
// Create the AlertDialog object and return it
return builder.create();
}


}


CARD_INFO_XML.JAVA

package com.kk.project;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;



@Root(name="card_info")
public class Card_info_xml {

@Element(name="company")
private String company_name;

@Element(name="designation")
private String company_designation;

@Element(name="department")
private String company_department;

@Element(name="address")
private String company_address;
75


@Element(name="tel_no")
private String company_telephone_no;

@Element(name="fax")
private String fax_no;

@Element(name="website")
private String company_website;

@Element(name="linkedin")
private String linkedin_link;

@Element(name="facebook")
private String facebook_link;

@Element(name="googleplus")
private String googleplus_link;

@Element(name="resume")
private String resume_link;

@Element(name="portfolio")
private String portfolio_link;

@Element(name="other")
private String other_link;

@Element(name="mobile")
private String mobile;

@Attribute(name="xml_id")
private int xml_id;

public Card_info_xml() {
super();
}

public Card_info_xml(String company, String designation,
String department, String address, String tel_no, String fax_no,
String website, String linkedin, String facebook, String googleplus,
String resume, String portfolio, String other, String mobile, int id) {

this.company_name = company;
this.company_designation = designation;
this.company_department = department;
this.company_address = address;
this.company_telephone_no = tel_no;
this.fax_no = fax_no;
this.company_website = website;
76

this.linkedin_link = linkedin;
this.facebook_link = facebook;
this.googleplus_link = googleplus;
this.resume_link = resume;
this.portfolio_link = portfolio;
this.other_link = other;
this.mobile = mobile;
this.xml_id = id;

}

public String getCompany_name(){
return company_name;
}

public String getDesignation(){
return company_designation;
}

public String getDepartment(){
return company_department;
}

public String getAddress(){
return company_address;
}

public String getTelphone_no(){
return company_telephone_no;
}

public String getFax_no(){
return fax_no;
}

public String getWebsite(){
return company_website;
}

public String getLinkedin(){
return linkedin_link;
}

public String getFacebook(){
return facebook_link;
}

public String getGoogleplus(){
return googleplus_link;
}
77


public String getResume(){
return resume_link;
}

public String getPortfolio(){
return portfolio_link;
}

public String getOther(){
return other_link;
}

public String getMobile(){
return mobile;
}

public int getXml_id() {
return xml_id;
}

}


CARDINFOENTRY.JAVA

package com.kk.project;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.File;

public class CardInfoEntry extends Activity {

public int xml_id = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
78

setContentView(R.layout.activity_cardinfoentry);

//Get name, email and phone number from the database; these detailed were stored
during registration
MainDataBase getRegInfo = new MainDataBase(this);
getRegInfo.open();
String[] regInfo = getRegInfo.getAllRegInfo();
getRegInfo.close();

String name = regInfo[0];
String email = regInfo[1];
String mobile = regInfo[2];

//Display the retrieved data in the EditText field by default
EditText username = (EditText) findViewById(R.id.name);
username.setText(name);

EditText useremail = (EditText) findViewById(R.id.email);
useremail.setText(email);

TextView userphone = (TextView) findViewById(R.id.phone_number);
userphone.setText(mobile);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.card_info_entry, menu);
return true;
}

public void next(View view) {

//Get the name and email id from the EditText fields
EditText cinName = (EditText)findViewById(R.id.name);
String username = cinName.getText().toString();

EditText cinEmail = (EditText)findViewById(R.id.email);
String useremail = cinEmail.getText().toString();

//Open database and replace values old values with the new values, even if the values
are unchanged.
//Mobile number is extracted too, so as to uniquely identify (mobile number is the
primary key) the row.
MainDataBase CardInfoEntry = new MainDataBase(CardInfoEntry.this);
CardInfoEntry.open();
String CardInfo[] = CardInfoEntry.getAllRegInfo();

String mobile = CardInfo[2];
String password = CardInfo[3];
79


CardInfoEntry.updateforCardInfoEntry(username, useremail, mobile);
CardInfoEntry.close();

//Take the user to the 2nd part of the info entry process i.e. the next activity
Intent goNextRegisterPage = new Intent(this, CardInfoEntryTwo.class);
startActivity(goNextRegisterPage);

}

}


CARDINFOENTRYTWO.JAVA

package com.kk.project;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.File;

public class CardInfoEntryTwo extends Activity {

public int xml_id = 1001;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.card_info_entry_two, menu);
return true;
}

public void next (View view) {

80

//Get all the info from the EditText fields
EditText cinCompanyName = (EditText)findViewById(R.id.company_name);
String companyname = cinCompanyName.getText().toString();

EditText cinDesignation = (EditText)findViewById(R.id.designation);
String designation = cinDesignation.getText().toString();

EditText cinDepartment = (EditText)findViewById(R.id.department);
String department = cinDepartment.getText().toString();

EditText cinAddress = (EditText)findViewById(R.id.address);
String address = cinAddress.getText().toString();

EditText cinTelephoneNumber = (EditText)findViewById(R.id.tel_number);
String Telephone = cinTelephoneNumber.getText().toString();

EditText cinFax = (EditText)findViewById(R.id.fax);
String fax = cinFax.getText().toString();

EditText cinWebsite = (EditText)findViewById(R.id.website);
String website = cinWebsite.getText().toString();

//Open database and enter info into it from the EditText fields
MainDataBase CardInfoEntry = new MainDataBase(CardInfoEntryTwo.this);
CardInfoEntry.open();
String[] regInfo = CardInfoEntry.getAllRegInfo();

String mobile = regInfo[2];

CardInfoEntry.updateforCardInfoEntryTwo(companyname, designation, department,
address,
Telephone, fax, website, mobile);
CardInfoEntry.close();

//Take the user to the final part of the info entry process
Intent goFinalRegisterPage = new Intent(this, CardInfoEntryThree.class);
startActivity(goFinalRegisterPage);

}

public void previous (View view) {

/*Go back to the previous page and display all the info as entered by the user.
In this case the current activity will not save the EditText data; saving will only happens
when the next button is clicked*/
finish();

}

}
81

CARDINFOENTRYTHREE.JAVA

package com.kk.project;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.File;

public class CardInfoEntryThree extends Activity {

public int xml_id = 1002;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.card_info_entry_three, menu);
return true;
}

public void next(View view) {

//Get all the info from the EdiText field
EditText cinlinkedin = (EditText)findViewById(R.id.linkedin);
String linkedin = cinlinkedin.getText().toString();

EditText cinfacebook = (EditText)findViewById(R.id.facebook);
String facebook = cinfacebook.getText().toString();

EditText cingoogleplus = (EditText)findViewById(R.id.googleplus);
String googleplus = cingoogleplus.getText().toString();

EditText cinresume = (EditText)findViewById(R.id.resume);
String resume = cinresume.getText().toString();

82

EditText cinportfolio = (EditText)findViewById(R.id.portfolio);
String portfolio = cinportfolio.getText().toString();

EditText cinotherlink = (EditText)findViewById(R.id.other);
String otherlink = cinotherlink.getText().toString();

//Open database and enter info into it from the EditText fields
MainDataBase CardInfoEntry = new MainDataBase(CardInfoEntryThree.this);
CardInfoEntry.open();
String[] regInfo = CardInfoEntry.getAllRegInfo();

String mobile = regInfo[2];

CardInfoEntry.updateforCardInfoEntryThree(linkedin, facebook, googleplus, resume,
portfolio,
otherlink, mobile);
CardInfoEntry.close();

//Generate card_info_three_xml.xml serialized file for above data

//Go to the preview page
Intent goRegisterPreviewPage = new Intent(this, RegisterPreview.class);
startActivity(goRegisterPreviewPage);

}

public void previous(View view) {

/*Go back to the previous page and display all the info as entered by the user.
In this case the current activity will not save the EditText data; this only happens when
next is clicked*/
finish();

}

}


DASHBOARD.JAVA

package com.kk.project;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

83

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.BufferedInputStream;
import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;


public class Dashboard extends Activity {

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

MainDataBase getUserInfo = new MainDataBase(this);
getUserInfo.open();
String[] regInfo = getUserInfo.getAllRegInfo();
getUserInfo.close();

TextView coutName = (TextView)findViewById(R.id.user_name);
coutName.setText(String.valueOf(regInfo[0]));

try {
getReceivedCards();
} catch(Exception e) {
e.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard, menu);
return true;
}

//Go to activity which enables profile edit
public void editprofile(View view) {

Intent goToEdit = new Intent(this, CardInfoEntry.class);
startActivity(goToEdit);
}

//Go to activity which enables card preview
84

public void viewmycard(View view) {

Intent goToMyBusinessCard = new Intent(this, RegisterPreview.class);
startActivity(goToMyBusinessCard);
}

//Go to activity which enables user to see all the received cards
public void viewreceivedcards(View view) {

Intent goToReceivedCards = new Intent(this, ReceivedCards.class);
startActivity(goToReceivedCards);
}

public void sendbussinesscard(View view) {

Intent goToSendCard = new Intent(this, SendCard.class);
startActivity(goToSendCard);
}

//Search according to company
public void search(View view) {

Intent goToSearch = new Intent(this, Search.class);
startActivity(goToSearch);

}

//Logout the current user
public void logout(View view) {

MainDataBase deleteTables = new MainDataBase(this);

deleteTables.open();
deleteTables.deleteRegInfoTable();
deleteTables.deleteUserCardInfoTable();
deleteTables.deleteReceivedCardInfoTable();
deleteTables.close();

//Recreate the last class.
Intent recreateclass =
getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getP
ackageName());
recreateclass.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(recreateclass);

finish();
}

//Method which connects with the "GetCard" servlet and retrieves the Received Cards
//This method is executed every time the activity starts.
85

public void getReceivedCards() throws Exception {

//Get current user mobile number from the user
MainDataBase getUserInfo = new MainDataBase(Dashboard.this);
getUserInfo.open();
String[] regInfo = getUserInfo.getAllRegInfo();
getUserInfo.close();

final String mobile = regInfo[2];

new Thread(new Runnable() {
@Override
public void run() {

try {

//Send user mobile number to the server.
URL mobileurl = new URL("http://10.0.2.2:8080/project_server/GetCard");
URLConnection connection = mobileurl.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new
OutputStreamWriter(connection.getOutputStream());
out.write(mobile);
out.close();

BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
in.close();

//Code to fetch GetCard XML, serialize it and save it to the local database.
URL GetCardXmlUrl = new
URL("http://10.0.2.2:8080/getcardxml/GetCard_xml_output_"+ mobile +".xml");
URLConnection GetCardXmlConnection = GetCardXmlUrl.openConnection();
InputStream PhonebookInstream = new
BufferedInputStream(GetCardXmlConnection.getInputStream());
Serializer PhoneBookSerializer = new Persister();

GetCard_info_xml parse_phonebook_xml =
PhoneBookSerializer.read(GetCard_info_xml.class, PhonebookInstream);
String[] mobile_nos = parse_phonebook_xml.getPhones();

MainDataBase addReceivedCard = new MainDataBase(Dashboard.this);
addReceivedCard.open();

for(int i=0; i<mobile_nos.length; i++) {

addReceivedCard.CreateEnteryReceivedCardInfo(mobile_nos[i]);
Log.d("value: ", mobile_nos[i]);
}
86


addReceivedCard.close();

} catch (Exception e) {
e.printStackTrace();
}

}
}).start();
}
}


GETCARD_INFO_XML.JAVA

package com.kk.project;

import android.util.Log;

import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;

/**
* Created by kartikey on 15/2/14.
*/
@Root(name="received_card_info")
public class GetCard_info_xml {

@ElementArray(name="phoneBook", entry="mobile_number")
private String[] phones;

public GetCard_info_xml() {
super();
}

public GetCard_info_xml(String[] phones) {
this.phones = phones;
}

public String[] getPhones() {
return phones;
}

}


INDEX.JAVA

package com.kk.project;

87

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class Index extends Activity {

//This activity is the first activity that is executed; does not have any layout.

/* Method which checks whether a user is logged in or not by checking the
database for the existence of a username.
If username is not blank, it implies that a user is logged in. Otherwise, user is not logged
in.
*/
private boolean getUserName() {

MainDataBase getName = new MainDataBase(this);
getName.open();
String[] regInfo = getName.getAllRegInfo();
getName.close();

String UserName = regInfo[0];

if(UserName.equals(""))
return false;
else
return true;

}

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

if(!getUserName())
{
Intent openLogin = new Intent(this, Login.class); //User is not logged in.
Hence, he/she is directed to the login page
startActivity(openLogin);
finish(); //finish() will destroy the current activity.
This will prevent the activity to open up again upon pressing back button
}
else
{
Intent openDashboard = new Intent(this, Dashboard.class); //User is logged in and
is directed to the dashboard.
startActivity(openDashboard);
finish();
}
88

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.index, menu);
return true;
}

}


LOGIN.JAVA

package com.kk.project;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

public class Login extends Activity {

public int id = 3000;

89

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}

public void login (View view) throws Exception { //Button click to direct the user to
the dashboard.

EditText cinMobile = (EditText)findViewById(R.id.mobile_no);
final String mobile = cinMobile.getText().toString();

EditText cinPassword = (EditText)findViewById(R.id.password);
final String password = cinPassword.getText().toString();

//Generate login_info_xml.xml serialized file for the above data.
Serializer serializer = new Persister();
Login_info_xml login_info_xml_object = new Login_info_xml(mobile, password, id);

File result = new File(Environment.getExternalStorageDirectory(), "login_info.xml");

try{
Log.d("Start","Serializing");
serializer.write(login_info_xml_object, result);
}catch (Exception e){
Log.d("Self", "Error");
e.printStackTrace();
}

/*--The connection to the server is established in another (not main) thread.
This prevents the app to stop responding if the connection to the server is not established
or it takes time to establish the connection--*/

new Thread(new Runnable() {
@Override
public void run() {

String url = "http://10.0.2.2:8080/project_server/Login";
File file = new File(Environment.getExternalStorageDirectory(), "login_info.xml");

try {

//Send user mobile number to the server.
90

URL mobileurl = new URL("http://10.0.2.2:8080/project_server/Login");
URLConnection connection = mobileurl.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new
OutputStreamWriter(connection.getOutputStream());
out.write(mobile);
out.close();

BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
in.readLine();
in.close();

//Send XML file over to the server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file),
-1);
reqEntity.setContentType("text/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

//Check the response only after verifying that the request has actually been
completed (status code should be = 200)
if(response.getStatusLine().getStatusCode() == 200) {

String StringToCheckResponse = EntityUtils.toString(response.getEntity());
if(StringToCheckResponse.equals("Login Verified")) {

//Code to fetch reg_info XML data and save it on the local database
URL RegXmlUrl = new
URL("http://10.0.2.2:8080/regxml/reg_info_xml_output_"+ mobile +".xml");
URLConnection RegXmlUrlConnection = RegXmlUrl.openConnection();
InputStream Reg_Instream = new
BufferedInputStream(RegXmlUrlConnection.getInputStream());
Serializer RegXmlSerializer = new Persister();

Reg_info_xml parse_reg_xml = RegXmlSerializer.read(Reg_info_xml.class,
Reg_Instream);

String name = parse_reg_xml.getName();
String email = parse_reg_xml.getEmail();

MainDataBase InputRegInfo = new MainDataBase(Login.this);
InputRegInfo.open();
InputRegInfo.CreateEntryInfoTable(name, email, password, mobile);
InputRegInfo.close();

Log.d("Received name:", name);
91

Log.d("Received email:", email);

//Code to fetch card_info XML data and save it on the local database
try {

URL cardxmlurl = new
URL("http://10.0.2.2:8080/cardxml/card_xml_output_"+ mobile +".xml");
URLConnection CardXmlUrlConnection =
cardxmlurl.openConnection();
InputStream Card_Instream = new
BufferedInputStream(CardXmlUrlConnection.getInputStream());
Serializer CardXmlSerializer = new Persister();

Card_info_xml parse_card_xml =
CardXmlSerializer.read(Card_info_xml.class, Card_Instream);

String company = parse_card_xml.getCompany_name();
String designation = parse_card_xml.getDesignation();
String department = parse_card_xml.getDepartment();
String address = parse_card_xml.getAddress();
String tel_no = parse_card_xml.getTelphone_no();
String fax_no = parse_card_xml.getFax_no();
String website = parse_card_xml.getWebsite();
String linkedin = parse_card_xml.getLinkedin();
String facebook = parse_card_xml.getFacebook();
String googleplus = parse_card_xml.getGoogleplus();
String resume = parse_card_xml.getResume();
String portfolio = parse_card_xml.getPortfolio();
String other = parse_card_xml.getOther();

MainDataBase InputCardInfo = new MainDataBase(Login.this);
InputCardInfo.open();
InputCardInfo.CreateEntryUserCardInfo(company, designation, address,
department,
tel_no, fax_no, website, linkedin,
facebook, googleplus, resume, portfolio,
other, mobile);
InputCardInfo.close();

InputCardInfo.open();
String[] name_val = InputCardInfo.getAllRegInfo();
InputCardInfo.close();

String user_name = name_val[0];

Log.d("user name:", user_name);

} catch (Exception e) {

Log.d("Partly Failed:","card info not found");
92

e.printStackTrace();

}

//Recreate the last class (Activity).
Intent recreateclass =
getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getP
ackageName());
recreateclass.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(recreateclass);

}

}

} catch(Exception e) {
Log.d("Not Sent", "fail");
e.printStackTrace();
}

}
}).start();

finish();

}

public void register (View view) { //Button click to direct the user to the register page

Intent openRegister = new Intent(this, Register.class);
startActivity(openRegister);

finish();

}

}

LOGIN_INFO_XML.JAVA

package com.kk.project;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
* Created by kartikey on 16/1/14.
*/

93

@Root(name="login_info")
public class Login_info_xml {

@Element(name="mobile")
private String mobile;

@Element(name="password")
private String password;

@Attribute(name="xml_id")
private int xml_id;

public Login_info_xml() {
super();
}

public Login_info_xml(String input_mobile, String input_password, int id) {

this.mobile = input_mobile;
this.password = input_password;
this.xml_id = id;

}

public String getMobile() {
return mobile;
}

public String getPassword() {
return password;
}

public int getXml_id() {
return xml_id;
}
}


MAINDATABASE.JAVA

package com.kk.project;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.Calendar;
94

public class MainDataBase {

//Columns for reg_info
public static final String USER_NAME = "name";
public static final String USER_EMAIL = "email";
public static final String USER_MOBILE_NUMBER = "mobile"; //Primary key and
foreign key
public static final String USER_PASSWORD = "password";

//Columns for user_card_info
public static final String COMPANY_NAME = "company";
public static final String DESIGNATION = "designation";
public static final String COMPANY_DEPARTMENT = "department";
public static final String COMPANY_ADDRESS = "company_address";
public static final String TELEPHONE_NUMBER = "company_telephone_number";
public static final String FAX = "fax";
public static final String WEBSITE = "company_website_link";
public static final String LINKEDIN = "linkedin_link";
public static final String FACEBOOK = "facebook_link";
public static final String GOOGLEPLUS = "googleplus_link";
public static final String RESUME = "resume_link";
public static final String PORTFOLIO = "portfolio_link";
public static final String OTHER = "other_link";

//Columns for received_card_info
public static final String RECEIVED_CARD_MOBILE_NO = "received_mobile_no";
public static final String RECEIVED_DATE = "card_received_date";

//Columns for search_result
public static final String MOBILE_NO = "mobile_no";

//Database name
private static final String DATABASE_NAME = "local_db";

//Tables in the database
public static final String REG_INFO_TABLE = "reg_info";
public static final String USER_CARD_INFO_TABLE = "user_card_info";
public static final String RECEIVED_CARD_INFO_TABLE ="received_card_info";
public static final String SEARCH_RESULT = "search_result";

private static final int DATABASE_VERSION = 1;

private DbHelper ourHelper;
private final Context dbContext;
private SQLiteDatabase MainDataBase;

private static class DbHelper extends SQLiteOpenHelper {

public DbHelper(Context context) {

95

super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {

//Creation of the table "info_table"
db.execSQL("CREATE TABLE "+ REG_INFO_TABLE + " (" +
USER_NAME + " TEXT NOT NULL, " +
USER_EMAIL + " TEXT NOT NULL, " +
USER_MOBILE_NUMBER + " TEXT NOT NULL PRIMARY KEY, " +
USER_PASSWORD + " TEXT NOT NULL);"
);

//creation of the table "user_card_info"
db.execSQL("CREATE TABLE "+ USER_CARD_INFO_TABLE +" (" +
DESIGNATION + " TEXT, " +
COMPANY_DEPARTMENT + " TEXT, " +
COMPANY_NAME + " TEXT, " +
COMPANY_ADDRESS + " TEXT, " +
TELEPHONE_NUMBER + " TEXT, " +
FAX + " TEXT, " +
WEBSITE + " TEXT, " +
LINKEDIN + " TEXT, " +
GOOGLEPLUS + " TEXT, " +
FACEBOOK + " TEXT, " +
RESUME + " TEXT, " +
PORTFOLIO + " TEXT, " +
USER_MOBILE_NUMBER + " TEXT NOT NULL PRIMARY KEY, " +
OTHER + " TEXT);"
);

//Creation of the table received_card_info
db.execSQL("CREATE TABLE "+ RECEIVED_CARD_INFO_TABLE +" (" +
RECEIVED_CARD_MOBILE_NO + " TEXT NOT NULL PRIMARY KEY, " +
RECEIVED_DATE + " INTEGER);"
);

//Creation of table search_result
db.execSQL("CREATE TABLE "+ SEARCH_RESULT +" (" +
MOBILE_NO + " TEXT);"
);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXIST " + DATABASE_NAME);
96

onCreate(db);

}

}

public MainDataBase (Context c) {
dbContext = c;
}

//Method to open a database for R/W
public MainDataBase open() {

ourHelper = new DbHelper(dbContext);
MainDataBase = ourHelper.getWritableDatabase();
return this;

}

//Method to close an open database
public void close() {

MainDataBase.close();

}

//Method to insert data into "reg_info"
public long CreateEntryInfoTable (String name, String email, String password, String
mobile_number) {

ContentValues cv = new ContentValues();
cv.put(USER_NAME, name);
cv.put(USER_EMAIL, email);
cv.put(USER_PASSWORD, password);
cv.put(USER_MOBILE_NUMBER, mobile_number);

return MainDataBase.insert(REG_INFO_TABLE, null, cv);

}

//Method to insert data into "user_card_info"
public long CreateEntryUserCardInfo (String company, String designation, String
company_address,
String department ,String telephone, String fax,
String website, String linkedin, String facebook,
String googleplus, String resume,
String portfolio, String other, String mobile) {

ContentValues cv = new ContentValues();
cv.put(COMPANY_NAME, company);
97

cv.put(DESIGNATION, designation);
cv.put(COMPANY_DEPARTMENT, department);
cv.put(COMPANY_ADDRESS, company_address);
cv.put(TELEPHONE_NUMBER, telephone);
cv.put(FAX, fax);
cv.put(WEBSITE, website);
cv.put(LINKEDIN, linkedin);
cv.put(FACEBOOK, facebook);
cv.put(GOOGLEPLUS, googleplus);
cv.put(RESUME, resume);
cv.put(PORTFOLIO, portfolio);
cv.put(OTHER, other);
cv.put(USER_MOBILE_NUMBER, mobile);

return MainDataBase.insert(USER_CARD_INFO_TABLE, null, cv);

}

//Method to insert data into "received_card_info"
public long CreateEnteryReceivedCardInfo (String received_card_mobile_no) {

ContentValues cv = new ContentValues();
cv.put(RECEIVED_CARD_MOBILE_NO, received_card_mobile_no);
cv.put(RECEIVED_DATE, Calendar.getInstance().getTimeInMillis()); //The date will
automatically pulled from the system when the function is called

return MainDataBase.insert(RECEIVED_CARD_INFO_TABLE, null, cv);

}

//Method to insert data into "search_result"
public long CreateEntrySearchResult (String mobile_no) {

ContentValues cv = new ContentValues();
cv.put(MOBILE_NO, mobile_no);

return MainDataBase.insert(SEARCH_RESULT, null, cv);

}

//Method to get all column values from "reg_info"
public String[] getAllRegInfo() {

String[] columns = new String[] {USER_NAME, USER_EMAIL,
USER_MOBILE_NUMBER, USER_PASSWORD};
Cursor c = MainDataBase.query(REG_INFO_TABLE, columns, null, null, null, null,
null);

String[] result = new String[4];

98

for(int j=0; j<4; ++j) {
result[j] = "";
}

int[] column = new int[4];

column[0] = c.getColumnIndex(USER_NAME);
column[1] = c.getColumnIndex(USER_EMAIL);
column[2] = c.getColumnIndex(USER_MOBILE_NUMBER);
column[3] = c.getColumnIndex(USER_PASSWORD);

while(c.moveToNext()) {

for(int i = 0; i<4; ++i) {
result[i] = c.getString(column[i]);
}

}

return result;
}

//Method to get all column values from "user_card_info"
public String[] getUserCardInfo() {

String[] columns = new String[] {COMPANY_NAME, DESIGNATION,
COMPANY_DEPARTMENT,
COMPANY_ADDRESS, TELEPHONE_NUMBER, FAX, WEBSITE,
LINKEDIN, FACEBOOK, GOOGLEPLUS, PORTFOLIO,
RESUME, OTHER};
Cursor c = MainDataBase.query(USER_CARD_INFO_TABLE, columns, null, null,
null, null, null);

String[] result = new String[13];

for(int j=0; j<13; ++j) {
result[j] = "";
}

int[] column = new int[13];

column[0] = c.getColumnIndex(COMPANY_NAME);
column[1] = c.getColumnIndex(DESIGNATION);
column[2] = c.getColumnIndex(COMPANY_DEPARTMENT);
column[3] = c.getColumnIndex(COMPANY_ADDRESS);
column[4] = c.getColumnIndex(TELEPHONE_NUMBER);
column[5] = c.getColumnIndex(FAX);
column[6] = c.getColumnIndex(WEBSITE);
column[7] = c.getColumnIndex(LINKEDIN);
column[8] = c.getColumnIndex(FACEBOOK);
99

column[9] = c.getColumnIndex(GOOGLEPLUS);
column[10] = c.getColumnIndex(PORTFOLIO);
column[11] = c.getColumnIndex(RESUME);
column[12] = c.getColumnIndex(OTHER);

while(c.moveToNext()) {

for(int i=0; i<13; ++i) {
result[i] = c.getString(column[i]);
}
}

return result;

}

//Method to get all column values from "received_card_info"
public String[] getRecievedCardInfo() {

String[] columns = new String[] {RECEIVED_CARD_MOBILE_NO};
Cursor c = MainDataBase.query(RECEIVED_CARD_INFO_TABLE, columns, null,
null, null, null, null);

long numRows = DatabaseUtils.queryNumEntries(MainDataBase,
RECEIVED_CARD_INFO_TABLE); //Rows count
int rowCount = (int) numRows; //long is type-casted to
int.

String[] result = new String[rowCount];

int Mobile_number = c.getColumnIndex(RECEIVED_CARD_MOBILE_NO);

int i=0;
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

result[i] = c.getString(Mobile_number);
++i;

}

return result;
}

//Method to values from search_result
public String[] getSearchResult() {

String[] columns = new String[] {MOBILE_NO};
Cursor c = MainDataBase.query(SEARCH_RESULT, columns, null, null, null, null,
null);

100

long numRows = DatabaseUtils.queryNumEntries(MainDataBase, SEARCH_RESULT);
int rowCount = (int) numRows;

String[] result = new String[rowCount];

int Mobile_number = c.getColumnIndex(MOBILE_NO);

int i=0;
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

result[i] = c.getString(Mobile_number);
++i;

}

return result;

}

//Method to update name and email (primarily for CardInfoEntry)
public void updateforCardInfoEntry(String name, String email, String mobile) {

ContentValues cvUpdate = new ContentValues();
cvUpdate.put(USER_NAME, name);
cvUpdate.put(USER_EMAIL, email);

MainDataBase.update(REG_INFO_TABLE, cvUpdate, USER_MOBILE_NUMBER +
"=" + mobile, null);

}

//Method to update Card Info (CardInfoEntryTwo)
public void updateforCardInfoEntryTwo(String company, String designation, String
department,
String address, String telephone, String fax,
String website, String mobile) {

ContentValues cvUpdate = new ContentValues();
cvUpdate.put(COMPANY_NAME, company);
cvUpdate.put(DESIGNATION, designation);
cvUpdate.put(COMPANY_DEPARTMENT, department);
cvUpdate.put(COMPANY_ADDRESS, address);
cvUpdate.put(TELEPHONE_NUMBER, telephone);
cvUpdate.put(FAX, fax);
cvUpdate.put(WEBSITE, website);

MainDataBase.update(USER_CARD_INFO_TABLE, cvUpdate,
USER_MOBILE_NUMBER + "=" + mobile, null);

}
101


//Method to update Card Info (CardInfoEntryThree)
public void updateforCardInfoEntryThree(String linkedin, String facebook, String
googleplus,
String resume, String portfolio, String other, String mobile) {

ContentValues cvUpdate = new ContentValues();
cvUpdate.put(LINKEDIN, linkedin);
cvUpdate.put(FACEBOOK, facebook);
cvUpdate.put(GOOGLEPLUS, googleplus);
cvUpdate.put(RESUME, resume);
cvUpdate.put(PORTFOLIO, portfolio);
cvUpdate.put(OTHER, other);

MainDataBase.update(USER_CARD_INFO_TABLE, cvUpdate,
USER_MOBILE_NUMBER + "=" + mobile, null);

}

//Method to clear reg_info table
public void deleteRegInfoTable() {

SQLiteDatabase db = ourHelper.getWritableDatabase();
db.delete(REG_INFO_TABLE, null, null);

}

//Method to clear user_card_info table
public void deleteUserCardInfoTable() {

SQLiteDatabase db = ourHelper.getWritableDatabase();
db.delete(USER_CARD_INFO_TABLE, null, null);

}

//Method to clear received_card_info table
public void deleteReceivedCardInfoTable() {

SQLiteDatabase db = ourHelper.getWritableDatabase();
db.delete(RECEIVED_CARD_INFO_TABLE, null, null);

}

//Method to delete search_result table
public void deleteSearchResult() {

SQLiteDatabase db = ourHelper.getWritableDatabase();
db.delete(SEARCH_RESULT, null, null);

}
102

}













RECEIVEDCARDS.JAVA

package com.kk.project;

import android.app.Fragment;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ReceivedCards extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

MainDataBase getReceivedMobileNos = new MainDataBase(this);
getReceivedMobileNos.open();
String[] Mobile_no = getReceivedMobileNos.getRecievedCardInfo();
getReceivedMobileNos.close();

try {

setListAdapter(new ArrayAdapter<String>(this, R.layout.phonebook_listview,
Mobile_no));
Log.d("Phone", Mobile_no[0]);

103

} catch(Exception e) {

e.printStackTrace();

}

ListView listView = getListView();
listView.setTextFilterEnabled(true);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the mobile number
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.received_cards, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
104

Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.phonebook_listview, container, false);
return rootView;
}
}

}






REG_INFO_XML.JAVA

package com.kk.project;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;



@Root(name="reg_info")
public class Reg_info_xml {

@Element(name="name")
private String user_name;

@Element(name="email")
private String mail_id;

@Element(name="mobile")
private String mobile_no;

@Element(name="pass")
private String passphrase;

@Attribute(name="xml_id")
private int xml_id;

public Reg_info_xml() {
super();
}

public Reg_info_xml(String name, String email, String mobile, String password, int id) {

this.user_name = name;
this.mail_id = email;
this.mobile_no = mobile;
105

this.passphrase = password;
this.xml_id = id;

}

public String getName() {
return user_name;
}

public String getEmail() {
return mail_id;
}

public String getMobile() {
return mobile_no;
}

public int getXml_id() {
return xml_id;
}
}


REGISTER.JAVA

package com.kk.project;

import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
106

import java.net.URLConnection;

public class Register extends Activity {

public int xml_id = 1000;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, menu);
return true;
}

public void register (View view) throws Exception { //button click to store
registration info in the database table "reg_info"
//and send data over to the server.
EditText cinName = (EditText)findViewById(R.id.user_name);
String userName = cinName.getText().toString();

EditText cinMobileNumber = (EditText)findViewById(R.id.mobile_number);
String mobileNumber = cinMobileNumber.getText().toString();

EditText cinEmailId = (EditText)findViewById(R.id.email);
String emailId = cinEmailId.getText().toString();

EditText cinPassword = (EditText)findViewById(R.id.password);
String password = cinPassword.getText().toString();

//Generate reg_info_xml.xml serialized file for above data
Serializer serializer = new Persister();
Reg_info_xml reg_info_xml_object = new Reg_info_xml(userName, emailId,
mobileNumber,
password, xml_id);
File result = new File(Environment.getExternalStorageDirectory(), "reg_info.xml");

try {
Log.d("Start", "Serializing");
serializer.write(reg_info_xml_object, result);
} catch (Exception e) {
Log.d("Self", "Error");
e.printStackTrace();
}

//Code to initialize database with registration values
107

MainDataBase inputRegInfo = new MainDataBase(Register.this);
inputRegInfo.open();
inputRegInfo.CreateEntryInfoTable(userName, emailId, password, mobileNumber);
inputRegInfo.close();

//Create the USER_CARD_INFO_TABLE (initialised with null values) when the user
clicks on this button
MainDataBase inputCardInfo = new MainDataBase(this);
inputCardInfo.open();
String[] regInfo = inputCardInfo.getAllRegInfo();

final String mobile = regInfo[2];

inputCardInfo.CreateEntryUserCardInfo(null, null, null, null, null, null, null,
null, null, null, null, null, null, mobile);
inputCardInfo.close();

//Send the data over to the server. Data is retrieved by parsing the xml file created
above.

/*--The connection to the server is established in another (not main) thread.
This prevents the app to stop responding if the connection to the server is not established
or if it takes time to establish the connection--*/

new Thread(new Runnable() {
@Override
public void run() {

String url = "http://10.0.2.2:8080/project_server/Register";
File file = new File(Environment.getExternalStorageDirectory(), "reg_info.xml");

try {


//Send user mobile number to the server.
URL mobileurl = new URL("http://10.0.2.2:8080/project_server/Register");
URLConnection connection = mobileurl.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new
OutputStreamWriter(connection.getOutputStream());
out.write(mobile);
out.close();

BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
in.readLine();
in.close();

//Send XML file to the server
108

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file),
-1);
reqEntity.setContentType("text/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("done", response.toString());

} catch(Exception e) {
Log.d("Not Sent", "failed");
e.printStackTrace();
}

}
}).start();

//Show dialogue box
AfterRegisterDialog df = new AfterRegisterDialog();
df.show(getFragmentManager(), "ContinueOrNot");

}

}


REGISTERPREVIEW.JAVA

package com.kk.project;

import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
109

import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class RegisterPreview extends Activity {

public String name;
public String designation;
public String department;
public String company;
public String address;
public String tel_no;
public String mobile;
public String email;
public String website;

public String fax_no;
public String linkedin;
public String facebook;
public String googleplus;
public String resume;
public String portfolio;
public String other;

int id = 2000;

//Method to retrieve all info from "reg_info" and "user_card_info, and display it"

private void getandsetAllInfo() {

MainDataBase getInfo = new MainDataBase(this);
getInfo.open();
String[] UserInfo = getInfo.getAllRegInfo();
String[] CardInfo = getInfo.getUserCardInfo();
getInfo.close();

TextView coutName = (TextView)findViewById(R.id.name);
coutName.setText(String.valueOf(UserInfo[0])); //Set name
name = UserInfo[0];

TextView coutDesignation = (TextView)findViewById(R.id.designation);
coutDesignation.setText(String.valueOf(CardInfo[1])); //Set designation
designation = CardInfo[1];

TextView coutDepartment = (TextView)findViewById(R.id.department);
coutDepartment.setText(String.valueOf(CardInfo[2])); //Set department
department = CardInfo[2];

TextView coutCompany = (TextView)findViewById(R.id.company);
coutCompany.setText(String.valueOf(CardInfo[0])); //Set Company
110

company = CardInfo[0];

TextView coutAddress = (TextView)findViewById(R.id.address);
coutAddress.setText(String.valueOf(CardInfo[3])); //Set Company Address
address = CardInfo[3];

TextView coutTelephone = (TextView)findViewById(R.id.telephone);
coutTelephone.setText(String.valueOf(CardInfo[4])); //Set Telephone
Number
tel_no = CardInfo[4];

TextView coutMobile = (TextView)findViewById(R.id.mobile);
coutMobile.setText(String.valueOf(UserInfo[2])); //Set Mobile Number
mobile = UserInfo[2];

TextView coutEmail = (TextView)findViewById(R.id.email);
coutEmail.setText(String.valueOf(UserInfo[1])); //Set Email Id
email = UserInfo[1];

TextView coutWebsite = (TextView)findViewById(R.id.website);
coutWebsite.setText(String.valueOf(CardInfo[6])); //Set Website
website = CardInfo[6];

fax_no = CardInfo[5]; //Get fax number
linkedin = CardInfo[7]; //Get linkedin link
facebook = CardInfo[8]; //Get facebook link
googleplus = CardInfo[9]; //Get googleplus link
resume = CardInfo[11]; //Get resume link
portfolio = CardInfo[10]; //Get portfolio link
other = CardInfo[12]; //Get other link

}

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

getandsetAllInfo(); //Call the method which will set values in all the TextViews

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present..
getMenuInflater().inflate(R.menu.register_preview, menu);
return true;
}

public void send_to_server(View view) throws Exception {
111


//Generate card_info.xml
Serializer serializer = new Persister();
Card_info_xml card_info_xml_object = new Card_info_xml(company, designation,
department,
address, tel_no, fax_no, website,
linkedin, facebook, googleplus, resume,
portfolio, other, mobile,id);

File result = new File(Environment.getExternalStorageDirectory(), "card_info.xml");

try {
Log.d("Start", "Serializing");
serializer.write(card_info_xml_object, result);
} catch (Exception e) {
Log.d("Self", "Error");
e.printStackTrace();
}

//Send the above xml to the server

/*--The connection to the server is established in another (not main) thread.
This prevents the app to stop responding if the connection to the server is not established
or it takes time to establish the connection--*/

new Thread(new Runnable() {
@Override
public void run() {

String url = "http://10.0.2.2:8080/project_server/Card";
File file = new File(Environment.getExternalStorageDirectory(), "card_info.xml");

try {

//Send user mobile number to the server.
URL mobileurl = new URL("http://10.0.2.2:8080/project_server/Card");
URLConnection connection = mobileurl.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new
OutputStreamWriter(connection.getOutputStream());
out.write(mobile);
out.close();

BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
in.readLine();
in.close();

//Send XML Data to the server
112

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file),
-1);
reqEntity.setContentType("text/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("done", response.toString());

} catch(Exception e) {
Log.d("Not Sent", "fail");
e.printStackTrace();
}

}
}).start();


}

}

SEARCH.JAVA

package com.kk.project;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.EditText;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
113


public class Search extends Activity {

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

if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search, container, false);
return rootView;
}
114

}

public void search(View view) {

EditText cinSearchString = (EditText)findViewById(R.id.search_string);
String searchString = cinSearchString.getText().toString();

//Send the search string to the server and get values as arrays
getSearchResult(searchString);

//Go to SearchResult activity
Intent openResult = new Intent(this, SearchResult.class);
startActivity(openResult);

}

//Method to fetch all the search result from the server
public void getSearchResult(final String searchString){

/*--The connection to the server is established in another (not main) thread.
This prevents the app to stop responding if the connection to the server is not established
or it takes time to establish the connection--*/

new Thread(new Runnable() {
@Override
public void run() {

try {

//Send search string to the server
URL mobileurl = new URL("http://10.0.2.2:8080/project_server/Search");
URLConnection connection = mobileurl.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new
OutputStreamWriter(connection.getOutputStream());
out.write(searchString);
out.close();

BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
in.readLine();
in.close();

//Fetch result in XML format
URL GetCardXmlUrl = new
URL("http://10.0.2.2:8080/searchresultxml/search_xml_output.xml");
URLConnection GetresultXmlConnection = GetCardXmlUrl.openConnection();
InputStream ResultInstream = new
BufferedInputStream(GetresultXmlConnection.getInputStream());
115

Serializer PhoneBookSerializer = new Persister();

Search_info_xml parse_result_xml =
PhoneBookSerializer.read(Search_info_xml.class, ResultInstream);
final String mobile_nos[] = parse_result_xml.getPhones();

Log.d("note:", "getting stuff");
Log.d("number: ", mobile_nos[0]);

MainDataBase addSearchResult = new MainDataBase(Search.this);
addSearchResult.open();

for(int i=0; i<mobile_nos.length; i++) {

addSearchResult.CreateEntrySearchResult(mobile_nos[i]);
Log.d("value: ", mobile_nos[i]);
}

addSearchResult.close();

} catch (Exception e) {

e.printStackTrace();
}

}
}).start();

}


}


SEARCH_INFO_XML.JAVA

package com.kk.project;


import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;

@Root(name="search_result")
public class Search_info_xml {

@ElementArray(name="searchResults", entry="mobile_number")
private String[] phones;

public Search_info_xml() {
super();
116

}

public Search_info_xml(String[] phones) {
this.phones = phones;
}

public String[] getPhones() {
return phones;
}
}


SEARCHRESULT.JAVA

package com.kk.project;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class SearchResult extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
117

super.onCreate(savedInstanceState);


MainDataBase getResult = new MainDataBase(SearchResult.this);
getResult.open();
String[] mobile_nos = getResult.getSearchResult();
getResult.close();

try {

setListAdapter(new ArrayAdapter<String>(this, R.layout.phonebook_listview,
mobile_nos));
} catch(Exception e) {

e.printStackTrace();
}

ListView listView = getListView();
listView.setTextFilterEnabled(true);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the mobile number
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_result, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
118


@Override
public void onBackPressed()
{
MainDataBase deleteResult = new MainDataBase(this);

deleteResult.open();
deleteResult.deleteSearchResult();
deleteResult.close();
super.onBackPressed();
}

}

SENDCARD.JAVA

package com.kk.project;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class SendCard extends Activity {

119

public int xml_id = 4000;

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

if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.send_card, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_send_card, container, false);
return rootView;
}
}
120


public void sendreceiverinfo(View view) throws Exception {

//Take the mobile number of the to-be receiver
EditText cinMobile = (EditText)findViewById(R.id.receiver_mobile);
String ReceiverMobile = cinMobile.getText().toString();

//Get the Sender's (current user's) mobile number form the local database.
MainDataBase getMobile = new MainDataBase(this);
getMobile.open();
String Mobile[] = getMobile.getAllRegInfo();
getMobile.close();

final String SenderMobile = Mobile[2];

Log.d("Sender Mobile:", SenderMobile);

//Generate send_card_info.xml serialized file for the above data
Serializer serializer = new Persister();
SendCard_info_xml sendCard_info_xml_object = new
SendCard_info_xml(SenderMobile, ReceiverMobile, xml_id);
File result = new File(Environment.getExternalStorageDirectory(),
"send_card_info.xml");

try {
Log.d("Start", "Serializing");
serializer.write(sendCard_info_xml_object, result);
} catch (Exception e) {
Log.d("Self", "Error");
e.printStackTrace();
}

//Send the data over to the server. Data is retrieved by parsing the xml file created
above.
Serializer getserializer = new Persister();
File source = new File(Environment.getExternalStorageDirectory(),
"send_card_info.xml");

SendCard_info_xml parse_xml = getserializer.read(SendCard_info_xml.class, source);

/*---*/

/*--The connection to the server is established in another (not main) thread.
This prevents the app to stop responding if the connection to the server is not established
or it takes time to establish the connection--*/

new Thread(new Runnable() {
@Override
public void run() {

121

String url = "http://10.0.2.2:8080/project_server/SendCard";
File file = new File(Environment.getExternalStorageDirectory(),
"send_card_info.xml");

try{

//Send user mobile number to the server.
URL mobileurl = new URL("http://10.0.2.2:8080/project_server/SendCard");
URLConnection connection = mobileurl.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new
OutputStreamWriter(connection.getOutputStream());
out.write(SenderMobile);
out.close();

BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
in.readLine();
in.close();

//Send XML file to the server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file),
-1);
reqEntity.setContentType("text/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("done", response.toString());

} catch(Exception e) {

Log.d("Not Sent", "failed");
e.printStackTrace();

}

}
}).start();


}

}

SENDCARD_INFO_XML.JAVA

package com.kk.project;

122

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;



@Root(name="sender_and_receiver_info")
public class SendCard_info_xml {

@Element(name="sender_mobile")
private String sender_mobile;

@Element(name="receiver_mobile")
private String receiver_mobile;

@Attribute(name="xml_id")
private int xml_id;

public SendCard_info_xml() {
super();
}

public SendCard_info_xml(String s_mobile, String r_mobile, int id) {

this.sender_mobile = s_mobile;
this.receiver_mobile = r_mobile;
this.xml_id = id;

}

public String getSender_mobile() {
return sender_mobile;
}

public String getReceiver_mobile() {
return receiver_mobile;
}

public int getXml_id() {
return xml_id;
}

}



7.1.2 LAYOUT CODE

ACTIVITY_CARDINFOENTRY.XML

123

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical">

<TextView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="27sp"
android:text="@string/create_card_text"/>

<TextView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#ff949494"
android:text="@string/create_card_info_text_one"/>

<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:hint="Name"/>

<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:inputType="textEmailAddress"
android:hint="Email"/>

<TextView
android:id="@+id/phone_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:hint="Phone Number"/>
124


<Button
android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="280dp"
android:text="@string/create_card_next_button"
android:onClick="next"/>

</LinearLayout>


</ScrollView>

ACTIVITY_CARDINFOENTRYTWO.XML

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp" >

<TextView
android:id="@+id/heading"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="27sp"
android:text="@string/create_card_text" />

<TextView
android:id="@+id/subheading"
android:layout_below="@id/heading"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#ff949494"
android:text="@string/create_card_info_text_two" />

<EditText
android:id="@+id/company_name"
125

android:layout_below="@id/subheading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:hint="Company Name"/>

<EditText
android:id="@+id/designation"
android:layout_below="@id/company_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Designation" />

<EditText
android:id="@+id/department"
android:layout_below="@id/designation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Department"/>


<EditText
android:id="@+id/address"
android:layout_below="@id/department"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Address" />

<EditText
android:id="@+id/tel_number"
android:layout_below="@id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Telephone Number" />

<EditText
android:id="@+id/fax"
android:layout_below="@id/tel_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Fax"/>

<EditText
android:id="@+id/website"
android:layout_below="@id/fax"
126

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Website" />

<Button
android:id="@+id/next_button"
android:layout_below="@id/website"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="250dp"
android:onClick="next"
android:text="@string/create_card_next_button" />

<Button
android:id="@+id/previous_button"
android:layout_below="@id/website"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="previous"
android:text="@string/create_card_previous_button"/>

</RelativeLayout>

</ScrollView>


ACTIVITY_CARDINFOENTRYTHREE.XML

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp" >

<TextView
android:id="@+id/heading"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="27sp"
android:text="@string/create_card_text" />

127

<TextView
android:id="@+id/subheading"
android:layout_below="@id/heading"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#ff949494"
android:text="@string/create_card_info_text_three" />

<EditText
android:id="@+id/linkedin"
android:layout_below="@id/subheading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:hint="LinkedIn Profile"/>

<EditText
android:id="@+id/facebook"
android:layout_below="@id/linkedin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Facebook Profile" />

<EditText
android:id="@+id/googleplus"
android:layout_below="@id/facebook"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Google+ Profile" />

<EditText
android:id="@+id/resume"
android:layout_below="@id/googleplus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Online Resume" />

<EditText
android:id="@+id/portfolio"
android:layout_below="@id/resume"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Online Portfolio"/>

128

<EditText
android:id="@+id/other"
android:layout_below="@id/portfolio"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Any other Link" />

<Button
android:id="@+id/next_button"
android:layout_below="@id/other"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="250dp"
android:onClick="next"
android:text="@string/create_card_next_button" />

<Button
android:id="@+id/previous_button"
android:layout_below="@id/other"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="previous"
android:text="@string/create_card_previous_button"/>

</RelativeLayout>

</ScrollView>

ACTIVITY_DASHBOARD.JAVA

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

<TextView
android:id="@+id/welcome_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dashboard_welcome_text" />

<TextView
129

android:id="@+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/welcome_text"
android:layout_marginLeft="2dp"
android:hint="UserName" />

<Button
android:id="@+id/edit_profile_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/welcome_text"
android:layout_marginTop="20dp"
android:text="@string/edit_profile_button_text"
android:onClick="editprofile" />

<Button
android:id="@+id/send_card_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/edit_profile_button"
android:layout_marginTop="10dp"
android:text="@string/send_card_button_text"
android:onClick="sendbussinesscard" />

<Button
android:id="@+id/view_received_cards_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/send_card_button"
android:layout_marginTop="10dp"
android:text="@string/view_received_card_info_button_text"
android:onClick="viewreceivedcards"/>

<Button
android:id="@+id/view_my_bussiness_card"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/view_received_cards_button"
android:layout_marginTop="10dp"
android:text="@string/view_my_business_card_button_text"
android:onClick="viewmycard"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/view_my_bussiness_card"
android:layout_marginTop="10dp"
android:text="@string/search_button_text"
android:onClick="search"/>
130


<Button
android:id="@+id/logoff_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/view_my_bussiness_card"
android:layout_marginTop="80dp"
android:text="@string/logout_button_text"
android:onClick="logout"/>

</RelativeLayout>

ACTIVITY_INDEX.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".Index">


</RelativeLayout>

ACTIVITY_INDEX.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/login_page_text"
android:textSize="40sp" />


<EditText
android:id="@+id/mobile_no"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
131

android:inputType="textEmailAddress"
android:hint="Mobile Number" />

<EditText
android:id="@+id/password"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:inputType="textPassword"
android:hint="Password" />

<Button
android:id="@+id/login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/login_button_text"
android:onClick="login" />

<TextView
android:gravity="center_horizontal"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="or" />

<Button
android:id="@+id/register_button"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/register_button_text"
android:onClick="register" />

</LinearLayout>






ACTIVITY_RECEIVED_CARDS.XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kk.project.ReceivedCards"
132

tools:ignore="MergeRootFrame" />

ACTIVITY_REGISTER.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >

<TextView
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="@string/register_text" />

<EditText
android:id="@+id/user_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:hint="Name" />

<EditText
android:id="@+id/mobile_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:inputType="phone"
android:hint="Mobile Number" />

<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:inputType="textEmailAddress"
android:hint="Email Id" />

<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:inputType="textPassword"
android:hint="Password" />

<Button
133

android:id="@+id/register_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/register_button_text"
android:onClick="register" />


</LinearLayout>


ACTIVITY_REGISTERPREVIEW.XML

<LinearLayout 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=".RegisterPreview"
android:orientation="vertical" >

<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:hint="Name"/>

<TextView
android:id="@+id/designation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:hint="Designation"/>

<TextView
android:id="@+id/department"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:hint="Department"/>

<TextView
android:id="@+id/company"
134

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:textSize="20sp"
android:hint="Company Name"/>

<TextView
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:hint="Address"/>

<TextView
android:id="@+id/telephone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:hint="Phone"/>

<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:hint="mobile"/>

<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:hint="Email Id"/>

<TextView
android:id="@+id/website"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:hint="Website"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
135

android:text="@string/send_to_server"
android:onClick="send_to_server"/>

</LinearLayout>


ACTIVITY_SEARCH.XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kk.project.Search"
tools:ignore="MergeRootFrame" />

ACTIVITY_SEARCH_RESULT.XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kk.project.SearchResult"
tools:ignore="MergeRootFrame" />

ACTIVITY_SEND_CARD.XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kk.project.SendCard"
tools:ignore="MergeRootFrame" />







ACTIVITY_TEST.XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".test"
136

tools:ignore="MergeRootFrame" />

FRAGMENT_SEARCH.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/search_page_text"
android:textSize="40sp" />

<EditText
android:id="@+id/search_string"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Enter name of a company"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/search_button_text"
android:onClick="search"/>

</LinearLayout>









FRAGMENT_SEARCH_RESULT.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
137

android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.kk.project.SearchResult$PlaceholderFragment">

<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</RelativeLayout>

FRAGMENT_SEND_CARD.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
tools:context="com.kk.project.SendCard$PlaceholderFragment">

<TextView
android:layout_marginTop="25dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send_card"
android:textSize="40sp"/>

<EditText
android:id="@+id/receiver_mobile"
android:layout_marginTop="25dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter the receiver's mobile number" />

<Button
android:layout_marginTop="25dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/send_button_text"
android:onClick="sendreceiverinfo"/>
7.2 BACK END CODE


CARD_INFO_XML.JAVA

package project_server;

import org.simpleframework.xml.Attribute;
138

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name="card_info")
public class Card_info_xml {

@Element(name="company", required=false)
private String company_name;

@Element(name="designation", required=false)
private String company_designation;

@Element(name="department", required=false)
private String company_department;

@Element(name="address", required=false)
private String company_address;

@Element(name="tel_no", required=false)
private String company_telephone_no;

@Element(name="fax", required=false)
private String fax_no;

@Element(name="website", required=false)
private String company_website;

@Element(name="linkedin", required=false)
private String linkedin_link;

@Element(name="facebook", required=false)
private String facebook_link;

@Element(name="googleplus", required=false)
private String googleplus_link;

@Element(name="resume", required=false)
private String resume_link;

@Element(name="portfolio", required=false)
private String portfolio_link;

@Element(name="other", required=false)
private String other_link;

@Element(name="mobile", required=false)
private String mobile;

@Attribute(name="xml_id", required=false)
private int xml_id;
139


public Card_info_xml() {
super();
}

public Card_info_xml(String company, String designation,
String department, String address, String tel_no, String fax_no,
String website, String linkedin, String facebook, String googleplus,
String resume, String portfolio, String other, String mobile, int id) {

this.company_name = company;
this.company_designation = designation;
this.company_department = department;
this.company_address = address;
this.company_telephone_no = tel_no;
this.fax_no = fax_no;
this.company_website = website;
this.linkedin_link = linkedin;
this.facebook_link = facebook;
this.googleplus_link = googleplus;
this.resume_link = resume;
this.portfolio_link = portfolio;
this.other_link = other;
this.xml_id = id;

}

public String getCompany_name(){
return company_name;
}

public String getDesignation(){
return company_designation;
}

public String getDepartment(){
return company_department;
}

public String getAddress(){
return company_address;
}

public String getTelphone_no(){
return company_telephone_no;
}

public String getFax_no(){
return fax_no;
}
140


public String getWebsite(){
return company_website;
}

public String getLinkedin(){
return linkedin_link;
}

public String getFacebook(){
return facebook_link;
}

public String getGoogleplus(){
return googleplus_link;
}

public String getResume(){
return resume_link;
}

public String getPortfolio(){
return portfolio_link;
}

public String getOther(){
return other_link;
}

public String getMobile(){
return mobile;
}

public int getXml_id() {
return xml_id;
}

}




CARD.JAVA

package project_server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
141

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/*This servlet is responsible for receiving user's card data and storing it on the DB; creating
his profile in the process */

@WebServlet("/Card")
public class Card extends HttpServlet {
private static final long serialVersionUID = 1L;

public boolean phoneReadFlag = true;
public String receivedMobileString;

public Card() {
super();
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.getOutputStream().println(
"Hello world! The Card servelet is alive and kicking!");

}

// This method is called by the Android app.
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

if(phoneReadFlag) {

//Get the phone number
int length = request.getContentLength();
System.out.print(length + "\n");
142

byte[] input = new byte[length];
ServletInputStream sin = request.getInputStream();
int c, count = 0;

while((c = sin.read(input, count, input.length-count)) != -1) {
count = +c;

}

sin.close();

receivedMobileString = new String(input);

System.out.print(receivedMobileString + "\n");

response.setStatus(HttpServletResponse.SC_OK);

phoneReadFlag = false;

} else {

//Accept XML data from the app
response.setContentType("text/xml");
ServletInputStream inputStream = request.getInputStream();
ServletOutputStream outputStream = response.getOutputStream();
BufferedReader in = new BufferedReader(new
InputStreamReader(inputStream));
BufferedWriter out = new BufferedWriter(new
OutputStreamWriter(outputStream));

String line = "";
String xmlString = "";
while ((line = in.readLine()) != null) {
xmlString += line + "\n";
}

//Write to a output stream writer
try {

System.out.println("Saving the file on HDD");
String thisFile = new
String("/home/arpita/Desktop/workspace/xml_files/card_xml_output/card_xml_output_"+
receivedMobileString +".xml");
OutputStreamWriter oos = new OutputStreamWriter(
new FileOutputStream(thisFile));
oos.write(xmlString);
oos.close();
oos = null;
thisFile = null;

143

} catch (IOException ioe) {
System.out.println("Opps! Something went wrong.");
System.out.println("IO error: " + ioe);
}

out.flush();
out.close();
in.close();

try {
PullXMLData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

phoneReadFlag = true;

}

System.out.println("End of Card doPost");

}

//Method to pull the data from the XML file
public void PullXMLData() throws Exception {

Serializer serializer = new Persister();
File source = new
File("/home/arpita/Desktop/workspace/xml_files/card_xml_output/card_xml_output_"+
receivedMobileString +".xml");

Card_info_xml parse_xml = serializer.read(Card_info_xml.class, source);

String company_name = parse_xml.getCompany_name();
String designation = parse_xml.getDepartment();
String department = parse_xml.getDepartment();
String address = parse_xml.getAddress();
String telephone = parse_xml.getTelphone_no();
String fax = parse_xml.getFax_no();
String website = parse_xml.getWebsite();
String linkedin = parse_xml.getLinkedin();
String facebook = parse_xml.getFacebook();
String googleplus = parse_xml.getGoogleplus();
String resume = parse_xml.getResume();
String portfolio = parse_xml.getPortfolio();
String other = parse_xml.getOther();
String mobile = parse_xml.getMobile();

DbWrite(company_name, designation, department, address, telephone,
144

fax, website, linkedin, facebook, googleplus, resume, portfolio,
other, mobile);

}

//Write the XML data on to the database
public void DbWrite(String company, String designation, String department, String
address, String telephone,
String fax, String website, String
linkedin, String facebook, String googleplus,
String resume, String portfolio, String
other, String mobile) throws SQLException, ClassNotFoundException {

Connection connection = null;
Statement statement = null;

Class.forName("com.mysql.jdbc.Driver");

connection =
DriverManager.getConnection("jdbc:mysql://localhost/MainDB","root","root");
statement = (Statement) connection.createStatement();
String insert = "INSERT INTO user_card_info_db VALUES('"+ company +"',
'"+ designation +"', '"+ department +
"', '" + address + "', '" + telephone + "', '" + fax + "', '" +
website + "', '" + linkedin + "', '" +
facebook + "', '" + googleplus + "', '" + resume + "', '" +
portfolio + "', '" + other +"', '" + mobile +"' );";
statement.executeUpdate(insert);

statement.close();
connection.close();

}

}




GETCARD_INFO_XML.JAVA

package project_server;

import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;

@Root(name="received_card_info")
public class GetCard_info_xml {

@ElementArray(name="phoneBook", entry="mobile_number")
145

private String[] phones;

public GetCard_info_xml() {
super();
}

public GetCard_info_xml(String[] phones) {
this.phones = phones;
}

public String[] getPhones() {
return phones;
}

}


GETCARD.JAVA

package project_server;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/* This servlet is used to send all the mobile nos (business cards) of all the users sent to him.
*/

@WebServlet("/GetCard")
public class GetCard extends HttpServlet {
private static final long serialVersionUID = 1L;

public String receivedMobileString;
public String[] received_numbers;
public int MobileCount = 0;

146

public GetCard() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getOutputStream().print("Hello world! The GetCard servlet is alive
and kicking!");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//Get the phone number
int length = request.getContentLength();
//System.out.print(length + "\n");
byte[] input = new byte[length];
ServletInputStream sin = request.getInputStream();
int c;
int count = 0;
int number_count = 0;

while((c = sin.read(input, count, input.length-count)) != -1) {
count = +c;

}

sin.close();

receivedMobileString = new String(input);

//System.out.print(receivedMobileString + "\n");

response.setStatus(HttpServletResponse.SC_OK);

//Query the database for all the received mobile numbers associate
with user's mobile number
Connection connection = null;
Statement statement = null;

try {

Class.forName("com.mysql.jdbc.Driver");

connection =
DriverManager.getConnection("jdbc:mysql://localhost/MainDB","root","root");
statement = (Statement) connection.createStatement();

String queryForCount = "SELECT received_mobile_no FROM
received_card_info_db WHERE mobile ='" +
147


receivedMobileString +"'; ";
ResultSet count_result =
statement.executeQuery(queryForCount);

while(count_result.next()) {

number_count++; //Keeps
track of number of mobile numbers in the DB

}

System.out.print("Number of phone numbers are: " +
number_count);

String query_to_get_received_mobile_numbers = "SELECT
received_mobile_no FROM received_card_info_db WHERE mobile = '" +
receivedMobileString +"' ;";
ResultSet result =
statement.executeQuery(query_to_get_received_mobile_numbers);

int i = 0;

received_numbers = new String[number_count];

while(result.next() && i<number_count) {

received_numbers[i] =
result.getString("received_mobile_no");
i++;

}

} catch (Exception e) {
e.printStackTrace();
}

System.out.print("\n");

for(int i=0; i<number_count; i++) {
System.out.print(received_numbers[i] + "\n");
}

Serializer serializer = new Persister();
GetCard_info_xml getCard_Object = new
GetCard_info_xml(received_numbers);
File result = new
File("/home/arpita/Desktop/workspace/xml_files/GetCard_xml_output/GetCard_xml_output_
"+ receivedMobileString +".xml");
try {
148

serializer.write(getCard_Object, result);
} catch (Exception e) {
e.printStackTrace();
}

OutputStreamWriter writer = new
OutputStreamWriter(response.getOutputStream());
writer.write(received_numbers.toString());

System.out.print("End of Login doPost");

}

}


LOGIN_INFO_XML.JAVA

package project_server;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name="login_info")
public class Login_info_xml {

@Element(name="mobile")
private String mobile;

@Element(name="password")
private String password;

@Attribute(name="xml_id")
private int xml_id;

public Login_info_xml() {
super();
}

public Login_info_xml(String input_mobile, String input_password, int id) {

this.mobile = input_mobile;
this.password = input_password;
this.xml_id = id;

}

public String getMobile() {
return mobile;
149

}

public String getPassword() {
return password;
}

public int getXml_id() {
return xml_id;
}
}

LOGIN.JAVA

package project_server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;


@WebServlet(description = "servlet which handles login (app sends the login data and
servlet authorises it)", urlPatterns = { "/Login" })
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;

public boolean phoneReadFlag = true;
public String receivedMobileString;

public Login() {
super();
150

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.getOutputStream().print("Hello world! The Login servlet is alive and
kicking!");

}

//This method is called by the android app
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

if(phoneReadFlag) {

//Get the phone number
int length = request.getContentLength();
System.out.print(length + "\n");
byte[] input = new byte[length];
ServletInputStream sin = request.getInputStream();
int c, count = 0;

while((c = sin.read(input, count, input.length-count)) != -1) {
count = +c;

}

sin.close();

receivedMobileString = new String(input);

System.out.print(receivedMobileString + "\n");

response.setStatus(HttpServletResponse.SC_OK);

phoneReadFlag = false;

} else {

//Accept the XML data from the app
response.setContentType("text/xml");
ServletInputStream inputStream = request.getInputStream();
ServletOutputStream outputStream = response.getOutputStream();
BufferedReader in = new BufferedReader(new
InputStreamReader(inputStream));
BufferedWriter out = new BufferedWriter(new
OutputStreamWriter(outputStream));

String line = "";
151

String xmlString = "";
while ( (line = in.readLine()) != null ) {
xmlString += line + "\n";
}

//write to a output stream writer
try {

System.out.println("Saving the file on HDD");
String thisFile = new
String("/home/arpita/Desktop/workspace/xml_files/login_xml_output/login_xml_output_" +
receivedMobileString +".xml");
OutputStreamWriter oos = new OutputStreamWriter(new
FileOutputStream(thisFile));
oos.write(xmlString);
oos.close();
oos=null;
thisFile=null;

}catch(IOException ioe) {
System.out.println("Opps! Something went wrong.");
System.out.println("IO error: " + ioe);
}

try {
if(PullXMLData()) {
System.out.print("User exists and password verified
\n");
out.write("Login Verified");
}
} catch (Exception e) {
e.printStackTrace();
}

out.flush();
out.close();
in.close();

phoneReadFlag = true;

}

System.out.println("End of Login doPost");

}

//Method which pulls data from the XML file saved by the doPost method
public boolean PullXMLData() throws Exception {

Serializer serializer = new Persister();
152

File source = new
File("/home/arpita/Desktop/workspace/xml_files/login_xml_output/login_xml_output_" +
receivedMobileString +".xml");

Login_info_xml parse_xml = serializer.read(Login_info_xml.class,
source);

String mobile = parse_xml.getMobile();
String password = parse_xml.getPassword();

if(DbCheck(mobile, password)) {
return true;
}else
return false;
}

//Method to check the passed values (password and mobile number) against the
values in the database
public boolean DbCheck(String mobile, String password) throws
ClassNotFoundException, SQLException {

Connection connection = null;
Statement statement = null;

String output_mobile = "";
String output_password = "";

Class.forName("com.mysql.jdbc.Driver");

connection =
DriverManager.getConnection("jdbc:mysql://localhost/MainDB","root","root");
statement = (Statement) connection.createStatement();
String query = "SELECT * FROM reg_info_db WHERE mobile = '"+ mobile
+"' ;";
ResultSet result = statement.executeQuery(query);

while(result.next()) {

output_mobile = result.getString("mobile");
System.out.print(output_mobile + "\n");

output_password = result.getString("password");
System.out.print(output_password + "\n");

}

if(output_mobile.equals("") && output_password.equals("")) {
return false;
} else if (password.equals(output_password) &&
mobile.equals(output_mobile)){
153

return true;
}

return false;

}



}

REGISTER_INFO_XML.JAVA

package project_server;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name="reg_info")
public class Reg_info_xml {

@Element(name="name")
private String user_name;

@Element(name="email")
private String mail_id;

@Element(name="mobile")
private String mobile_no;

@Element(name="pass")
private String passphrase;

@Attribute(name="xml_id")
private int xml_id;

public Reg_info_xml() {
super();
}

public Reg_info_xml(String name, String email, String mobile, String password, int id) {

this.user_name = name;
this.mail_id = email;
this.mobile_no = mobile;
this.passphrase = password;
this.xml_id = id;

}
154


public String getName() {
return user_name;
}

public String getEmail() {
return mail_id;
}

public String getMobile() {
return mobile_no;
}

public String getPassword() {
return passphrase;
}

public int getXml_id() {
return xml_id;
}

}


REGISTER.JAVA

package project_server;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simpleframework.xml.Serializer;
155

import org.simpleframework.xml.core.Persister;

@WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;

public boolean phoneReadFlag = true;
public String receivedMobileString;

public Register() {
super();
}


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.getOutputStream().println("Hello world! The Register servlet is alive
and kicking!");

}

//this method is called by the Android app.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

if(phoneReadFlag) {

//Get the phone number
int length = request.getContentLength();
System.out.print(length + "\n");
byte[] input = new byte[length];
ServletInputStream sin = request.getInputStream();
int c, count = 0;

while((c = sin.read(input, count, input.length-count)) != -1) {
count = +c;

}

sin.close();

receivedMobileString = new String(input);

System.out.print(receivedMobileString + "\n");

response.setStatus(HttpServletResponse.SC_OK);

phoneReadFlag = false;

156

} else {

//Accept the XML data from the app
response.setContentType("text/xml");
ServletInputStream inputStream = request.getInputStream();
//ServletOutputStream outputStream = response.getOutputStream();
BufferedReader in = new BufferedReader(new
InputStreamReader(inputStream));
//BufferedWriter out = new BufferedWriter(new
OutputStreamWriter(outputStream));

String line = "";
String xmlString = "";
while ( (line = in.readLine()) != null ) {
xmlString += line + "\n";
}

//write to a output stream writer
try {

System.out.println("Saving the file on HDD");
String thisFile = new
String("/home/arpita/Desktop/workspace/xml_files/reg_info_xml_output/reg_info_xml_outpu
t_"+ receivedMobileString +".xml");
OutputStreamWriter oos = new OutputStreamWriter(new
FileOutputStream(thisFile));
oos.write(xmlString);
oos.close();
oos=null;
thisFile=null;

}catch(IOException ioe) {
System.out.println("Opps! Something went wrong.");
System.out.println("IO error: " + ioe);
}

//out.flush();
//out.close();
in.close();

try {
PullXMLData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

phoneReadFlag = true;

}
157


System.out.println("End of Register doPost");

}

//Method to write data from the XML to the database ('reg_info_db' table).
public void DbWrite(String user_name, String user_mail, String user_mobile, String
user_password) throws ClassNotFoundException, SQLException {

Connection connection = null;
Statement statement = null;

Class.forName("com.mysql.jdbc.Driver");

connection =
DriverManager.getConnection("jdbc:mysql://localhost/MainDB","root","root");
statement = (Statement) connection.createStatement();
String insert = "INSERT INTO reg_info_db VALUES ('"+ user_name +"', '"+
user_mail +"', '"+ user_mobile +"', '"+ user_password +"');";
statement.executeUpdate(insert);

statement.close();
connection.close();

}


//Method to pull data from the XML file saved by the doPost() method.
public void PullXMLData() throws Exception {

Serializer serializer = new Persister();
File source = new
File("/home/arpita/Desktop/workspace/xml_files/reg_info_xml_output/reg_info_xml_output_
"+ receivedMobileString +".xml");

Reg_info_xml parse_xml = serializer.read(Reg_info_xml.class, source);
String name = parse_xml.getName();
String email = parse_xml.getEmail();
String mobile = parse_xml.getMobile();
String password = parse_xml.getPassword();

System.out.print(name);
System.out.print("\n" + email);
System.out.print("\n" + mobile);
System.out.print("\n" + password);

DbWrite(name, email, mobile, password);

}

158

}


SEARCH_INFO_XML.JAVA

package project_server;

import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;

@Root(name="search_result")
public class Search_info_xml {

@ElementArray(name="searchResults", entry="mobile_number")
private String[] phones;

public Search_info_xml() {
super();
}

public Search_info_xml(String[] phones) {
this.phones = phones;
}

public String[] getPhones() {
return phones;
}
}






SEARCH.JAVA


package project_server;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
159

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/* This servlet is responsible for searching users by company */

@WebServlet("/Search")
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;

int number_count = 0;
public String receivedSearchString;
public String[] result_numbers;

public Search() {
super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.getOutputStream().print("Hello world! The Search servlet is alive
and kicking!");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//Get the search string
int length = request.getContentLength();
byte[] input = new byte[length];
ServletInputStream sin = request.getInputStream();
int c;
int count = 0;
int number_count = 0;

while((c = sin.read(input, count, input.length-count)) != -1) {
count = +c;

}

sin.close();

receivedSearchString = new String(input);
System.out.print(receivedSearchString);

160

//Query the database for matching results
Connection connection = null;
Statement statement = null;

try {

Class.forName("com.mysql.jdbc.Driver");

connection =
DriverManager.getConnection("jdbc:mysql://localhost/MainDB","root","root");
statement = (Statement) connection.createStatement();

String queryForCount = "SELECT mobile FROM user_card_info_db
WHERE company ='" +
receivedSearchString +"';
";
ResultSet count_result = statement.executeQuery(queryForCount);

while(count_result.next()) {

number_count++; //Keeps track of
number of mobile numbers in the DB

}

System.out.print("\nNumber of phone numbers are: " +
number_count);

String query_to_get_received_mobile_numbers = "SELECT mobile
FROM user_card_info_db WHERE company ='" +

receivedSearchString +"'; ";
ResultSet result =
statement.executeQuery(query_to_get_received_mobile_numbers);

int i = 0;

result_numbers = new String[number_count];

while(result.next() && i<number_count) {

result_numbers[i] = result.getString("mobile");
i++;
}

} catch (Exception e) {

e.printStackTrace();
}

161

for(int i=0; i<number_count; i++) {
System.out.print("\n" + result_numbers[i]);
}

Serializer serializer = new Persister();
Search_info_xml search_xml_object = new Search_info_xml(result_numbers);
File result = new
File("/home/arpita/Desktop/workspace/xml_files/search_xml_output/search_xml_output.xml"
);
try {
serializer.write(search_xml_object, result);
} catch (Exception e) {
e.printStackTrace();
}


System.out.println("\nEnd of Search doPost");

}

}



SENDCARD_INFO_XML.JAVA

package project_server;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name="sender_and_receiver_info")
public class SendCard_info_xml {

@Element(name="sender_mobile")
private String sender_mobile;

@Element(name="receiver_mobile")
private String receiver_mobile;

@Attribute(name="xml_id")
private int xml_id;

public SendCard_info_xml() {
super();
}

public SendCard_info_xml(String s_mobile, String r_mobile, int id) {

162

this.sender_mobile = s_mobile;
this.receiver_mobile = r_mobile;
this.xml_id = id;

}

public String getSender_mobile() {
return sender_mobile;
}

public String getReceiver_mobile() {
return receiver_mobile;
}

public int getXml_id() {
return xml_id;
}

}


SENDCARD.JAVA

package project_server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/* This servlet is utilized when a user sends his/her card to another */

163

@WebServlet("/SendCard")
public class SendCard extends HttpServlet {
private static final long serialVersionUID = 1L;

public boolean phoneReadFlag = true;
public String receivedMobileString;

public SendCard() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.getOutputStream().print("Hello world! The SendCard servlet is alive
and kicking!");

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

if(phoneReadFlag) {

//Get the phone number
int length = request.getContentLength();
System.out.print(length + "\n");
byte[] input = new byte[length];
ServletInputStream sin = request.getInputStream();
int c, count = 0;

while((c = sin.read(input, count, input.length-count)) != -1) {
count = +c;

}

sin.close();

receivedMobileString = new String(input);

System.out.print(receivedMobileString + "\n");

response.setStatus(HttpServletResponse.SC_OK);

phoneReadFlag = false;

} else {

// Accept XML data from the app
response.setContentType("text/xml");
164

ServletInputStream inputStream = request.getInputStream();
ServletOutputStream outputStream = response.getOutputStream();
BufferedReader in = new BufferedReader(new
InputStreamReader(inputStream));
BufferedWriter out = new BufferedWriter(new
OutputStreamWriter(outputStream));

String line = "";
String xmlString = "";
while ((line = in.readLine()) != null) {
xmlString += line + "\n";
}

// write to a output stream writer
try {

System.out.println("Saving the file on HDD");
String thisFile = new
String("/home/arpita/Desktop/workspace/xml_files/send_card_xml_output/send_card_xml_o
utput_"+ receivedMobileString +".xml");
OutputStreamWriter oos = new OutputStreamWriter(new
FileOutputStream(thisFile));
oos.write(xmlString);
oos.close();
oos = null;
thisFile = null;

} catch (IOException ioe) {
System.out.println("Opps! Something went wrong.");
System.out.println("IO error: " + ioe);
}

out.flush();
out.close();
in.close();

try {
PullXMLData();
} catch (Exception e) {
e.printStackTrace();
}

phoneReadFlag = true;
}

System.out.print("End of Login doPost");

}

//Pull data from the XML file
165

public void PullXMLData() throws Exception {

Serializer serializer = new Persister();
File source = new
File("/home/arpita/Desktop/workspace/xml_files/send_card_xml_output/send_card_xml_outp
ut_"+ receivedMobileString +".xml");

SendCard_info_xml parse_xml = serializer.read(SendCard_info_xml.class,
source);

String SenderMobile = parse_xml.getSender_mobile();
String ReceiverMobile = parse_xml.getReceiver_mobile();

DbWrite(SenderMobile, ReceiverMobile);

}

//Write the pulled data from the XML file and write onto the database
public void DbWrite(String S_Mobile, String R_Mobile) throws
ClassNotFoundException, SQLException {

Connection connection = null;
Statement statement = null;

Class.forName("com.mysql.jdbc.Driver");

connection =
DriverManager.getConnection("jdbc:mysql://localhost/MainDB","root","root");
statement = (Statement) connection.createStatement();

/*-- Important Note: The sender's mobile number is ultimately saved under
"received_mobile_no"
* because that becomes received mobile number for the receiver. Confusing,
I know ;) --*/
String insert = "INSERT INTO received_card_info_db VALUES('" + S_Mobile
+"', '"+ R_Mobile +"');";
statement.executeUpdate(insert);
statement.close();

connection.close();

}

}





166

Das könnte Ihnen auch gefallen