How to set typeface from ExternalStorage and multi font - environment

I've created a list of fonts in ExternalStorageDirectory and I'm saving it to :
ArrayList<String> list = new ArrayList<String>();
How do I set the typeface in textView from fonts to myFolder?
This code only sets typeface to one font in a directory
String root_sd = Environment.getExternalStorageDirectory().toString();
File name = new File(root_sd + "/myFolder/");
File[] files = name.listFiles();
for (int i = 0; i < files.length; i++){
Typeface typeface = Typeface.createFromFile(files[i].getPath());
textView.setTypeface(typeface);
textView.setTextSize(20);
}

This is the sample for using 3 different typeface in 3 different textView based on your code. You can try this instead of removing the loop.
String root_sd = Environment.getExternalStorageDirectory().toString();
File name = new File(root_sd + "/myFolder/");
File[] files = name.listFiles();
Typeface typeface = Typeface.createFromFile(files[0].getPath());
textView.setTypeface(typeface);
textView.setTextSize(20);
Typeface typeface2 = Typeface.createFromFile(files[1].getPath());
textView2.setTypeface(typeface2);
textView2.setTextSize(20);
Typeface typeface3 = Typeface.createFromFile(files[2].getPath());
textView3.setTypeface(typeface3);
textView3.setTextSize(20);

