Get image from standard Android Gallery - image

I am having problems getting an image back from the default android gallery. All I want to do is call the Android standard gallery intent and return the uri for the image in my onActivityResult. When I run this code it open the gallery just fine but then it force closes whenever I click on a picture. Any tips for this would be helpful.
private void doGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setType(IJudgeSingleton.IMAGEINTENT);
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select Picture"), IJudgeSingleton.REQUEST_CODE_GALLERY);
}
case IJudgeSingleton.REQUEST_CODE_GALLERY:
Uri uri = data.getData();
mSingleton.mFileTemp = new File(getMediaPath(uri));
try {
IJudgeSingleton.copy(mSingleton.mFileTemp, mSingleton.mCropFileTemp);
mData.setImageSet(true, mSingleton.mFileTemp.toURI().toString(), true);
mData.setPhoto(true);
}
catch (IOException e) {
Log.d(this.getClass().getName(), "REQUEST_CODE_GALLERY", e);
}
break;

Figured it out my file was pointing to a null so that's what was giving me the force close. Also I had to add change some code around in my onActivityResult for REQUEST_CODE_GALLERY. I have posted the added code below for anyone who has this problem.
case IJudgeSingleton.REQUEST_CODE_GALLERY:
Uri uri = data.getData();
//This takes the uri/image returned from the gallery intent a places it into a file.
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
try {
InputStream in = getContentResolver().openInputStream(uri);
OutputStream out = new FileOutputStream(mSingleton.mFileTemp); // I'm assuming you already have the File object for where you're writing to
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
in.close();
out.close();
} catch (Exception ex) {
Log.e(this.getClass().getName(),"REQUEST_CODE_GALLERY");
}
// mSingleton.mFileTemp = new File(getMediaPath(uri));
try {
IJudgeSingleton.copy(mSingleton.mFileTemp, mSingleton.mCropFileTemp);
mData.setImageSet(true, mSingleton.mFileTemp.toURI().toString(), true);
mData.setPhoto(true);
}
catch (IOException e) {
Log.d(this.getClass().getName(), "REQUEST_CODE_GALLERY", e);
}
break;
case IJudgeSingleton.REQUEST_CODE_DEFAULT_CAPTURE:
mData = data.getParcelableExtra(IJudgeSingleton.SURVEY_INTENT);
showListView();
completedIntent = false;

Related

how to copy OdadataSourceHandle from one design report to another design report?

String targetRptFile = System.getenv("LOCAL_BIRT_INPUT") + "/"+report.getMergeRptTemplates().getTargetTemplate()+".rptdesign";
String attachRptFile = System.getenv("LOCAL_BIRT_INPUT") + "/"+report.getMergeRptTemplates()
.getAttachTemplate()+".rptdesign";
DesignConfig dConfig = new DesignConfig();
IDesignEngineFactory factory = (IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);
IDesignEngine dEngine = factory.createDesignEngine(dConfig);
SessionHandle session = dEngine.newSessionHandle(null);
ReportDesignHandle targetRptDesignHandle = null;
ReportDesignHandle attachRptDesignHandle = null;
try {
targetRptDesignHandle = session.openDesign(targetRptFile);
attachRptDesignHandle = session.openDesign(attachRptFile);
} catch (DesignFileException e) {
e.printStackTrace();
}
OdaDataSourceHandle attachOdaDataSourceHandle = (OdaDataSourceHandle)attachRptDesignHandle.getAllDataSources()
.get(0);
targetRptDesignHandle.getAllDataSources().add(attachOdaDataSourceHandle);
String newTargetRptFile = System.getenv("LOCAL_BIRT_INPUT") + "/"+report
.getMergeRptTemplates().getTargetTemplate()+"-merge"+".rptdesign";
try {
targetRptDesignHandle.saveAs(newTargetRptFile);
targetRptDesignHandle.close();
attachRptDesignHandle.close();
session.closeAll(true);
} catch (IOException e) {
e.printStackTrace();
}
}
Never did this, but I remember a similar problem when I wanted to copy a JDBCDataSource. I worked around this by setting all the properties manually instead of trying to copy the whole DS.

How to read Data via a Future using file channels?

