Read Excel data and use it in selenium - selenium-webdriver

This script is to read data from excel and use it in selenium script. This uses Apache POI to read the data, store it in variables and use it.

You can try following code. I have taken facebook as sample application.
package testPackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import org.testng.annotations.DataProvider;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ExcelReadingwithDP {
WebDriver driver;
#BeforeTest
public void OpenApp()
{
System.setProperty("webdriver.chrome.driver", "E:/Selenium/Webdriver/Softwares/chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://facebook.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test(dataProvider="empLogin")
public void login(String username, String password)
{
WebElement login1 = driver.findElement(By.id("email"));
login1.clear();
login1.sendKeys(username);
WebElement passwd=driver.findElement(By.id("pass"));
passwd.clear();
passwd.sendKeys(password);
driver.findElement(By.xpath("//*[#id='u_0_q']")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement back = driver.findElement(By.xpath("//*[#id='blueBarDOMInspector']/div/div[1]/div/div/h1/a/i"));
back.click();
}
#DataProvider(name="empLogin")
public Object[][] logindata()
{
Object[][] arrayobject = getexceldata("E://Deepak/IntranetLogin.xls","Sheet1");
return arrayobject;
}
public String[][] getexceldata(String filename, String sheetname)
{
String[][] arrayexceldata = null;
try
{
FileInputStream fis = new FileInputStream(filename);
Workbook wb = Workbook.getWorkbook(fis);
Sheet sh = wb.getSheet(sheetname);
int row = sh.getRows();
int col = sh.getColumns();
arrayexceldata = new String[row-1][col];
for (int i=1;i< row;i++)
{
for(int j=0;j<col;j++)
{
arrayexceldata[i-1][j]=sh.getCell(j,i).getContents();
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayexceldata;
}
}

/*
* Download Apache POI from https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-3.16-20170419.zip
*
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FormFill {
public static void main(String[] args) throws Exception {
try {
FileInputStream fileInputStream = new FileInputStream("C:\\data.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("sheet1");
HSSFRow row1 = worksheet.getRow(0);
HSSFCell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
HSSFCell cellB1 = row1.getCell((short) 1);
String b1Val = cellB1.getStringCellValue();
System.out.println("A1: " + a1Val);
System.out.println("B1: " + b1Val);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String url = "http://thedemosite.co.uk/addauser.php";
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(url);
//Thread.sleep(30000);
driver.findElement(By.name("username")).sendKeys(a1Val);
driver.findElement(By.name("password")).sendKeys(b1Val);
}
}

I feel csv is better than Excel because Excel more time to read the data but csv is fast.
private static final String CSV_SEPARATOR = ",(?=(?:[^\"]\"[^\"]\")[^\"]$)";
public List<String[]> parseFile(String fileName) {
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine(); // skip header;
String line = br.readLine();
List<String[]> lines = new ArrayList();
while (line != null) {
//System.out.println(line.toString());
lines.add(line.split(CSV_SEPARATOR));
line = br.readLine();
}
return lines;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Related

DocumentsContract.copyDocument

I have a problem with DocumentsContract.copyDocument
Each time my program crashes: "java.lang.UnsupportedOperationException: Copy not supported"
The curious thing is the below-listed actions are working fine!!
DocumentsContract.moveDocument
DocumentsContract.deleteDocument
DocumentsContract.renameDocument
DocumentsContract.createDocument
Permission to SD card access is apparently granted (above actions would fail without permission)
How come document moving, deleting and renaming is supported but not copying?
Can anyone help me with this issue?
Is there a great conceptual difference between copyDocument and moveDocument. Why move does work and copy does not?
Any hint will be highly appreciated
package com.example.forum14_11_2020;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.UriPermission;
import android.net.Uri;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.DocumentsContract;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Uri uri;
DocumentFile pickedDir;
Button Button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button1 = new Button(MainActivity.this);
Button1 = findViewById(R.id.button1);
Button1.setOnClickListener(onClickListener_Button1);
takeCardUriPermission("storage/1619-0D07");
}
View.OnClickListener onClickListener_Button1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
uri = getUri();
pickedDir = DocumentFile.fromTreeUri(getBaseContext(), uri);
DocumentFile file = pickedDir.findFile("attempt.txt");
DocumentFile folder = pickedDir.findFile("folder");
try {
//DocumentsContract.moveDocument(getContentResolver(), file.getUri(), folder.getUri(), folder.getUri()); // does work!
//DocumentsContract.deleteDocument(getContentResolver(), file.getUri()); // does work!
//DocumentsContract.renameDocument(getContentResolver(), file.getUri(), file.getName() + "_rename"); // does work!
DocumentsContract.copyDocument(getContentResolver(), file.getUri(), folder.getUri()); // does not work
} catch (UnsupportedOperationException | FileNotFoundException e) {
e.printStackTrace();
e.getMessage();
}
}
};
public void takeCardUriPermission(String sdCardRootPath) {
int stop=1;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
File sdCard = new File(sdCardRootPath);
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
StorageVolume storageVolume = storageManager.getStorageVolume(sdCard);
Intent intent = storageVolume.createAccessIntent(null);
try {
startActivityForResult(intent, 4010);
} catch (ActivityNotFoundException e) {
}
}
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 4010) {
Uri uri = data.getData();
grantUriPermission(getPackageName(), uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(uri, takeFlags);
}
}
public Uri getUri() {
List<UriPermission> persistedUriPermissions = getContentResolver().getPersistedUriPermissions();
if (persistedUriPermissions.size() > 0) {
UriPermission uriPermission = persistedUriPermissions.get(0);
return uriPermission.getUri();
}
return null;
}
}

Selenium-webdriver is giving me blank screen of google chrome and a Java null pointer exception. Can anyone suggest?

TestBase which contains the intialization method which is creating problem :
package TestBase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
public class testBasesetup {
public static Properties prop;
public static WebDriver driver;
public static testBasesetup testBaseObj;
public static EventFiringWebDriver e_driver;
public testBasesetup() throws Exception
{
try {
prop = new Properties();
File src = new File("C:\\Users\\LENOVO\\eclipse-workspace\\Demon\\src\\main\\java\\Config\\config.properties");
FileInputStream ip = new FileInputStream(src) ;
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization() throws Exception
{
String browsername = prop.getProperty("browser");
if(browsername.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", "F:\\Eclipse\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
}
else if(browsername.equals("firefox"))
{
System.setProperty("webdriver.gecko.driver", "F:\\Eclipse\\browser\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
String URLtoTest = prop.getProperty("URL");
Thread.sleep(1000);
}
}
Test Class which I am running and this is creating issue. I guess there is some issue with driver variable but don't know the error:
package PageTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
import TestBase.testBasesetup;
public class LoginPageTest extends testBasesetup{
LoginPage LoginPageObj;
testBasesetup testBaseObj;
public LoginPageTest() throws Exception
{
super();
}
#BeforeMethod
public void setup() throws Exception
{
initialization();
LoginPageObj = new LoginPage();
Thread.sleep(2000);
}
#Test()
public void LoginCheck() throws Exception
{
LoginPageObj.login("first.customer#kkr.com","Potatok");
}
#AfterMethod
public void tearDown()
{
driver.quit();
}
}
Image of error:
Code
Your static instance of WebDriver remain uninitialized. You need to initialize static instance instead of local driver instance in initialization() method. Like Below:
public class testBasesetup {
public static Properties prop;
public static WebDriver driver;
public static testBasesetup testBaseObj;
public static EventFiringWebDriver e_driver;
public testBasesetup() throws Exception
{
try {
prop = new Properties();
File src = new File("C:\\Users\\LENOVO\\eclipse-workspace\\Demon\\src\\main\\java\\Config\\config.properties");
FileInputStream ip = new FileInputStream(src) ;
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization() throws Exception
{
String browsername = prop.getProperty("browser");
if(browsername.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", "F:\\Eclipse\\chromedriver.exe");
**driver = new ChromeDriver();**
}
else if(browsername.equals("firefox"))
{
System.setProperty("webdriver.gecko.driver", "F:\\Eclipse\\browser\\geckodriver.exe");
**driver = new FirefoxDriver();**
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
String URLtoTest = prop.getProperty("URL");
Thread.sleep(1000);
}
}

In prepareStatement string value is not setting in its placeholder. help me to sort out this?

This is my code and see the error help me. in this code i am trying to get username and password from table student1. by using preparedStatement but i am getting an error .
package jdbcMY;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class demo {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Connection con = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/abhi", "root", "root");
String sql = "select * from student1 where username = ? ";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "abhi");
ResultSet rs = ps.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
More details:
here is the table i created in mysql
here is the error that i got

Null Pointer Exception when using Apache POI

I am trying to input the values to excel from web, having 2 columns and 9 rows, so that I will get the price and the description of 10 products from the web.
but Iam getting the Null pointer exception. Please any one help me out in clearing this error.
package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//import org.apache.commons.io.FileUtils;
//import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
//import org.openqa.selenium.OutputType;
//import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class A1 {
public static void main(String[] args) throws InterruptedException, ParseException, IOException, EncryptedDocumentException, InvalidFormatException
{
System.out.println("selenium");
WebDriver webdriver = new FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get("http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
int linkcnt = alllinks.size();
System.out.println("total links=" +linkcnt);
Actions action = new Actions(webdriver);
WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
action.moveToElement(COG).build().perform();
Thread.sleep(5000);
EHD.click();
webdriver.findElement(By.xpath("//label[#for='Capacity_s-1 TB']")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("(//span[#class='price-collapse-arrow'])[1]/..")).click();
WebElement totalitems = webdriver.findElement(By.xpath("//span[#class='category-count']"));
String totalitemsvalue=totalitems.getText();
System.out.println(totalitemsvalue);
String value=totalitemsvalue.replaceAll(" Items","");
System.out.println(value);
try{
List<WebElement> productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[#class='product-desc-rating title-section-collapse']"));
int count=productprice.size();
int count1=productTitle.size();
System.out.println(count);
System.out.println(count1);
//int i=9;
// int j=9;
Thread.sleep(2000);
for (count=0;count<10;count++)
{
productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
// File srcfile=((TakesScreenshot)webdriver).getScreenshotAs(OutputType.FILE);
// FileUtils.copyFile(srcfile, new File("c:\\screenshot.png"));
Thread.sleep(2000);
String RupeesValue= productprice.get(count).getText();
System.out.println(RupeesValue);
Thread.sleep(2000);
productTitle = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[1]"));
Thread.sleep(2000);
String TitleValue= productTitle.get(count1).getText();
System.out.println(TitleValue);
Thread.sleep(2000);
FileInputStream fis = new FileInputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheet("Sheet1");
// Sheet sheet1 = wb.getSheet("Sheet1");
for (int i=0;i<2;i++)
{
Row row=sheet.getRow(count);
// Row row1=sheet.getRow(j);
Cell cell = row.createCell(count);
// Cell cell1 = row1.createCell(count1);
cell.setCellType(cell.CELL_TYPE_STRING);
//cell1.setCellType(cell1.CELL_TYPE_STRING);
if(i==0){
cell.setCellValue(productprice.get(count).getText());
}
else
{
cell.setCellValue(productTitle.get(count).getText());
}
//cell1.setCellValue(productTitle.get(count1).getText());
FileOutputStream fos=new FileOutputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
wb.write(fos);
fos.close();
wb.close();
}
}
} catch(Exception e){
e.printStackTrace();
}
}
}
exception which am getting is :
Exception in thread "main" java.lang.NullPointerException
at samples.learningold.main(learningold.java:97)
First of all your ProductTitle Xpath is not fetching all the product names from the list. I have updated that too.
Following code works well.
package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class X
{
#SuppressWarnings("resource")
public static void main(String[] args) throws InterruptedException, ParseException, IOException, EncryptedDocumentException, InvalidFormatException
{
System.out.println("selenium");
WebDriver webdriver = new FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get("http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
int linkcnt = alllinks.size();
System.out.println("total links=" +linkcnt);
Actions action = new Actions(webdriver);
WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
action.moveToElement(COG).build().perform();
Thread.sleep(5000);
EHD.click();
webdriver.findElement(By.xpath("//label[#for='Capacity_s-1 TB']")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("(//span[#class='price-collapse-arrow'])[1]/..")).click();
Thread.sleep(5000);
WebElement totalitems = webdriver.findElement(By.xpath("//span[#class='category-count']"));
String totalitemsvalue=totalitems.getText();
System.out.println(totalitemsvalue);
String value=totalitemsvalue.replaceAll(" Items","");
System.out.println(value);
try
{
List<WebElement> productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[1]"));
int count=productprice.size();
int count1=productTitle.size();
System.out.println(count);
System.out.println(count1);
String[] productPriceList = new String[count];
String[] productTitleList = new String[count];
Thread.sleep(2000);
for(int k =0; k<count; k++)
{
System.out.println(productprice.get(k).getText());
productPriceList[k]=productprice.get(k).getText();
System.out.println(productTitle.get(k).getText());
productTitleList[k]=productTitle.get(k).getText();
}
File file= new File("C:\\Users\\XX\\Downloads\\snapdeal.xlsx"); // give your file path
FileInputStream inputStream = new FileInputStream(file);
Workbook sampleWorkbook=null;
sampleWorkbook=new XSSFWorkbook(inputStream);
Sheet sheet = sampleWorkbook.getSheet("Sheet1");
for(int t=0;t<count;t++)
{
Row row = sheet.createRow(t);
Cell cell = row.createCell(0); // create column 1
cell.setCellValue(productPriceList[t].toString());
Cell cell1 = row.createCell(1); // create column 2
cell1.setCellValue(productTitleList[t].toString());
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(file);
sampleWorkbook.write(outputStream);
System.out.println("Data written to Excel successful");
outputStream.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

ArrayIndexOutOfBoundsException error when writing to a tag

I followed a tutorial on how to write a NDEF message to a tag. and now when I run it. it detects the tag and when I press the button to write the message and the app crashes. it gives me JAVA.LANG.ArrayIndexOutOfBoundsException can someone please help me on what I'm doing wrong.
this is the error I see in logcat.
any help is appreciated.
Here is the code:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class WriteMessage extends Activity {
NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
boolean writeMode;
Tag myTag;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_message);
ctx=this;
Button WriteTag = (Button) findViewById (R.id.WriteTag);
final TextView Message = (TextView) findViewById (R.id.MessageBox);
WriteTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(myTag==null){
Toast.makeText(ctx, "Error_detected", Toast.LENGTH_LONG).show();
}else{
write(Message.getText().toString(), myTag);
Toast.makeText(ctx, "Ok_Writing", Toast.LENGTH_LONG).show();
}
}catch(IOException e){
Toast.makeText(ctx, "Error_Writing", Toast.LENGTH_LONG).show();
e.printStackTrace();
//} catch(FormatException e){
e.printStackTrace();
} catch (FormatException e) {
// TODO Auto-generated catch block
Toast.makeText(ctx, "Error_Writing", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent (this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter (NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] {tagDetected };
}
private void write(String text, Tag myTag)throws IOException, FormatException {
NdefRecord[] records = {createRecord(text)};
NdefMessage message = new NdefMessage(records);
Ndef ndef = Ndef.get(myTag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
}
private NdefRecord createRecord (String text ) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte [1+ langLength + textLength ];
payload[0] = (byte) langLength;
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(langBytes, 0, payload, 1 + langLength, textLength);
NdefRecord recordNFC = new NdefRecord (NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
return recordNFC;
}
#Override
protected void onNewIntent(Intent intent){
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(this, "ok_detection" + myTag.toString(), Toast.LENGTH_LONG ).show();
}
}
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
private void WriteModeOn(){
writeMode = true;
adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
private void WriteModeOff(){
writeMode = false;
adapter.disableForegroundDispatch(this);
}
}
Looks like createRecord() is copying langBytes into payload twice instead of copying textBytes, but with the length of textBytes. If textBytes is longer than langBytes, it won't find enough data to copy from the source.
See the documentation on arraycopy.

Resources