i'm set list of fonts With code :
public static ArrayList<String> getPersianFonts(Context context) {
ArrayList<String> list = new ArrayList<String>();
try {
String root_sd = Environment.getExternalStorageDirectory().toString();
File name = new File(root_sd + "/myFolder/");
File[] files = name.listFiles();
for (int i = 0; i < files.length; i++){
list.add( files[i].getName() );
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
Now have get typeface from list and set to textView??

Related

How to keep the hyperlink in an pdf merge in ITextSharp? [duplicate]

How to merge multiple pdf files (generated on run time) through ItextSharp then printing them.
I found the following link but that method requires the pdf names considering that the pdf files stored and this is not my case .
I have multiple reports i'll convert them to pdf files through this method :
private void AddReportToResponse(LocalReport followsReport)
{
string mimeType;
string encoding;
string extension;
string[] streams = new string[100];
Warning[] warnings = new Warning[100];
byte[] pdfStream = followsReport.Render("PDF", "", out mimeType, out encoding, out extension, out streams, out warnings);
//Response.Clear();
//Response.ContentType = mimeType;
//Response.AddHeader("content-disposition", "attachment; filename=Application." + extension);
//Response.BinaryWrite(pdfStream);
//Response.End();
}
Now i want to merge all those generated files (Bytes) in one pdf file to print it
If you want to merge source documents using iText(Sharp), there are two basic situations:
You really want to merge the documents, acquiring the pages in their original format, transfering as much of their content and their interactive annotations as possible. In this case you should use a solution based on a member of the Pdf*Copy* family of classes.
You actually want to integrate pages from the source documents into a new document but want the new document to govern the general format and don't care for the interactive features (annotations...) in the original documents (or even want to get rid of them). In this case you should use a solution based on the PdfWriter class.
You can find details in chapter 6 (especially section 6.4) of iText in Action — 2nd Edition. The Java sample code can be accessed here and the C#'ified versions here.
A simple sample using PdfCopy is Concatenate.java / Concatenate.cs. The central piece of code is:
byte[] mergedPdf = null;
using (MemoryStream ms = new MemoryStream())
{
using (Document document = new Document())
{
using (PdfCopy copy = new PdfCopy(document, ms))
{
document.Open();
for (int i = 0; i < pdf.Count; ++i)
{
PdfReader reader = new PdfReader(pdf[i]);
// loop over the pages in that document
int n = reader.NumberOfPages;
for (int page = 0; page < n; )
{
copy.AddPage(copy.GetImportedPage(reader, ++page));
}
}
}
}
mergedPdf = ms.ToArray();
}
Here pdf can either be defined as a List<byte[]> immediately containing the source documents (appropriate for your use case of merging intermediate in-memory documents) or as a List<String> containing the names of source document files (appropriate if you merge documents from disk).
An overview at the end of the referenced chapter summarizes the usage of the classes mentioned:
PdfCopy: Copies pages from one or more existing PDF documents. Major downsides: PdfCopy doesn’t detect redundant content, and it fails when concatenating forms.
PdfCopyFields: Puts the fields of the different forms into one form. Can be used to avoid the problems encountered with form fields when concatenating forms using PdfCopy. Memory use can be an issue.
PdfSmartCopy: Copies pages from one or more existing PDF documents. PdfSmartCopy is able to detect redundant content, but it needs more memory and CPU than PdfCopy.
PdfWriter: Generates PDF documents from scratch. Can import pages from other PDF documents. The major downside is that all interactive features of the imported page (annotations, bookmarks, fields, and so forth) are lost in the process.
I used iTextsharp with c# to combine pdf files. This is the code I used.
string[] lstFiles=new string[3];
lstFiles[0]=#"C:/pdf/1.pdf";
lstFiles[1]=#"C:/pdf/2.pdf";
lstFiles[2]=#"C:/pdf/3.pdf";
PdfReader reader = null;
Document sourceDocument = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage;
string outputPdfPath=#"C:/pdf/new.pdf";
sourceDocument = new Document();
pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
//Open the output file
sourceDocument.Open();
try
{
//Loop through the files list
for (int f = 0; f < lstFiles.Length-1; f++)
{
int pages =get_pageCcount(lstFiles[f]);
reader = new PdfReader(lstFiles[f]);
//Add pages of current file
for (int i = 1; i <= pages; i++)
{
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
}
reader.Close();
}
//At the end save the output file
sourceDocument.Close();
}
catch (Exception ex)
{
throw ex;
}
private int get_pageCcount(string file)
{
using (StreamReader sr = new StreamReader(File.OpenRead(file)))
{
Regex regex = new Regex(#"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
Here is some code I pulled out of an old project I had. It was a web application but I was using iTextSharp to merge pdf files then print them.
public static class PdfMerger
{
/// <summary>
/// Merge pdf files.
/// </summary>
/// <param name="sourceFiles">PDF files being merged.</param>
/// <returns></returns>
public static byte[] MergeFiles(List<Stream> sourceFiles)
{
Document document = new Document();
MemoryStream output = new MemoryStream();
try
{
// Initialize pdf writer
PdfWriter writer = PdfWriter.GetInstance(document, output);
writer.PageEvent = new PdfPageEvents();
// Open document to write
document.Open();
PdfContentByte content = writer.DirectContent;
// Iterate through all pdf documents
for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
{
// Create pdf reader
PdfReader reader = new PdfReader(sourceFiles[fileCounter]);
int numberOfPages = reader.NumberOfPages;
// Iterate through all pages
for (int currentPageIndex = 1; currentPageIndex <=
numberOfPages; currentPageIndex++)
{
// Determine page size for the current page
document.SetPageSize(
reader.GetPageSizeWithRotation(currentPageIndex));
// Create page
document.NewPage();
PdfImportedPage importedPage =
writer.GetImportedPage(reader, currentPageIndex);
// Determine page orientation
int pageOrientation = reader.GetPageRotation(currentPageIndex);
if ((pageOrientation == 90) || (pageOrientation == 270))
{
content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0,
reader.GetPageSizeWithRotation(currentPageIndex).Height);
}
else
{
content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception exception)
{
throw new Exception("There has an unexpected exception" +
" occured during the pdf merging process.", exception);
}
finally
{
document.Close();
}
return output.GetBuffer();
}
}
/// <summary>
/// Implements custom page events.
/// </summary>
internal class PdfPageEvents : IPdfPageEvent
{
#region members
private BaseFont _baseFont = null;
private PdfContentByte _content;
#endregion
#region IPdfPageEvent Members
public void OnOpenDocument(PdfWriter writer, Document document)
{
_baseFont = BaseFont.CreateFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
_content = writer.DirectContent;
}
public void OnStartPage(PdfWriter writer, Document document)
{ }
public void OnEndPage(PdfWriter writer, Document document)
{ }
public void OnCloseDocument(PdfWriter writer, Document document)
{ }
public void OnParagraph(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnParagraphEnd(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnChapter(PdfWriter writer, Document document,
float paragraphPosition, Paragraph title)
{ }
public void OnChapterEnd(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnSection(PdfWriter writer, Document document,
float paragraphPosition, int depth, Paragraph title)
{ }
public void OnSectionEnd(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnGenericTag(PdfWriter writer, Document document,
Rectangle rect, string text)
{ }
#endregion
private float GetCenterTextPosition(string text, PdfWriter writer)
{
return writer.PageSize.Width / 2 - _baseFont.GetWidthPoint(text, 8) / 2;
}
}
I didn't write this, but made some modifications. I can't remember where I found it. After I merged the PDFs I would call this method to insert javascript to open the print dialog when the PDF is opened. If you change bSilent to true then it should print silently to their default printer.
public Stream addPrintJStoPDF(Stream thePDF)
{
MemoryStream outPutStream = null;
PRStream finalStream = null;
PdfDictionary page = null;
string content = null;
//Open the stream with iTextSharp
var reader = new PdfReader(thePDF);
outPutStream = new MemoryStream(finalStream.GetBytes());
var stamper = new PdfStamper(reader, (MemoryStream)outPutStream);
var jsText = "var res = app.setTimeOut('this.print({bUI: true, bSilent: false, bShrinkToFit: false});', 200);";
//Add the javascript to the PDF
stamper.JavaScript = jsText;
stamper.FormFlattening = true;
stamper.Writer.CloseStream = false;
stamper.Close();
//Set the stream to the beginning
outPutStream.Position = 0;
return outPutStream;
}
Not sure how well the above code is written since I pulled it from somewhere else and I haven't worked in depth at all with iTextSharp but I do know that it did work at merging PDFs that I was generating at runtime.
Tested with iTextSharp-LGPL 4.1.6:
public static byte[] ConcatenatePdfs(IEnumerable<byte[]> documents)
{
using (var ms = new MemoryStream())
{
var outputDocument = new Document();
var writer = new PdfCopy(outputDocument, ms);
outputDocument.Open();
foreach (var doc in documents)
{
var reader = new PdfReader(doc);
for (var i = 1; i <= reader.NumberOfPages; i++)
{
writer.AddPage(writer.GetImportedPage(reader, i));
}
writer.FreeReader(reader);
reader.Close();
}
writer.Close();
outputDocument.Close();
var allPagesContent = ms.GetBuffer();
ms.Flush();
return allPagesContent;
}
}
To avoid the memory issues mentioned, I used file stream instead of memory stream(mentioned in ITextSharp Out of memory exception merging multiple pdf) to merge pdf files:
var parentDirectory = Directory.GetParent(SelectedDocuments[0].FilePath);
var savePath = parentDirectory + "\\MergedDocument.pdf";
using (var fs = new FileStream(savePath, FileMode.Create))
{
using (var document = new Document())
{
using (var pdfCopy = new PdfCopy(document, fs))
{
document.Open();
for (var i = 0; i < SelectedDocuments.Count; i++)
{
using (var pdfReader = new PdfReader(SelectedDocuments[i].FilePath))
{
for (var page = 0; page < pdfReader.NumberOfPages;)
{
pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, ++page));
}
}
}
}
}
}
****/*For Multiple PDF Print..!!*/****
<button type="button" id="btnPrintMultiplePdf" runat="server" class="btn btn-primary btn-border btn-sm"
onserverclick="btnPrintMultiplePdf_click">
<i class="fa fa-file-pdf-o"></i>Print Multiple pdf</button>
protected void btnPrintMultiplePdf_click(object sender, EventArgs e)
{
if (ValidateForMultiplePDF() == true)
{
#region Declare Temp Variables..!!
CheckBox chkList = new CheckBox();
HiddenField HidNo = new HiddenField();
string Multi_fofile, Multi_listfile;
Multi_fofile = Multi_listfile = "";
Multi_fofile = Server.MapPath("PDFRNew");
#endregion
for (int i = 0; i < grdRnew.Rows.Count; i++)
{
#region Find Grd Controls..!!
CheckBox Chk_One = (CheckBox)grdRnew.Rows[i].FindControl("chkOne");
Label lbl_Year = (Label)grdRnew.Rows[i].FindControl("lblYear");
Label lbl_No = (Label)grdRnew.Rows[i].FindControl("lblCode");
#endregion
if (Chk_One.Checked == true)
{
HidNo .Value = llbl_No .Text.Trim()+ lbl_Year .Text;
if (File.Exists(Multi_fofile + "\\" + HidNo.Value.ToString() + ".pdf"))
{
#region Get Multiple Files Name And Paths..!!
if (Multi_listfile != "")
{
Multi_listfile = Multi_listfile + ",";
}
Multi_listfile = Multi_listfile + Multi_fofile + "\\" + HidNo.Value.ToString() + ".pdf";
#endregion
}
}
}
#region For Generate Multiple Pdf..!!
if (Multi_listfile != "")
{
String[] Multifiles = Multi_listfile.Split(',');
string DestinationFile = Server.MapPath("PDFRNew") + "\\Multiple.Pdf";
MergeFiles(DestinationFile, Multifiles);
Response.ContentType = "pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + DestinationFile + "\"");
Response.TransmitFile(DestinationFile);
Response.End();
}
else
{
}
#endregion
}
}
private void MergeFiles(string DestinationFile, string[] SourceFiles)
{
try
{
int f = 0;
/**we create a reader for a certain Document**/
PdfReader reader = new PdfReader(SourceFiles[f]);
/**we retrieve the total number of pages**/
int n = reader.NumberOfPages;
/**Console.WriteLine("There are " + n + " pages in the original file.")**/
/**Step 1: creation of a document-object**/
Document document = new Document(reader.GetPageSizeWithRotation(1));
/**Step 2: we create a writer that listens to the Document**/
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(DestinationFile, FileMode.Create));
/**Step 3: we open the Document**/
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
/**Step 4: We Add Content**/
while (f < SourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
/**Console.WriteLine("Processed page " + i)**/
}
f++;
if (f < SourceFiles.Length)
{
reader = new PdfReader(SourceFiles[f]);
/**we retrieve the total number of pages**/
n = reader.NumberOfPages;
/**Console.WriteLine("There are"+n+"pages in the original file.")**/
}
}
/**Step 5: we Close the Document**/
document.Close();
}
catch (Exception e)
{
string strOb = e.Message;
}
}
private bool ValidateForMultiplePDF()
{
bool chkList = false;
foreach (GridViewRow gvr in grdRnew.Rows)
{
CheckBox Chk_One = (CheckBox)gvr.FindControl("ChkSelectOne");
if (Chk_One.Checked == true)
{
chkList = true;
}
}
if (chkList == false)
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Check At Least On CheckBox.";
grdRnew.Focus();
set_timeout();
return false;
}
return true;
}

error in generating pdf using iTextSharp

this is my controller class:-
public class PlantHeadController : Controller
{
private WOMSEntities2 db = new WOMSEntities2();
//
// GET: /PlantHead/
Document doc = new Document();
static String[] tt=new String[20];
public ActionResult Index()
{
ViewBag.productCode = new SelectList(db.Product, "ID","code");
return View();
}
public void Convert()
{
PdfWriter.GetInstance(doc, new
FileStream((Request.PhysicalApplicationPath + "\\Receipt3.pdf"),
FileMode.Create));
doc.Open();
PdfPTable table = new PdfPTable(2);
doc.AddCreationDate();
PdfPCell cell = new PdfPCell(new Phrase("Receipt"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("ahym");
table.AddCell("ram";
table.AddCell("good");
table.AddCell("morning");
String rawGroup = "";
foreach (String lll in raw)
rawGroup = rawGroup + lll+" ";
table.AddCell("" + rawGroup);
doc.Add(table);
doc.Close();
Response.Redirect("~/Receipt3.pdf");
}
}
whenever i press submit button to make pdf file then this error window is opened:-
means pdf is not generated successfully. in some cases old pdf is shown. please suggest me what should i do?
Everything looks good for the most part above (except a missing parenthesis on table.AddCell("ram"; which I assume is just a typo and you could also do with some using statements). I don't know why you would get an error but the reason that you're getting the same PDF is almost definitely because of browser caching. You could append a random querystring to the file but I'd recommend instead skipping the file completely and writing the binary stream directly. This way you can control the caching and you don't have to work about browser redirection. The below code should work for you (its targeting 5.1.1.0 depending on your version you may or may not be able to use some of the using statements).
EDIT
I donwgraded my code to not use the IDisposable interfaces found in newer versions, this should work for you now. (I don't have access to a C# compiler so I didn't test it so hopefully this works.)
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document());
PdfWriter writer = PdfWriter.GetInstance(doc, ms));
doc.Open();
doc.AddCreationDate();
PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell(new Phrase("Receipt"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("ahym");
table.AddCell("ram");
table.AddCell("good");
table.AddCell("morning");
String rawGroup = "";
foreach (String lll in raw)
{
rawGroup = rawGroup + lll + " ";
}
table.AddCell("" + rawGroup);
doc.Add(table);
doc.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Receipt3.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(ms.ToArray());
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
}

RichTextEdit with multicolored text?

How do I create a RichTextEdit using RIM 4.5 API that contains text with multiple colors?
For example I want to create a RichTextEdit as follows:
The Text is "Hello BB world"
"Hello" should be blue
"BB world" should be red
"BB" should be ITALIC
"Hello" should be BOLD
The main problem is getting colors, not the bold and italic.
I have tried overriding RichTextEdit.paint function, but this formats the color of the whole string, not just a substring of it!
Here's the code I implemented to make the text bold and italic and overriding the paint to change the whole string color:
public final class RichTextFieldSample extends UiApplication
{
public static void main(String[] args)
{
RichTextFieldSample theApp = new RichTextFieldSample();
theApp.enterEventDispatcher();
}
public RichTextFieldSample()
{
String richText = "This is how you create text with formatting!!!";
Font fonts[] = new Font[3];
int[] offset = new int[4];
byte[] attribute = new byte[3];
fonts[0] = Font.getDefault();
fonts[1] = Font.getDefault().derive(Font.BOLD);
fonts[2] = Font.getDefault().derive(Font.BOLD | Font.ITALIC);
offset[0] = 0;
attribute[0] = 2;
offset[1] = 4;
attribute[1] = 0;
offset[2] = 33;
attribute[2] = 1;
offset[3] = richText.length();
RichTextField rtField = new RichTextField
(richText, offset, attribute, fonts,
RichTextField.USE_TEXT_WIDTH) {
protected void paint(Graphics graphics) {
graphics.clear();
graphics.setColor(0x0000FF);
super.paint(graphics);
}
};
MainScreen mainScreen = new MainScreen();
mainScreen.setTitle(new LabelField
("RichTextFieldSample Sample",
LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH));
mainScreen.add(rtField);
pushScreen(mainScreen);
}
}
Unfortunately no easy answer to this one. According to this post, RichTextField doesn't support multiple colors (despite the presence of a getForegroundColors method).
It may be possible to extend RichTextField to support multiple colors, but with the amount of work necessary, it would very likely be easier to implement your own Field from scratch.

Blackberry - How to get Field Labels from PIMItem

How can we get Field Labels from PIMItem. The following code is with PIMList
String label = pimList.getAttributeLabel(
blackBerryContact.getAttributes(Contact.TEL, i));
But i have PIMItem. There is a method PIMItem.getPIMList() which returns null for me in the code below. THE API at http://www.blackberry.com/developers/docs/5.0.0api/index.html says "getPIMList()
Gets the PIMList associated with this item." Below is sample code that i am trying to achive -
// Load the address Book and allow the user to select a contact
BlackBerryContactList contactList = (BlackBerryContactList)
PIM.getInstance().openPIMList(PIM.CONTACT_LIST,PIM.READ_ONLY);
PIMItem userSelectedContact = contactList.choose();
// Now get the Field labels for contact numbers for userSelectedContact
class Scr extends MainScreen {
Scr() {
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("add label", 1, 1){public void run() {
try {
BlackBerryContactList contactList =
(BlackBerryContactList) PIM.getInstance().openPIMList(
PIM.CONTACT_LIST, PIM.READ_ONLY);
BlackBerryContact contact =
(BlackBerryContact) contactList.choose();
add(new LabelField(getContactInfo(contact)));
} catch (PIMException e) {
e.printStackTrace();
}
}});
}
String getContactInfo(BlackBerryContact c) {
StringBuffer result = new StringBuffer();
result.append("Name: ");
result.append(c.getStringArray(
BlackBerryContact.NAME, 0)[BlackBerryContact.NAME_GIVEN]);
result.append(" ");
result.append(c.getStringArray(
BlackBerryContact.NAME, 0)[BlackBerryContact.NAME_FAMILY]);
result.append("Email: ");
result.append("\n");
result.append(c.getString(
BlackBerryContact.EMAIL, BlackBerryContact.ATTR_NONE));
return result.toString();
}
}
Thanks Max for the response. The returning NULL issue was problem with my code which i have rectified. I was also able to get Labels for Fields, but the loop retrieves only fields that the Contact has on his card.
I am looking to get all the 8 labels that Contact.TEL has -
Int maxAllowed = contactList.maxValues(Contact.TEL); // Gives me 8
All the 8 Labels might not be in use in for a user, For e.g a user might have WORK, WORK2, HOME, HOME2 and MOBILE. Others FAX, PAGER and OTHER might not be filled i want to get all the allowed labels and update a given number for the one that is empty.
How can we check and update the following
Contact.ATTR_PAGER, Contact.ATTR_FAX, Contact.ATTR_OTHER
Please let me know if the explanation is not clear, or some more details are required.
BlackBerryContactList contactList = (BlackBerryContactList)
PIM.getInstance().openPIMList(PIM.CONTACT_LIST,PIM.READ_WRITE);
PIMItem pimItem = contactList.choose();
BlackBerryContact blackBerryContact = (BlackBerryContact)pimItem;
PIMList pimList = blackBerryContact.getPIMList();
// To get Labels
int phoneCount = blackBerryContact.countValues(BlackBerryContact.TEL);
String[] phoneNumbers = new String[phoneCount];
String[] labels = new String[phoneCount];
for (int i = 0; i > phoneCount; i++) {
String phoneNumber = blackBerryContact.getString(Contact.TEL, i);
String label = pimList.getAttributeLabel(
blackBerryContact.getAttributes(Contact.TEL, i));
//Add the number and label to the array.
phoneNumbers[i] = phoneNumber;
labels[i] = label + ":" + phoneNumber;
}

Using streamreader to read line containing this "//"?

Read a Text file having any line starts from "//" omit this line and moved to next line.
The Input text file having some seprate partitions. Find line by line process and this mark.
If you are using .Net 3.5 you can use LINQ with a IEnumerable wrapped around a Stream Reader. This cool part if then you can just use a where statement to file statmens or better yet use a select with a regular expression to just trim the comment and leave data on the same line.
//.Net 3.5
static class Program
{
static void Main(string[] args)
{
var clean = from line in args[0].ReadAsLines()
let trimmed = line.Trim()
where !trimmed.StartsWith("//")
select line;
}
static IEnumerable<string> ReadAsLines(this string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
...
//.Net 2.0
static class Program
{
static void Main(string[] args)
{
var clean = FilteredLines(args[0]);
}
static IEnumerable<string> FilteredLines(string filename)
{
foreach (var line in ReadAsLines(filename))
if (line.TrimStart().StartsWith("//"))
yield return line;
}
static IEnumerable<string> ReadAsLines(string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
I'm not sure what you exactly need but, if you just want to filter out // lines from some text in a stream... just remember to close the stream after using it.
public string FilterComments(System.IO.Stream stream)
{
var data = new System.Text.StringBuilder();
using (var reader = new System.IO.StreamReader(stream))
{
var line = string.Empty;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
if (!line.TrimStart(' ').StartsWith("//"))
{
data.Append(line);
}
}
}
return data.ToString();
}
Class SplLineIgnorStrmReader:StreamReader // derived class from StreamReader
SplLineIgnorStrmReader ConverterDefFileReadStream = null;
{
//created the Obj for this Class.
Obj = new SplLineIgnorStrmReader(strFile, Encoding.default);
}
public override string ReadLine()
{
string strLineText = "", strTemp;
while (!EndOfStream)
{
strLineText = base.ReadLine();
strLineText = strLineText.TrimStart(' ');
strLineText = strLineText.TrimEnd(' ');
strTemp = strLineText.Substring(0, 2);
if (strTemp == "//")
continue;
break;
}
return strLineText;
This is if u want to read the Text file and omit any comments from that file(here exclude "//" comment).

Resources