How to read datamatrix embedded in document? - zxing

I try to read a datamatrix which is embedded into a document.
This is for an opensource project which helps to create and read 2DCODE standard.
I try with this code :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ZxingTest {
#Test
public void test() {
readQRCode("sfr-facture-1048469311-1.jpg");
readQRCode("sfr-facture-1048469311-1.png");
}
public static void readQRCode(String fileName) {
System.out.println("Try reading " + fileName);
File file = new File(fileName);
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image == null)
return;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
// hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.DATA_MATRIX));
decode(image, hints);
}
public static void decode(BufferedImage tmpBfrImage, Hashtable<DecodeHintType, Object> hintsMap) {
if (tmpBfrImage == null)
throw new IllegalArgumentException("Could not decode image.");
LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
Result tmpResult;
String tmpFinalResult;
try {
if (hintsMap != null && !hintsMap.isEmpty())
tmpResult = tmpBarcodeReader.decode(tmpBitmap, hintsMap);
else
tmpResult = tmpBarcodeReader.decode(tmpBitmap);
// setting results.
tmpFinalResult = String.valueOf(tmpResult.getText());
System.out.println("tmpFinalResult=" + tmpFinalResult);
} catch (Exception tmpExcpt) {
tmpExcpt.printStackTrace();
}
}
}
and those images found on the net :
sfr-facture-1048469311-1.jpg
sfr-facture-1048469311-1.png
But I get this exception regardless of the image format: com.google.zxing.NotFoundException
May you advise me an lib which parses the page and detect the datamatrix coordinates for a pre-processing cropping?
Or a better a example of code which read the datamatrix?

I have a solution to my problem. I use opencv to locate any barcode then, after extraction according to the returned coordinates, I read them with zxing.
I based my solution the work of http://karthikj1.github.io/BarcodeLocalizer/
this the code i use :
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import barcodelocalizer.Barcode;
import barcodelocalizer.CandidateResult;
import barcodelocalizer.ImageDisplay;
import barcodelocalizer.MatrixBarcode;
import barcodelocalizer.TryHarderFlags;
public class OpencvUtils {
private static boolean SHOW_INTERMEDIATE_STEPS = false;
private static boolean showImages = false;
public static String process_bufferedImage(BufferedImage bufferedImage) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(bufferedImage, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding buffered image " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
public static String process_image(String imgFile) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(imgFile, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding " + imgFile + " " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
private static String decodeBarcode(List<CandidateResult> candidateCodes, String filename, String caption) {
// decodes barcode using ZXing and either print the barcode text or says no
// barcode found
BufferedImage decodedBarcode = null;
String title = null;
Result result = null;
String barcodeText = null;
for (CandidateResult cr : candidateCodes) {
BufferedImage candidate = cr.candidate;
decodedBarcode = null;
LuminanceSource source = new BufferedImageLuminanceSource(candidate);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try {
result = reader.decode(bitmap, hints);
decodedBarcode = candidate;
title = filename + " " + caption + " - barcode text " + result.getText() + " " + cr.getROI_coords();
} catch (ReaderException re) {
}
if (decodedBarcode == null) {
title = filename + " - no barcode found - " + cr.getROI_coords();
if (showImages)
ImageDisplay.showImageFrame(candidate, title);
} else {
if (showImages)
ImageDisplay.showImageFrame(decodedBarcode, title);
System.out.println("Barcode text for " + filename + " is " + result.getText());
barcodeText = result.getText();
}
}
return barcodeText;
}
}
i added the method process_bufferedImage which process a java.awt.image.BufferedImage of a String filename.
And this sub-method to get the matrix of the BufferedImage bi.
protected Mat loadBufferedImage(BufferedImage bi) throws IOException {
// reads the BufferedImage passed in parameter
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bi, "png", byteArrayOutputStream);
byteArrayOutputStream.flush();
Mat mat = Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.IMREAD_UNCHANGED);
return mat;
}

Related

Error enlarging buttons on eclipse