I am reading a file using RandomFileAccess, FileChannel and ByteBuffer as follows:
RandomAccessFile myFile = new RandomAccessFile("/Users/****/Documents/a.txt", "rw");
FileChannel myInChannel = myFile.getChannel();
ByteBuffer bb = ByteBuffer.allocate(48);
int bytesRead = myInChannel.read(bb);
while (bytesRead != -1) {
// do something
}
myFile.close();
All this code is working fine.
But i am wondering is there any way i can read the data using Future?
I tried following code, and it worked fine for:
try(AsynchronousFileChannel afileChannel = AsynchronousFileChannel.open(Paths.get("/Users/***/Documents/myFile.txt"), StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
Future<Integer> operation = afileChannel.read(buffer, position);
while(!operation.isDone()){
//do something
}
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Got to know that this can be done via AsynchronousFileChannel but not via FileChannel.

BlackBerry - Downloaded images are corrupted on wifi with HttpConnection

In my app I need to download several images from a server. I use this code to get a byte array :
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
The url are formed with the suffix ";deviceSide=false;ConnectionType=MDS - public" (without spaces) and it is working perfectly well.
The problem is that with phones that do not have a sim card, we can't connect to the internet via the MDS server. So we changed to use the connection factory and let BB choose whatever he wants :
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
The connection works because it select the good prefix (interface=wifi in our case), but this create another problem.
Some images are not well downloaded, some of them (not the sames at each try) are corrupted, but only when the phone use a wifi connection to get these images.
How can I avoid this problem ? What method to get a connection do I have to use ? Is it possible to check if the user have a sim card in orderto use MDS - public ?
Here is an example of a corrupted image :
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
try this:
public static String buildURL(String url) {
String connParams = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connParams = ";interface=wifi"; //Connected to a WiFi access point.
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
//
if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
connParams = ";deviceside=false;ConnectionType=mds-public";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
ServiceRecord record = getWAP2ServiceRecord();
//
if (record != null) {
connParams = ";deviceside=true;ConnectionUID=" + record.getUid();
} else {
connParams = ";deviceside=true";
}
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connParams = ";deviceside=false";
}
}
Log.d("connection param"+url+connParams);
//
return url+connParams;
}
private static ServiceRecord getWAP2ServiceRecord() {
String cid;
String uid;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
//
for (int i = records.length -1; i >= 0; i--) {
cid = records[i].getCid().toLowerCase();
uid = records[i].getUid().toLowerCase();
//
if (cid.indexOf("wptcp") != -1
&& records[i].getUid().toLowerCase().indexOf("wap2") !=-1
&& uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
//
return null;
}
What happens when you append interface=wifi? Can you run the network diagnostic tool attached to below kb article and run all tests with SIM removed
http://supportforums.blackberry.com/t5/Java-Development/What-Is-Network-API-alternative-for-legacy-OS/ta-p/614822
Please also note that when download large files over BES/MDS there are limits imposed by MDS. Please ensure you review the below kb article
http://supportforums.blackberry.com/t5/Java-Development/Download-large-files-using-the-BlackBerry-Mobile-Data-System/ta-p/44585
You can check to see if coverage is sufficient for BIS_B (MDS public) but that won't help you if you are trying to support SIM-less users. I wonder if the problem is in an incomparability between the connection on Wi-Fi and IOUtilities.streamToBytes(). Try coding as recommended in the API documents.

How to make a save action that checks whether a 'save-as' has already been performed

I have researched and tried to refer back to my fileChooser.getSeletedFile() in my save as action but can not work out how to check whether or not a file has been created. Here is my attempted code so far:
Save as code(works well):
public void Save_As() {
fileChooserTest.setApproveButtonText("Save");
int actionDialog = fileChooserTest.showOpenDialog(this);
File fileName = new File(fileChooserTest.getSelectedFile() + ".txt");
try {
if (fileName == null) {
return;
}
BufferedWriter outFile = new BufferedWriter(new FileWriter(fileName));
outFile.write(this.jTextArea2.getText());//put in textfile
outFile.flush(); // redundant, done by close()
outFile.close();
} catch (IOException ex) {
}
}
"Save" code doesn't work:
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
File f = fileChooserTest.getSelectedFile();
try {
if (f.exists()) {
BufferedWriter bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
String text = ((JTextArea) jTabbedPane1.getSelectedComponent()).getText();
bw1.write(text);
bw1.close();
} else {
Save_As();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Instead of storing an instance to the JFileChooser rather store an instance to the File (wich will be null before any save has been performed). In your SaveActionPerformed method check if the file is null. If it is null then do a Save_As and store the selected file in your file variable, if it is not null then do a normal save into the file.

BlackBerry create bitmap from path

After taking a picture in my app I want to get the image (by it's path).
I see lots of examples on how to get an image, the only problem is that it no longer is possible doing it by using Connector.open() since Connector is deprecated now.
What to use instead?
conn = (FileConnection)Connector.open("file:///SDCard/BlackBerry/pictures/" + picture);
try {
InputStream input = null;
input = fconn.openInputStream();
int available = 0;
available = input.available();
int fSz = (int)fconn.fileSize();
byte[] data = new byte[fSz];
input.read(data, 0, fSz);
image = EncodedImage.createEncodedImage(data,0,data.length);
bkBitmap = image.getBitmap();
} catch(ControlledAccessException e) {
pLog = "*** Problem Accessing image file:" + e;
EventLogger.logEvent( GUID, pLog.getBytes() );
}
Thanks!
Try this code:
public class LoadingScreen extends MainScreen
{
public LoadingScreen()
{
setTitle("Loading Screen");
createGUI();
}
private void createGUI()
{
BitmapField bitmapField=new BitmapField(getTheImage());
add(bitmapField);
}
private Bitmap getTheImage()
{
Bitmap bitmap=null,scaleBitmap=null;
InputStream inputStream=null;
FileConnection fileConnection=null;
try
{
fileConnection=(FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/"+"background.png");
if(fileConnection.exists())
{
inputStream=fileConnection.openInputStream();
byte[] data=new byte[(int)fileConnection.fileSize()];
data=IOUtilities.streamToBytes(inputStream);
inputStream.close();
fileConnection.close();
bitmap=Bitmap.createBitmapFromBytes(data,0,data.length,1);
//You can return this bitmap otherwise, after this you can scale it according to your requirement; like...
scaleBitmap=new Bitmap(150, 150);
bitmap.scaleInto(scaleBitmap, Bitmap.FILTER_LANCZOS);
}
else
{
scaleBitmap=Bitmap.getBitmapResource("noimage.png");//Otherwise, Give a Dialog here;
}
}
catch (Exception e)
{
try
{
if(inputStream!=null)
{
inputStream.close();
}
if(fileConnection!=null)
{
fileConnection.close();
}
}
catch (Exception exp)
{
}
scaleBitmap=Bitmap.getBitmapResource("noimage.png");//Your known Image;
}
return scaleBitmap;//return the scale Bitmap not the original bitmap;
}
}
I got like this below Image:

Resources