Android Studio, downloading image form url/app has stopped working - save

Hi could you help me find out why my app stops working when I want to download image from url, here is the code
public void getOnClick(View view) throws IOException {
urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp- content/uploads/2010/11/Capri.jpg");
InputStream is = urlAdress.openStream();
filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
outputFile = new File(context.getCacheDir(),filename);
OutputStream os = new FileOutputStream(outputFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
is.close();
os.close();
I was also trying to use some code from similar topics but I get same message
Your app has stopped working
and it shuts down

Caused by: android.os.NetworkOnMainThreadException
The problem is that you are trying to download the image from the UIThread. You have to create a class which extends to AsyncTask class and make the download on the doInBackground method
private class DownloadAsync extends AsyncTask<Void, Void, Void> {
private Context context;
DownloadAsync(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(Void... params) {
try {
URL urlAdress = urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp- content/uploads/2010/11/Capri.jpg");
InputStream is = urlAdress.openStream();
String filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
File outputFile = new File(context.getCacheDir(), filename);
OutputStream os = new FileOutputStream(outputFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
is.close();
os.close();
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Then you can execute like this
public void getOnClick(View view){
new DownloadAsync(this).execute();
}

Related

Sentiment Analysis with OpenNLP

I found this description of implementing a Sentiment Analysis task with OpenNLP. In my case I am using the newest OPenNLP-version, i.e., version 1.8.0. In the following example, they use a Maximum Entropy Model. I am using the same input.txt (tweets.txt)
http://technobium.com/sentiment-analysis-using-opennlp-document-categorizer/
public class StartSentiment {
public static DoccatModel model = null;
public static String[] analyzedTexts = {"I hate Mondays!"/*, "Electricity outage, this is a nightmare"/*, "I love it"*/};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);
}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("bin/text.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "2");
tp.put(TrainingParameters.ITERATIONS_PARAM, "30");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text){
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(new String[]{text});
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}
}
In my case no matter what input String I am using, I am only getting a positive estimation of the input string. Any idea what could be the reason?
Thanks

listfield with bitmap loaded from server

i have made a listfield with images, the listfield is parsed from online xml file.
it seems that downloading the images into the listfield is blocking the process of parsing the content of the listfield "text" , i want to show the content of the listfield "text" and then start to proccess the download of the images and then show the images.
here is the code to call the downloader class:
Thread t = new Thread();
{
String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
String saveDire = "file:///store/home/user/pictures/listfield/"+imageFilename;
try {
FileConnection fconn = (FileConnection)Connector.open(saveDire);
if (fconn.exists()) {
// do nothing
}
if (!fconn.exists()) {
UrlToImage bit = new UrlToImage(imageurlStrin);
pic = bit.getbitmap();
}
}catch (Exception ioe) {
System.out.println("error 18");
}
};
t.start();
and this is the downloader class code:
public class UrlToImage implements Runnable{
String imageurlStrin=null;
BitmapDowloadListener listener=null;
public static Bitmap _bmap;
private EncodedImage eih1;
public void run() {
UrlToImage bit = new UrlToImage(imageurlStrin);
}
public UrlToImage(String imageurlStrin)
{
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;
//byte[] data1 = null;
try
{
connection = (HttpConnection) Connector.open(imageurlStrin, Connector.READ, true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}
final String result = rawResponse.toString();
dataArray = result.getBytes();
}
catch (final Exception ex)
{ }
finally
{
try
{
inputStream.close();
inputStream = null;
connection.close();
connection = null;
}
catch(Exception e){}
}
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
// this will scale your image acc. to your height and width of bitmapfield
int multH;
int multW;
int currHeight = bitmap.getHeight();
int currWidth = bitmap.getWidth();
int scrhi = Display.getWidth()/4;
int scrwe = Display.getWidth()/4;
multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(scrhi));//height
multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(scrwe));//width
bitmap = bitmap.scaleImage32(multW,multH);
Bitmap thefinal = bitmap.getBitmap();
//url = StringUtils.replaceAll(url ,"http://u.bbstars.com/i-", "");
final String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
String saveDire = "file:///store/home/user/pictures/listfield/"+imageFilename;
String Dire = "file:///store/home/user/pictures/listfield/";
JPEGEncodedImage finalJPEG = JPEGEncodedImage.encode(thefinal, 100);
byte[] raw_media_bytes = finalJPEG.getData();
int raw_length = finalJPEG.getLength();
int raw_offset = finalJPEG.getOffset();
FileConnection filecon = null;
OutputStream out = null;
try {
filecon = (FileConnection) Connector.open(Dire,Connector.READ_WRITE);
if(!filecon.exists()){
filecon.mkdir();
}
filecon = (FileConnection) Connector.open(saveDire,Connector.READ_WRITE);
if(!filecon.exists()){
filecon.create();
}
out = filecon.openOutputStream();
out.write(raw_media_bytes, raw_offset, raw_length);
out.close();
filecon.close();
System.out.println("----------------file saved"+imageFilename);
} catch (IOException e) {
System.out.println("---------------===================- error saving the file");
};
try {
FileConnection fconn = (FileConnection)Connector.open(saveDire);
if (fconn.exists()) {
InputStream input = fconn.openInputStream();
int available = input.available();
final byte[] data1=IOUtilities.streamToBytes(input);
input.read(data1, 0, available);
eih1 = EncodedImage.createEncodedImage(data1,0,data1.length);
}
}catch (Exception ioe) {
System.out.println("error gettin bitmap details from the piture");
}
_bmap=eih1.getBitmap();
}
public Bitmap getbitmap()
{
return _bmap;
}
}
what should i do to prevent UI blocking, i want the perfect why to call that downloader class without stoping the process of parsing the other listfield content?
I think you may just have a simple syntax problem with the way you declared your thread object. See the BlackBerry documentation on Thread here
When you create a Thread, you normally either extend the Thread class with a subclass of your own, that implements the run() method, or you pass a new Runnable object in to the constructor of your Thread object. In your code, you actually declare a Thread instance, and create it, but do not give it a Runnable, or override the default run() method. So, this thread won't do anything in the background.
You have essentially declared a chunk of code within a local scope. That's what happens if you just put some code within a set of curly brackets ({ and }) that are not attached to anything:
Thread t = new Thread();
// this next curly bracket starts a "local scope". it is NOT part of Thread t!
{
String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
// The rest of your code here will not be executed on Thread t. It will be executed
// on the thread where you instantiate Thread t, right before you call t.start();
// If this code is called on the main/UI thread (which it probably is), then the
// network request will block the UI thread, which will stop the loading of the rest
// of the list.
};
t.start();
What you probably want is this:
Thread t = new Thread(new Runnable() {
public void run() {
String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
String saveDire = "file:///store/home/user/pictures/listfield/"+imageFilename;
try {
FileConnection fconn = (FileConnection)Connector.open(saveDire);
if (fconn.exists()) {
// do nothing
}
if (!fconn.exists()) {
UrlToImage bit = new UrlToImage(imageurlStrin);
pic = bit.getbitmap();
}
} catch (Exception ioe) {
System.out.println("error 18");
}
}
});
t.start();
Try that, and see if that fixes the problem.

BlackBerry: Creat Bitmap object from SD card image

Can we create an Bitmap object from the SD card image file path ?
I have written a sample method to create it. Is it right approach?
public Bitmap createBitmap(String filepath){
try {
// filepath e.g. "file:///SDCard/test.jpg"
FileConnection fc = (FileConnection)Connector.open(filepath);
byte[] responseData = new byte[10000];
InputStream inputStream =fc.openDataInputStream();
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
byte[] dataArray = rawResponse.toString().getBytes();
Bitmap bitmap = Bitmap.createBitmapFromBytes(dataArray, 0, dataArray.length, 1);
// EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
return bitmap;
} catch (IOException e) {
return null;
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
public final class MyScreen extends MainScreen {
Bitmap bit, bit1;
BitmapField bitf[] = new BitmapField[12];
FileConnection fc;
FlowFieldManager grid;
String[] imgpath = { "bharat.png", "fighter1.jpg", "fighter2.jpg",
"fighter3.jpg", "fighter4.jpg", "fighter5.jpg", "fighter7.jpg",
"fighter8.jpg", "fighter9.jpg", "fighter10.jpg", "fighter11.jpg",
"fighter6.jpg" };
String compath = "file:///SDCard/";`enter code here`
public MyScreen() {
grid = new FlowFieldManager();
try {
setTitle("Bharat Title");
for (int i = 0; i < imgpath.length; i++) {
fc = (FileConnection) Connector.open(compath + imgpath[i]);
DataInputStream in = fc.openDataInputStream();
int size = (int) fc.fileSize();
byte[] bb = new byte[size];
bb = IOUtilities.streamToBytes(in);
bit = bit.createBitmapFromBytes(bb, 0, bb.length, 1);
bit1 = new Bitmap(120, 120);
bit.scaleInto(bit1, Bitmap.FILTER_BOX);
bitf[i] = new BitmapField(bit1, FOCUSABLE);
grid.add(bitf[i]);
fc.close();
}
}
catch (Exception ex)
{
ex.getMessage();
}
finally {
try {
fc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
add(grid);
}
}

Blackberry Java - Fixed length streaming a POST body over a HTTP connect

I'm working on some code which POSTs large packets often over HTTP to a REST server on IIS. I'm using the RIM/JavaME HTTPConnection class.
As far as I can tell HTTPConnection uses an internal buffer to "gather" up the output stream before sending the entire contents to the server. I'm not surprised, since this is how HttpURLConnect works by default as well. (I assume it does this so that the content-length is set correctly.) But in JavaSE I could override this behavior by using the method setFixedLengthStreamingMode so that when I call flush on the output stream it would send that "chunk" of the stream. On a phone this extra buffering is too expensive in terms of memory.
In Blackberry Java is there a way to do fixed-length streaming on a HTTP request, when you know the content-length in advance?
So, I never found a way to do this was the base API for HTTPConnection. So instead, I created a socket and wrapped it with my own simple HTTPClient, which did support chunking.
Below is the prototype I used and tested on BB7.0.
package mypackage;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
public class MySimpleHTTPClient{
SocketConnection sc;
String HttpHeader;
OutputStreamWriter outWriter;
InputStreamReader inReader;
public void init(
String Host,
String port,
String path,
int ContentLength,
String ContentType ) throws IllegalArgumentException, IOException
{
String _host = (new StringBuffer())
.append("socket://")
.append(Host)
.append(":")
.append(port).toString();
sc = (SocketConnection)Connector.open(_host );
sc.setSocketOption(SocketConnection.LINGER, 5);
StringBuffer _header = new StringBuffer();
//Setup the HTTP Header.
_header.append("POST ").append(path).append(" HTTP/1.1\r\n");
_header.append("Host: ").append(Host).append("\r\n");
_header.append("Content-Length: ").append(ContentLength).append("\r\n");
_header.append("Content-Type: ").append(ContentType).append("\r\n");
_header.append("Connection: Close\r\n\r\n");
HttpHeader = _header.toString();
}
public void openOutputStream() throws IOException{
if(outWriter != null)
return;
outWriter = new OutputStreamWriter(sc.openOutputStream());
outWriter.write( HttpHeader, 0 , HttpHeader.length() );
}
public void openInputStream() throws IOException{
if(inReader != null)
return;
inReader = new InputStreamReader(sc.openDataInputStream());
}
public void writeChunkToServer(String Chunk) throws Exception{
if(outWriter == null){
try {
openOutputStream();
} catch (IOException e) {e.printStackTrace();}
}
outWriter.write(Chunk, 0, Chunk.length());
}
public String readFromServer() throws IOException {
if(inReader == null){
try {
openInputStream();
} catch (IOException e) {e.printStackTrace();}
}
StringBuffer sb = new StringBuffer();
int data = inReader.read();
//Note :: This will also read the HTTP headers..
// If you need to parse the headers, tokenize on \r\n for each
// header, the header section is done when you see \r\n\r\n
while(data != -1){
sb.append( (char)data );
data = inReader.read();
}
return sb.toString();
}
public void close(){
if(outWriter != null){
try {
outWriter.close();
} catch (IOException e) {}
}
if(inReader != null){
try {
inReader.close();
} catch (IOException e) {}
}
if(sc != null){
try {
sc.close();
} catch (IOException e) {}
}
}
}
Here is example usage for it:
MySimpleHTTPClient myConn = new MySimpleHTTPClient() ;
String chunk1 = "ID=foo&data1=1234567890&chunk1=0|";
String chunk2 = "ID=foo2&data2=123444344&chunk1=1";
try {
myConn.init(
"pdxsniffe02.webtrends.corp",
"80",
"TableAdd/234234234443?debug=1",
chunk1.length() + chunk2.length(),
"application/x-www-form-urlencoded"
);
myConn.writeChunkToServer(chunk1);
//The frist chunk is already on it's way.
myConn.writeChunkToServer(chunk2);
System.out.println( myConn.readFromServer() );
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
myConn.close();
}

send sms from background thread in blackberry using j2me

hey i made a lot of search and found some similar types of code.
I tried for gsm
method 1 gives IllegalArgumentException
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE);
tm.setPayloadText(smsText);
tm.setAddress("965xxxxxxx");
_mc.send(tm);
_mc.close();
}catch(exception e){}
method 2: gives java.lang.error exception
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE,
"//9790XXXXXX");
tm.setPayloadText(text);
_mc.send(tm);
_mc.close();
}catch(Exception e){}
I think the problem is with address
i also tried : but no success
+91965xxxxxxx ,
0091965xxxxxxx ,
0965xxxxxxx
How my application works----
i have created 2 applications--
1) Application 1 is a background app that is a System module as well as
startup application.
2) Another is a uiapplication
the background app runs in background.If there comes an incoming call then a flag value is set in persistent object and after checking that value as true the sms is send to that no from whom call is made.
ok try this
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
import net.rim.device.api.system.RadioInfo;
public class SendSMS extends Thread {
private String to;
private String msg;
public SendSMS(String to, String msg) {
this.to = to;
this.msg = msg;
}
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + to);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
dc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} else {
MessageConnection mc = null;
try {
mc = (MessageConnection) Connector
.open("sms://" + to);
TextMessage m = (TextMessage) mc
.newMessage(MessageConnection.TEXT_MESSAGE);
m.setPayloadText(msg);
mc.send(m);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
mc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
}
and call like this
public void callDisconnected(int callId) {
final PhoneCall call = Phone.getCall(callId);
final String number = call.getDisplayPhoneNumber();
SendSMS sendSMS = new SendSMS(number, "message");
sendSMS.start();
super.callDisconnected(callId);
}

Resources