Hello im trying to enlarge my buttons on eclipse. I found this code on the web that suppose to fix it
but it keeps giving me the error
Error: Could not find or load main class testEclipse.FixIcons
Any idea what can i do?
Im pretty new at this .. thanks
package testEclipse;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.imgscalr.Scalr;
import com.mortennobel.imagescaling.AdvancedResizeOp;
import com.mortennobel.imagescaling.ResampleOp;
/**
* Small utility to double the size of eclipse icons for QHD monitors.
*
* #author David Levy
* #since 2014/04/10
*
*/
public class FixIcons {
private static final Logger logger = Logger.getLogger(FixIcons.class);
public static final void main(String[] args) {
try {
Options options = new Options();
options.addOption(new Option("b", "baseDir", true,
"This is the base directory where we'll parse jars/zips"));
options.addOption(new Option("o", "outputDir", true,
"This is the base directory where we'll place output"));
for (Option o : new ArrayList<Option>(options.getOptions())) {
o.setRequired(true);
}
GnuParser parser = new GnuParser();
CommandLine commandLine = parser.parse(options, args);
String baseDirArg = "D:\\things\\tools\\eclipse";
logger.info("Base directory: " + baseDirArg);
String outputDirArg = "D:\\things\\tools\\eclipsetmp";
logger.info("Output directory: " + outputDirArg);
File base = new File(baseDirArg);
if (!base.exists() || !base.canRead() || !base.isDirectory()) {
logger.error("Unable to read from base directory");
return;
}
File output = new File(outputDirArg);
if (!output.exists() || !output.canRead() || !output.canWrite()
|| !output.isDirectory()) {
logger.error("Unable to write to output director");
return;
}
if (base.list() == null || base.list().length == 0) {
logger.error("The base directory is empty");
return;
}
if (output.list() != null && output.list().length != 0) {
logger.error("The output directory is not empty");
return;
}
processDirectory(base, output);
} catch (ParseException e) {
logger.error("Unable to parse arguments: " + e.getMessage());
} catch (Exception e) {
logger.error("Unexpected error: " + e.getMessage(), e);
}
}
public static void processDirectory(File directory, File outputDirectory)
throws Exception {
logger.info("Processing directory [" + directory.getAbsolutePath()
+ "]");
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
File targetDir = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
logger.info("Creating directory: "
+ targetDir.getAbsolutePath());
targetDir.mkdir();
processDirectory(file, targetDir);
} else {
File targetFile = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
if (file.getName().toLowerCase().endsWith(".zip")
|| file.getName().toLowerCase().endsWith(".jar")) {
logger.info("Processing archive file: "
+ file.getAbsolutePath());
ZipFile zipSrc = new ZipFile(file);
Enumeration<? extends ZipEntry> srcEntries = zipSrc.entries();
ZipOutputStream outStream = new ZipOutputStream(
new FileOutputStream(targetFile));
while (srcEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) srcEntries.nextElement();
logger.info("Processing zip entry [" + entry.getName()
+ "]");
ZipEntry newEntry = new ZipEntry(entry.getName());
try {
outStream.putNextEntry(newEntry);
} catch (Exception e) {
if (!e.getMessage().startsWith("duplicate entry: ")) {
logger.error("error: ", e);
} else {
logger.info(e.getMessage(), e);
}
outStream.closeEntry();
continue;
}
BufferedInputStream bis = new BufferedInputStream(
zipSrc.getInputStream(entry));
if (ImageType.findType(entry.getName()) != null) {
processImage(zipSrc.getName() + "!/" + entry.getName(), bis, outStream);
} else {
IOUtils.copy(bis, outStream);
}
outStream.closeEntry();
bis.close();
}
zipSrc.close();
outStream.close();
} else if (ImageType.findType(file.getName()) != null) {
logger.info("Processing image: " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
processImage(file.getName(), inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
} else {
logger.info("Processing : " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
IOUtils.copy(inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
}
}
}
}
public static void processImage(String fileName, InputStream input,
OutputStream output) throws IOException {
logger.info("Scaling image: " + fileName);
boolean imageWriteStarted = false;
try {
BufferedImage out = ImageIO.read(input);
int outWidth = out.getWidth() * 2;
int outHeight = out.getHeight() * 2;
BufferedImage rescaledOut = createResizedCopy(out, outWidth, outHeight);
ImageIO.write(rescaledOut, ImageType.findType(fileName).name(),
output);
} catch (Exception e) {
if (imageWriteStarted) {
throw new RuntimeException("Failed to scale image [" + fileName
+ "]: " + e.getMessage(), e);
} else {
logger.error(
"Unable to scale [" + fileName + "]: " + e.getMessage(),
e);
IOUtils.copy(input, output);
}
}
}
private static BufferedImage createResizedCopy(BufferedImage originalImage, int scaledWidth, int scaledHeight) {
try {
// Resample failed - maybe the image was too small, try another way (Scalr)
BufferedImage scaledBI = Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, scaledWidth, scaledHeight);
return scaledBI;
} catch (RuntimeException e) {
return scale(originalImage, 2.0);
}
}
private static BufferedImage scale(BufferedImage source,double ratio) {
int w = (int) (source.getWidth() * ratio);
int h = (int) (source.getHeight() * ratio);
BufferedImage bi = getCompatibleImage(w, h);
Graphics2D g2d = bi.createGraphics();
double xScale = (double) w / source.getWidth();
double yScale = (double) h / source.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return bi;
}
private static BufferedImage getCompatibleImage(int w, int h) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
return image;
}
}

