delimiter issue while reading from csv to sqlite - android

I tried every search on the net but couldn't managed to find a solution. I have managed to create a csv file(as attached in the image). But while importing it to sqlite whatever I do I can't have the correct rows in the correct positions in my sqlite, I believe it's about delimiters but couldn't find out can you help me please, I'm looking for it for the last 2 days. thank you
File exportDir = new File(Environment.getExternalStorageDirectory(), "/XXX/");
if (!exportDir.exists()) { exportDir.mkdirs(); }
File file2 = new File(exportDir, "XXX.csv");
FileReader file = new FileReader(file2);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues=new ContentValues();
String line = "";
String tableName =WordListOpenHelper.MY_LIST_TABLE;
db.beginTransaction();
while ((line = buffer.readLine()) != null)
{
x++;
String[] str = line.split("\\+");
if (x>5) {
contentValues.put(Contract.WordList.KEY_ENTRY, str[0]);
contentValues.put(Contract.WordList.KEY_NICKNAME_DATE, str[1]);
contentValues.put(Contract.WordList.KEY_LOCATION, str[2]);
contentValues.put(Contract.WordList.KEY_LOCATION_IMAGE, str[3]);
contentValues.put(Contract.WordList.KEY_HEART, str[4]);
db.insert(tableName, null, contentValues);
}
}
db.setTransactionSuccessful();
db.endTransaction();
And CSVWriter class
public class CSVWriter {
private PrintWriter pw;
private String separator;
private char escapechar;
private String lineEnd;
private char quotechar;
public static final String DEFAULT_SEPARATOR = "+\n";
public static final char NO_QUOTE_CHARACTER = '\u0000';
public static final char NO_ESCAPE_CHARACTER = '\u0000';
public static final String DEFAULT_LINE_END = "+\n";
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final char DEFAULT_ESCAPE_CHARACTER = ' ';
public CSVWriter(Writer writer) {
this(writer, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END);
}
public CSVWriter(Writer writer, String separator, char quotechar, char escapechar, String lineEnd) {
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
public void writeNext(String[] nextLine) {
try{
if (nextLine == null)
return;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nextLine.length; i++) {
if (i != 0) {
sb.append(separator);
}
String nextElement = nextLine[i];
if (nextElement == null)
continue;
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
for (int j = 0; j < nextElement.length(); j++) {
char nextChar = nextElement.charAt(j);
if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
sb.append(escapechar).append(nextChar);
} else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
sb.append(escapechar).append(nextChar);
} else {
sb.append(nextChar);
}
}
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
}
sb.append(lineEnd);
pw.write(sb.toString());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void close() throws IOException {
pw.flush();
pw.close();
}
public void flush() throws IOException {
pw.flush();
}
}
CSV file in file manager:

This is not exactly a csv file, so it needs special dealing.
Use this method:
public String getLine(String line) {
line = line.trim();
if (line.isEmpty())
return "";
if (line.equals("\"\"+"))
return "";
if (line.length() <= 3)
return "";
return line.substring(1, line.length() - 1);
}
and this instead of your while loop:
boolean noMoreLines = false;
for (int i = 1; i <= 5; i++) {
line = buffer.readLine();
if (line == null) {
noMoreLines = true;
break;
}
}
if (!noMoreLines) {
while ((line = buffer.readLine()) != null) {
contentValues.put(Contract.WordList.KEY_ENTRY, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_NICKNAME_DATE, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_LOCATION, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_LOCATION_IMAGE, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_HEART, getLine(line));
db.insert(tableName, null, contentValues);
}
}

Related

Android SDK AsyncTask doInBackground not running

plz help me
I did added async library at my project and checked already, I don't know why code flow doesn't go in to asynctask
my Update code doesn't execute.
in this line my update calss doesnt run
dataupdate.execute();
CODE:
public class Update extends AsyncTask<Void, Void, Integer> {
private String User;
private final String mLink;
public Update(String user) {
User = user;
mLink = "http://www./Update.php";
}
#Override
protected Integer doInBackground(Void... params) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
}
return null;
}
}
Main:
showProgress(true);
dataupdate = new Update(username);
dataupdate.execute();
// dataupdate.execute((Void) null);
showProgress(false);
do it like this
public class Update extends AsyncTask<String, String, Integer> {
#Override
protected Integer doInBackground(String... params) {
User user=params[0]; //get string user value here
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(user, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
e.printstacktrace();
}
return null;
}
}
to run
//put username value in execute
new Update()execute(username);

Get path to the External SdCard in android