Data in Adapter but not loding in Listview | converted Listactivity to ListFragment

I have converted Many Activities to Fragment, all are working fine except one. In the Previous version of this java file, it was extending ListActivity, now I have replaced it with ListFragment. Initially it was giving a nullPointerException, but with help of this post, I managed to remove error. Now it is fetching data in Adapter but not in listview (which I checked by printing it in log). So I need to show data in listview.
Here is Java code:
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.io.InputStreamReader;
import java.net.URL;
import java.io.BufferedReader;
import java.net.URLConnection;
import android.support.v4.app.Fragment;
public class listtojson extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
// public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listFileDir.php";
public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listnews.php";
//public static String url = "http://www.newsvoice.in/sites/listNewsSites.php";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
private static final String TAG_PHONE_URL = "url";
private static final String TAG_FILETYPE = "filetype";
private static final String TAG_FILETYPETXT = "filetypetxt";
private static final String TAG_DETAILS = "details";
private static final String TAG_FILEPATH = "filepath";
private static final String TAG_LOCATION = "location";
private static final String TAG_DATETIME = "datetime";
private static final String TAG_USERNAME = "username";
private static final String TAG_HIGHALERT= "highalert";
// public ImageLoader imageLoader;
public int ssid ;
// contacts JSONArray
JSONArray contacts = null;
public TextView view1;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
View fragment;
LinearLayout llLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentActivity faActivity = (FragmentActivity) super.getActivity();
llLayout = (LinearLayout) inflater.inflate(R.layout.listnewsjson, container, false);
contactList = new ArrayList<HashMap<String, String>>();
fragment = inflater.inflate(R.layout.listnewsjson, container, false);
return llLayout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv = (ListView) fragment.findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String size = ((TextView) view.findViewById(R.id.size))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String details = ((TextView) view.findViewById(R.id.details))
.getText().toString();
String location = ((TextView) view.findViewById(R.id.location))
.getText().toString();
String datetime = ((TextView) view.findViewById(R.id.datetime))
.getText().toString();
String filetype = ((TextView) view.findViewById(R.id.filetypetxt))
.getText().toString();
String username = ((TextView) view.findViewById(R.id.username))
.getText().toString();
//String highalert = ((TextView) view.findViewById(R.id.highalert)).getText().toString();
//ImageView thumb_image=(ImageView)view.findViewById(R.id.filetype);
// ImageView image = (ImageView) view.findViewById(R.id.filetype);
// thumb image
//= String filetype = ((ImageView) view.findViewById(R.id.filetype))
//= .getText().toString();
// Starting single contact activity
/* Intent in = new Intent(getApplicationContext(),
fileDownloader.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_SIZE, cost);
in.putExtra(TAG_PHONE_URL, description);
startActivity(in);
*/
Intent in = new Intent(getActivity().getApplicationContext(), jsondetailActivity.class);
// passing sqlite row id
//= in.putExtra(TAG_ID, sqlite_id);
in.putExtra(TAG_ID, String.valueOf(id));
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_DETAILS, details);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_DATETIME, datetime);
in.putExtra(TAG_FILETYPE, filetype);
in.putExtra(TAG_PHONE_URL, description);
in.putExtra(TAG_SIZE, size);
in.putExtra(TAG_USERNAME, username);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
//return llLayout;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading People News");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
try {
// Making a request to url and getting response
// String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
URL requestUrl = new URL(url);
Log.e("Debug", " Sapp 1 : " + requestUrl.toString());
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
//Reader rd=new Readable(in);
int cp;
try {
while((cp=in.read())!=-1){
sb.append((char)cp);
}}
catch(Exception e){
}
String jsonStr=sb.toString();
Log.e("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
String url = c.getString(TAG_PHONE_URL);
String details = c.getString(TAG_DETAILS);
String location = c.getString(TAG_LOCATION);
String datetime = c.getString(TAG_DATETIME);
String filetype = c.getString(TAG_FILETYPE);
String username = c.getString(TAG_USERNAME);
String highalert = c.getString(TAG_HIGHALERT);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_SIZE, size);
contact.put(TAG_PHONE_URL, url);
contact.put(TAG_DETAILS, details);
contact.put(TAG_LOCATION, location);
contact.put(TAG_DATETIME, datetime);
contact.put(TAG_FILETYPE, filetype);
contact.put(TAG_FILETYPETXT, filetype);
contact.put(TAG_USERNAME, username);
contact.put(TAG_HIGHALERT, highalert);
// Log.e("Debug", " Sapp 7 : " + name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}catch(Exception ec){
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_selector, new String[] { TAG_NAME, TAG_SIZE,
TAG_PHONE_URL,TAG_FILETYPE, TAG_FILETYPETXT,TAG_DETAILS,TAG_LOCATION,TAG_DATETIME, TAG_USERNAME, TAG_HIGHALERT}, new int[] { R.id.name,
R.id.size, R.id.url, R.id.filetype,R.id.filetypetxt, R.id.details, R.id.location, R.id.datetime, R.id.username, R.id.highalert });
Log.e("Debug", " Sapp 10" + TAG_NAME+contactList.toString());
//Here it is printing the array in Log
//Problem seems here
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11"+view.getId());
if (view.getId() == R.id.name) {
((TextView) view).setText((String) data);
return true;
} else if (view.getId() == R.id.size) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.url) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.details) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.location) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.datetime) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.filetypetxt) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.username) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10,20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert=(String.valueOf((String) data));
if(halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
return true;
}
else { return true; }
} else if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res =getResources();
String tnew=(String.valueOf((String) data));
String tst=tnew;
int sidd=0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if(tst.equals("c")) { ssid = R.drawable.ca; }
else if(tst.equals("d")) { ssid = R.drawable.da; }
else if(tst.equals("e")) { ssid = R.drawable.ea; }
//s=2130837566;
Log.e("Debug", " Sapp 8 :"+ssid+":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
};
((SimpleAdapter) adapter).setViewBinder(viewBinder);
lv.setAdapter(adapter);
registerForContextMenu(lv);
}
}
public static String getFileSize(long size) {
if (size <= 0)
return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
and Here is xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
/>
</LinearLayout>
Some suggestions:
No need for View fragment; and its initialization: fragment = inflater.inflate(R.layout.listnewsjson, container, false); Remove them.
Replace lv = (ListView) fragment.findViewById(android.R.id.list); with lv = getListView();. getListView() is a method defined by ListFragment that returns the fragment's ListView.
IMPORTANT: Replace lv.setAdapter(adapter); in onPostExecute() with setListAdapter(adapter);. From documentation of ListFragment:
You must use ListFragment.setListAdapter() to associate the list with an adapter. Do not directly call ListView.setAdapter() or else important initialization will be skipped.
Modify setViewValue() method of viewBinder to:
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11" + view.getId());
if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10, 20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert = (String.valueOf((String) data));
if (halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
} else {
// TODO: Should remove gradient color here because views are recycled.
}
return true;
}
if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res = getResources();
String tnew = (String.valueOf((String) data));
String tst = tnew;
int sidd = 0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if (tst.equals("c")) {
ssid = R.drawable.ca;
} else if (tst.equals("d")) {
ssid = R.drawable.da;
} else if (tst.equals("e")) {
ssid = R.drawable.ea;
}
//s=2130837566;
Log.e("Debug", " Sapp 8 :" + ssid + ":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
ViewBinder only needs to handle cases where you need to do something extra (like setting background color or loading images based on passed-in data values in your case) than just simply binding values to views. Ordinary binding of values to views is provided by SimpleAdapter by default.

iText - Convert field names with square brackets to fields without square brackets?

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfStamper;
import java.util.Set;
import java.io.FileOutputStream;
public class PDFFile {
public static final String xfaForm3 = "C:/PDF_Service/pdf-project/src/sample.pdf";
public static final String dest = "sample2.xml";
public static void main(String[] args)
{
PdfReader reader;
PdfReader.unethicalreading = true;
AcroFields form;
try{
reader = new PdfReader(xfaForm3);
PdfStamper stamper2 = new PdfStamper(reader, new FileOutputStream(dest));
form = stamper2.getAcroFields();
stamper2.close();
Set<String> fldNames = form.getFields().keySet();
for (String fldName : fldNames)
{
System.out.println( fldName + " : " + form.getField( fldName ) );
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
My code above is reading a PDF file that has the XFA format and it prints out something that looks like this:
F[0].P1[0].FFField1[14] : 11 Pine Drive
Instead of printing out "F[0].P1[0].FFField1[14]", how can I print out "Address"?
I would like my code to print out this:
Address : 11 Pine Drive

Google maps API v2 Android, not drawing polygon when offline

I have a test application that I draw a Polygon using google maps API.
The problem is that, when I have no cache of any maps (new installed application) the Polygon does not draw.
Its not a problem not having the maps loaded, but I do need the Polygons drawn in my screen.
Is there a way I can do that?
Sry for my bad english
Heres the code I have:
package ngvl.testegmaps_v2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import ngvl.testegmaps_v2.VO.GeoPosicionamento;
import ngvl.testegmaps_v2.VO.Layer;
import ngvl.testegmaps_v2.VO.Secao;
import ngvl.testegmaps_v2.VO.Talhao;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends FragmentActivity {
private List<Secao> secoes;
private List<Polygon> poligonos = new ArrayList<Polygon>();
private HashMap<String,Object[]> informacoes = new HashMap<String,Object[]>();
private GoogleMap map;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = fragment.getMap();
map.getUiSettings().setRotateGesturesEnabled(false);
// Setting a click event handler for the map
LatLng latLng = new LatLng(-20.9957152, -47.3241304);
// map.addMarker(new
// MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).title("Av. Paulista").snippet("São Paulo"));
configuraPosicao(map, latLng);
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
}
private void configuraPosicao(GoogleMap map, LatLng latLng) {
/*
* 3D map.moveCamera( CameraUpdateFactory.newLatLngZoom(latLng, 15));
* map.animateCamera( CameraUpdateFactory.zoomTo(10), 2000, null);
*
* CameraPosition cameraPosition = new CameraPosition.Builder()
* .target(latLng) .zoom(17) .bearing(90) .tilt(45) .build();
*
* map.animateCamera( CameraUpdateFactory.newCameraPosition(
* cameraPosition));
*/
map.setMapType(GoogleMap.MAP_TYPE_NONE);
// map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
try {
String json = readFileAsString("geo.json");
Gson gson = new Gson();
this.secoes = gson.fromJson(json, new TypeToken<List<Secao>>() {
}.getType());
json = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
escrevePoligons(map);
}
private String readFileAsString(String fileName) throws IOException {
InputStream is = getAssets().open(fileName);
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
private void escrevePoligons(GoogleMap map) {
float stroke = (float) 1.5;
for (Secao secao : secoes) {
for (Talhao talhao : secao.getTalhoes()) {
for (Layer layer : talhao.getLayers()) {
// PolygonOptions rectOptions = new PolygonOptions();
List<LatLng> latlngs = new ArrayList<LatLng>();
for (GeoPosicionamento geoPosicionamento : layer.getGeoPosicionamentos()) {
latlngs.add(new LatLng(geoPosicionamento.getLatitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue(), geoPosicionamento
.getLongitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue()));
}
int color = 0x1F00FF00;
int color2 = 0x5F000000;
PolygonOptions polygonOptions = new PolygonOptions()
.fillColor(color).addAll(latlngs)
.strokeColor(color2).strokeWidth(stroke);
Polygon p = map.addPolygon(polygonOptions);
poligonos.add(p);
informacoes.put( p.getId(), new Object[]{ secao, talhao , layer } );
//System.out.println(polygonOptions.getPoints());
polygonOptions = null;
latlngs = null;
}
}
}
this.secoes = null;
// String mUrl =
// "https://khms0.google.com.br/kh/v=124&src=app&z={z}&x={x}&y={y}";
// MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256,
// mUrl);
// mTileProvider.tilesRange();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
//String mUrl = "http://a.tile.openstreetmap.org/{z}/{x}/{y}.png";
//MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256, mUrl);
//map.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
// TileProvider tileProvider = TileProviderFactory.getTileProvider();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(tileProvider));
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
// LatLng(-20.9957152, -47.3241304), 15));
map.setOnMapClickListener(new OnMapClickListener()
{
public void onMapClick(LatLng point)
{
Polygon p = isPointInPolygon(point);
if( p != null){
p.setFillColor(getRandomColor());
Object[] clicado = informacoes.get( p.getId() );
Secao secao_clicada = (Secao) clicado[0];
Talhao talhao_clicada = (Talhao) clicado[1];
Layer layer_clicada = (Layer) clicado[2];
//System.out.println(secao_clicada);
//System.out.println(talhao_clicada);
//System.out.println(layer_clicada);
//System.out.println("=======================");
StringBuilder texto = new StringBuilder();
texto.append("Seção: " + secao_clicada.getDesc() + "\n");
texto.append("Talhão: " + talhao_clicada.getTalhao() + "\n");
texto.append("Variedade: " + talhao_clicada.getVariedade() + " - " + talhao_clicada.getDescVariedade() + "\n");
texto.append("Layer: " + layer_clicada.getSequencia() + "\n");
//Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
addMarker(point,texto);
}//else
//Toast.makeText(MainActivity.this,"Clicou fora da Área de um Poligono", Toast.LENGTH_LONG).show();
}
});
}
public void addMarker(LatLng point, StringBuilder texto) {
/*map.addMarker(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.title("Caracteristicas: ")
.snippet( texto );
*/
Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
}
private Polygon isPointInPolygon(LatLng tap) {
for( Polygon p : poligonos){
int intersectCount = 0;
List<LatLng> vertices = p.getPoints();
for(int j=0; j<vertices.size()-1; j++) {
if( rayCastIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
intersectCount++;
}
}
if(((intersectCount % 2) == 1)){
return p;
}
}
return null;// odd = inside, even = outside;
}
private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
}
double m = (aY-bY) / (aX-bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
}
};
public int getRandomColor() {
int color;
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
return color;
}
}
Setting map type to MAP_TYPE_NONE like example above does not solve the problem
I will this as marked solved by using Maps Forge Open Source API
If someone did with Google Maps Api please share and I would change the answer.
The answer I found is that its impossible to render or access anything without rendering the map first (online or via cache)
This is actually a bug of GoogleMaps Api v2 for Android.
It is referenced here:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5017
Star it if you want to accelerate the bug fix!

How to run a main class from a GUI Jbutton?

I've created a main class (class file). As fas as i'm concerned, it works properly. Now, i'm creating a GUI which contains a button to launch that class file. How do I write the code for the actionListener in order to run mainProgram class?
This is the main class:
import java.io.*;
import java.util.*;
public class MainProgram
{
public static void main (String args[]) throws IOException
{
//Declare variables
Scanner in = new Scanner (System.in); // Scanner used for user input
BufferedReader inputQuote;
BufferedReader inputTheme;
BufferedReader inputCharacterAnalysis;
BufferedReader inputSignificance;
BufferedReader inputPlotEnhancement;
BufferedReader inputSpeaker;
String [][] quotes;
String text;
int quoteSelection;
int analysisSelection;
int howMany=0;
int count;
//Count the number of lines in a text file
FileReader fr = new FileReader ("CrucibleQuotations.txt");
LineNumberReader ln = new LineNumberReader (fr);
while (ln.readLine() != null)
{
howMany++;
}
//import information from the text file
inputQuote = new BufferedReader (new FileReader ("CrucibleQuotations.txt"));
inputTheme = new BufferedReader (new FileReader("CrucibleTheme.txt"));
inputCharacterAnalysis = new BufferedReader (new FileReader("CrucibleCharacterAnalysis.txt"));
inputSignificance = new BufferedReader (new FileReader("CrucibleSignificance.txt"));
inputPlotEnhancement = new BufferedReader (new FileReader("CruciblePlotEnhancement.txt"));
inputSpeaker = new BufferedReader (new FileReader("CrucibleSpeaker.txt"));
//Create array based on how many quotes available in the text file
quotes = new String [howMany][6];
//Store quote information in the array and display the list of quotations
for (int i=0; i<howMany; i++)
{
quotes [i][0] = inputQuote.readLine();
System.out.println (i+1 + ") " + quotes [i][0]);
quotes [i][1] = inputTheme.readLine();
quotes [i][2] = inputCharacterAnalysis.readLine();
quotes [i][3] = inputSignificance.readLine();
quotes [i][4] = inputPlotEnhancement.readLine();
quotes [i][5] = inputSpeaker.readLine();
}
//Ask user to choose the quote they want to analyze
System.out.println ("Choose a quotation by inputting the number. If the quotation you would like to analyse is unavailable, you may create your own by entering the number 0. ");
quoteSelection = in.nextInt ();
if (quoteSelection!=0)
{
//Show user selections to analyze
System.out.println ("Choose your analysis");
System.out.println ("1. Theme");
System.out.println ("2. Character Analysis");
System.out.println ("3. Significance");
System.out.println ("4. Plot Enhancement");
System.out.println ("5. Speaker");
analysisSelection = in.nextInt ();
//Display the analysis
if (analysisSelection <= 5 || analysisSelection > 0)
{
System.out.println (quotes [quoteSelection-1][analysisSelection]);
}
}
This would be my GUI class
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
public class GUI
{
public GUI()
{
JFrame frame = new JFrame ("Quotes");
frame.setSize(500, 500);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
cButton.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent ae) {
try{
MainProgram.main (new String[]);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void main (String [] args)
{
new GUI();
}
}
Remember to call
frame.pack();
frame.setVisible(true);
or your JFrame will not be shown.
As for the ActionListener code, you've to add [0] for the String Array dimension such as:
cButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
MainProgram.main(new String[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
});