I want to get External SdCard path on devices if it available. by using Environment.getExternalStorageDirectory().getAbsolutePath() I can get the path to the Internal Storage. So I used below class for detecting External storage.
public class ExternalStorage {
public static final String SD_CARD = "sdCard";
public static final String EXTERNAL_SD_CARD = "externalSdCard";
/**
* #return True if the external storage is available. False otherwise.
*/
public static boolean isAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getSdCardPath() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
/**
* #return True if the external storage is writable. False otherwise.
*/
public static boolean isWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* #return A map of all storage locations available
*/
public static Map<String, File> getAllStorageLocations() {
Map<String, File> map = new HashMap<String, File>(10);
List<String> mMounts = new ArrayList<String>(10);
List<String> mVold = new ArrayList<String>(10);
mMounts.add("/mnt/sdcard");
mVold.add("/mnt/sdcard");
try {
File mountFile = new File("/proc/mounts");
if(mountFile.exists()){
Scanner scanner = new Scanner(mountFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
// don't add the default mount path
// it's already in the list.
if (!element.equals("/mnt/sdcard"))
mMounts.add(element);
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
try {
File voldFile = new File("/system/etc/vold.fstab");
if(voldFile.exists()){
Scanner scanner = new Scanner(voldFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (!element.equals("/mnt/sdcard"))
mVold.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
if (!mVold.contains(mount))
mMounts.remove(i--);
}
mVold.clear();
List<String> mountHash = new ArrayList<String>(10);
for(String mount : mMounts){
File root = new File(mount);
if (root.exists() && root.isDirectory() && root.canWrite()) {
File[] list = root.listFiles();
String hash = "[";
if(list!=null){
for(File f : list){
hash += f.getName().hashCode()+":"+f.length()+", ";
}
}
hash += "]";
if(!mountHash.contains(hash)){
String key = SD_CARD + "_" + map.size();
if (map.size() == 0) {
key = SD_CARD;
} else if (map.size() == 1) {
key = EXTERNAL_SD_CARD;
}
mountHash.add(hash);
map.put(key, root);
}
}
}
mMounts.clear();
if(map.isEmpty()){
map.put(SD_CARD, Environment.getExternalStorageDirectory());
}
return map;
}
Example usage
Map <String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard=externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);
on some device like Samsung Galaxy S3 it detects External SdCard correctly and return /storage/extSdCard for path to the External SdCard but on other devices like Sony Experia Z1 and Z2 it can't detect External Sdcard and give me the path to the Internal Storage. How can I solve this problem?
Use below code in order to get sd card path
public class DiskHelper
{
public static final int MODE_INTERNAL = 0;
public static final int MODE_EXTERNAL = 1;
public static final int MODE_EXTERNAL_SD = 2;
private StatFs statFs;
protected String path;
public DiskHelper(int mode)
{
try
{
if(mode == 0)
{
path = Environment.getRootDirectory().getAbsolutePath();
statFs = new StatFs(path);
statFs.restat(path);
}
else if(mode == 1)
{
path = Environment.getExternalStorageDirectory().getAbsolutePath();
statFs = new StatFs(path);
statFs.restat(path);
}
else
{
for(String str : getExternalMounts())
{
path = str;
statFs = new StatFs(str);
statFs.restat(str);
break;
}
}
}
catch(Exception e)
{
KLog.error(e);
}
}
public String getPath()
{
return path;
}
public long getTotalMemory()
{
if(statFs == null)
{
return 0;
}
long total = ((long)statFs.getBlockCount() * (long)statFs.getBlockSize());
return total;
}
public long getFreeMemory()
{
if(statFs == null)
{
return 0;
}
long free = ((long)statFs.getAvailableBlocks() * (long)statFs.getBlockSize());
return free;
}
public long getBusyMemory()
{
if(statFs == null)
{
return 0;
}
long total = getTotalMemory();
long free = getFreeMemory();
long busy = total - free;
return busy;
}
public static HashSet<String> getExternalMounts()
{
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try
{
final Process process = new ProcessBuilder().command("mount").redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while(is.read(buffer) != -1)
{
s = s + new String(buffer);
}
is.close();
}
catch(Exception e)
{
KLog.error(e);
}
final String[] lines = s.split("\n");
for (String line : lines)
{
if(!line.toLowerCase(Locale.US).contains("asec"))
{
if(line.matches(reg))
{
String[] parts = line.split(" ");
for(String part : parts)
{
if(part.startsWith("/"))
{
if(!part.toLowerCase(Locale.US).contains("vold"))
{
out.add(part);
}
}
}
}
}
}
return out;
}
private static final long MEGABYTE = 1024L * 1024L;
public static String humanReadableByteCount(long bytes, boolean si)
{
if(true)
{
long ret = bytes / MEGABYTE;
return ret + " MB";
}
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
Then
final DiskHelper sdDiskHelper = new DiskHelper(DiskHelper.MODE_EXTERNAL_SD);
path = sdDiskHelper.getPath();
You can customize this class.
String secStore = System.getenv("SECONDARY_STORAGE");
File externalsdpath = new File(secStore);
This will get the path of external sd secondary storage.

Database insert data

I receive data in webservice and insert in sqlite database Android but if filed is empty repeat before filed As far as new filed no empty and repeat ...
please help me:
public class gfc extends AsyncTask {
private String Link = "";
private String Count = "";
private String tid = "";
private String tim = "";
private String tuser = "";
private String tusername = "";
private String tmatn = "";
private String tcomments = "";
private String tlikes = "";
private String tdate = "";
private String tip_addr = "";
private database db;
public gfc(String link, String count, Context c) {
Link = link;
Count = count;
db = new database(c);
}
#Override
protected String doInBackground(Object... arg0) {
try {
String data = URLEncoder.encode("count", "UTF8") + "=" + URLEncoder.encode(Count, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
db.open();
while ((line = reader.readLine()) != null) {
int f = 0;
int c = 0;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
String temp = line.substring(f, i);
if (c == 0) {
tid = temp;
}
if (c == 1) {
tdate = temp;
}
if (c == 2) {
tuser = temp;
}
if (c == 3) {
tusername = temp;
}
if (c == 4) {
tip_addr = temp;
}
if (c == 5) {
tcomments = temp;
}
if (c == 6) {
tlikes = temp;
}
if (c == 7) {
tim = temp;
}
if (c == 8) {
tmatn = temp.replace("^", "\n");
}
c += 1;
f = i + 1;
}
}
db.insert(tid, tuser, tusername, tmatn, tcomments, tlikes, tdate, tip_addr, tim);
sb.append("t");
}
db.close();
index.res = sb.toString();
} catch (Exception e) {}
return "";
}
}

CSV file Uploader to Array

I have created this code but don't know why its not working. The code doesn't print all lines of the csvfile.
try{
File csvfile = new File(FullPath);
FileInputStream csvStream = new FileInputStream(csvfile);
BufferedReader in = new BufferedReader(new InputStreamReader(csvStream));
String line;
int iCount=0;
while ((line = in.readLine()) != null){
String[] RowData = line.split(",");
name[iCount] = RowData[0];
Toast.makeText(NewMessage.this, "CSV", 2000).show();
number[iCount] = RowData[1];
iCount++;
}
in.close();
Toast.makeText(NewMessage.this, "CSV Has uploaded", 2000).show();
}
catch(Exception e)
{
e.printStackTrace();
}
If the problem is that is not printing all lines of the file, you are overriding the array on loop. You should edit your question, because the array is working, the really problem is that the file wasn't printing all lines.
Here's the solution for name,number format:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Teste {
public static void main(String[] args) throws IOException {
Teste x = new Teste();
x.doTeste();
}
public void doTeste() throws IOException{
String fileName = "D:\\Projetos\\Testes\\src\\teste.txt";
BufferedReader in = null;
try{
File csvfile = new File(fileName);
FileInputStream csvStream = new FileInputStream(csvfile);
in = new BufferedReader(new InputStreamReader(csvStream));
String line;
String[] rowName = new String[(countLines(fileName)+1)];
String[] rowNameData = new String[(countLines(fileName)+1)];
int linha = 0;
while ((line = in.readLine()) != null){
String[] array = line.split(",");
rowName[linha] = array[0];
rowNameData[linha] = array[1];
++linha;
}
System.out.println("The rowName ARRAY");
for (String s: rowName){
System.out.println(s);
}
System.out.println("The rowNameData ARRAY");
for (String s: rowNameData){
System.out.println(s);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
in.close();
}
}
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
}
and for name in one line, and number the next line:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Teste {
public static void main(String[] args) throws IOException {
Teste x = new Teste();
x.doTeste();
}
public void doTeste() throws IOException{
String fileName = "D:\\Projetos\\Testes\\src\\teste.txt";
BufferedReader in = null;
try{
File csvfile = new File(fileName);
FileInputStream csvStream = new FileInputStream(csvfile);
in = new BufferedReader(new InputStreamReader(csvStream));
String line;
String[] rowName = new String[(countLines(fileName)+1)/2];
String[] rowNameData = new String[(countLines(fileName)+1)/2];
int iCount=0;
int x = 0;
int y = 0;
while ((line = in.readLine()) != null){
if (iCount == 0 || iCount%2 == 0) {
rowName[x] = line;
++x;
}
else {
rowNameData[y] = line;
++y;
}
iCount++;
}
System.out.println("The rowName ARRAY");
for (String s: rowName){
System.out.println(s);
}
System.out.println("The rowNameData ARRAY");
for (String s: rowNameData){
System.out.println(s);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
in.close();
}
}
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
}

Error while converting text to QR code

I am trying to create a text to QR code converter.
I used the core2.2.jar from http://code.google.com/p/zxing/downloads/list and the code as told in Integrating the ZXing library directly into my Android application.
My Main.Activity is as shown below
package com.example.qr_androidone;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.qrCode);
String qrData = "Data I want to encode in QR code";
int qrCodeDimention = 500;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
imageView.setImageBitmap(bitmap);
} catch (WriterException 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.main, menu);
return true;
}
}
I used the "Contents.java" and "QRCodeEncoder.java" as shown in link Integrating the ZXing library directly into my Android application. I changed "activity_main.xml" also , as shown in above link
There are no errors in compiling, but there is error when the app runs
Could not find class 'com.google.zxing.EncodeHintType', referenced
from method com.example.qr_androidone.QRCodeEncoder.encodeAsBitmap
Could not find class 'com.google.zxing.MultiFormatWriter', referenced
from method com.example.qr_androidone.QRCodeEncoder.encodeAsBitmap
java.lang.NoClassDefFoundError: com.google.zxing.BarcodeFormat
Please help me solve the error
Download de JAR file, go to your Build Path and Import it from External JARs.
http://repo1.maven.org/maven2/com/google/zxing/core/2.2/
Then import it in your project.
you need the class of QRCodeEncoder.java..
public class QRCodeEncoder {
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
// private int dimension = Integer.MAX_VALUE;
private String contents = null;
private String displayContents = null;
private String title = null;
private BarcodeFormat format = null;
private boolean encoded = false;
public QRCodeEncoder(String data, Bundle bundle, String type, String format) {
// this.dimension = dimension;
encoded = encodeContents(data, bundle, type, format);
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
private boolean encodeContents(String data, Bundle bundle, String type, String formatString) {
// Default to QR_CODE if no format given.
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if (format == null || format == BarcodeFormat.QR_CODE) {
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(data, bundle, type);
} else if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(String data, Bundle bundle, String type) {
if (type.equals(Contents.Type.TEXT)) {
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
} else if (type.equals(Contents.Type.EMAIL)) {
data = trim(data);
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = "E-Mail";
}
} else if (type.equals(Contents.Type.PHONE)) {
data = trim(data);
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "Phone";
}
} else if (type.equals(Contents.Type.SMS)) {
data = trim(data);
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "SMS";
}
} else if (type.equals(Contents.Type.CONTACT)) {
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
uniquePhones.add(phone);
}
}
for (String phone : uniquePhones) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
uniqueEmails.add(email);
}
}
for (String email : uniqueEmails) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
String url = trim(bundle.getString(Contents.URL_KEY));
if (url != null) {
// escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
newContents.append("URL:").append(url).append(';');
newDisplayContents.append('\n').append(url);
}
String note = trim(bundle.getString(Contents.NOTE_KEY));
if (note != null) {
newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
newDisplayContents.append('\n').append(note);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "Contact";
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
if (bundle != null) {
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = "Location";
}
}
}
}
public Bitmap encodeAsBitmap() throws WriterException {
if (!encoded) return null;
Hashtable<EncodeHintType, String> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result =writer.encode(contents, format, 300, 300, hints);
int width = result.getWidth();
int height =result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
if(result.get(x, y) )
{
pixels[offset + x] = BLACK ;
}
else
pixels[offset + x] = WHITE ;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) { return "UTF-8"; }
}
return null;
}
private static String trim(String s) {
if (s == null) { return null; }
String result = s.trim();
return result.length() == 0 ? null : result;
}
private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; }
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
and also need content.java class..
public class Contents {
private Contents() {
}
public static final class Type {
public static final String TEXT = "TEXT_TYPE";
public static final String EMAIL = "EMAIL_TYPE";
public static final String PHONE = "PHONE_TYPE";
public static final String SMS = "SMS_TYPE";
public static final String CONTACT = "CONTACT_TYPE";
public static final String LOCATION = "LOCATION_TYPE";
private Type() {
}
}
public static final String URL_KEY = "URL_KEY";
public static final String NOTE_KEY = "NOTE_KEY";
public static final String[] PHONE_KEYS = {
ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE,
ContactsContract.Intents.Insert.TERTIARY_PHONE
};
public static final String[] PHONE_TYPE_KEYS = {
ContactsContract.Intents.Insert.PHONE_TYPE,
ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
};
public static final String[] EMAIL_KEYS = {
ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL,
ContactsContract.Intents.Insert.TERTIARY_EMAIL
};
public static final String[] EMAIL_TYPE_KEYS = {
ContactsContract.Intents.Insert.EMAIL_TYPE,
ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE
};
}
also need the core.jar file..
its perfectly work...

Categories

Resources