Hi I am trying to get an image from url to bitmap. I have android 4.1 device. When I run this code on new URL(). open connection().getInputStream()); app freezes then force close. Any idea?
runOnUiThread(new Runnable() {
public void run() {
String url = "http://netmera.com/cdn/app/file/netmera.com/series/img-48/1372262272227_89/medium";
try {
Bitmap bmp = BitmapFactory.decodeStream(new URL(url)
.openConnection().getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You are running network related operation on the ui thread using runOnUiThread.
You should use a Thread or use Asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
You are probably getting NetworkOnMainThreadException
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
Load asynctask on ui thread.
new TheTask().execute().
AsyncTask
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "http://netmera.com/cdn/app/file/netmera.com/series/img-48/1372262272227_89/medium";
try {
Bitmap bmp = BitmapFactory.decodeStream(new URL(url)
.openConnection().getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
Use runOnUiThread to update ui and do your netowrk related operation in doInbackground().
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
// update ui
}
});
bitmap = BitmapFactory.decodeStream((InputStream) new URL("your url").getContent());
The reason for the Crash can be two things
Network operation should not be done on the UI thread. Kindly use AsyncTask for this. //NetworkOnMainThreadException
Do not use strong referneces for Bitmaps. Use WeakReference<Bitmap> objects //OutOfMemoryException
I am doing it like this
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what==1){
doctoImage.setImageBitmap(bitmap);// doctoImage you image view
}
}
};
Thread thread = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
doctor.getPhoto()).getContent());
handler.sendEmptyMessage(1);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});thread.start();
Related
I defined connection variable in top of the main class:
private XMPPConnection connection;
I am connecting to server with following code:
public void connect(final String username,final String password) {
Thread t=new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig=new ConnectionConfiguration("server ip", 5222,"localhost");
XMPPConnection connection=new XMPPTCPConnection(connConfig);
try{
connection.connect();
}catch(XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username,password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setConnection(connection);
}
});
t.start();
}
You see I am using thread for this operation.And if connection was successful setConnection method is calling.
setConnection method:
public void setConnection(XMPPConnection connection) {
this.connection=connection;
if (connection != null) {
//Other stuff
....
So,I am setting connection variable inside thread.But when I want to disconnect from server i am getting crash report.
Disconnect code:
try{
connection.disconnect();
}catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Report:
01-27 14:14:05.162: E/XMPPConnection(3160): Error in listener while closing connection
01-27 14:14:05.162: E/XMPPConnection(3160): android.os.NetworkOnMainThreadException
01-27 14:14:05.162: E/XMPPConnection(3160): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.getLocalHost(InetAddress.java:365)
01-27 14:14:05.162: E/XMPPConnection(3160): at org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy.<init>(Socks5Proxy.java:108)
I know this error.Android doesn't allow to use network operations from ui thread.But I already set connection inside another thread.Why do i need one more thread for disconnect operation ?
I followed this tutorial:http://developer.samsung.com/technical-doc/view.do?v=T000000119
And in this tutorial they didn't use another thread for disconnect.Why I am getting this error ?
Using you code which you have posted. define strict mode thread policy permission in onCreate method of Activity or Application
Assuming you have given INTERNET permission in manifest
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
If you dont wants to use the code which you have posted thn alternate solutions for that below i hve mentioned
Use Async task for the Network related operation or long process related
public class MyActivity extends Activity {
XMPPConnection connection;
private String username;
private String password;
public void connect(final String username, final String password) {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class XMPPConnection extends AsyncTask<Void, Void, Void> {
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... params) {
connect(username, password);
return null;
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// from here update the ui and make ui related changes once
// onpostExecute is called
setConnection(connection);
}
}
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.test_layout);
username = "username#chat.abc.com";
password = "1234567";
new XMPPConnection().execute();
}
}
also Please check this
For async and ui changes , network related operation on main thread related please check this
and make sure setConnection(XMPPConnection connection) you are not doing any UI update related things..
OR you can also try
XMPPTCPConnection connection;
#Override
protected void onResume() {
super.onResume();
connect(LOGGED_USERNAME,"pass");
}
#Override
public void onPause() {
super.onPause();
try{
connection.disconnect();
}catch (SmackException e) {
e.printStackTrace();
}
}
private Handler handler = new Handler() {
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
setConnection(connection);
}
};
public void connect(final String username, final String password) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessageAtTime(0, 1000);
}
});
t.start();
}
public void setConnection(XMPPTCPConnection connection) {
this.connection=connection;
if (connection != null) {
....
This is an issue in proccess dialog in async task
I search a lot for finding the reason of proccessDialog in Async task is SlowDown speed of what you put in doInBackground.
Can anyone say why its occuring...
Below is my code
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Asycdialog = new ProgressDialog(Server_connection.this);
Asycdialog.setMessage("Checking Connection.......");
Asycdialog.setCanceledOnTouchOutside(false);
Asycdialog.show();
field_res_partner = mf.fields_res_partner();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OVersionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
sync_data_server.Search_read(Server_connection.this, "res.partner",
field_res_partner);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Asycdialog.dismiss();
// Intent intent = new Intent(Server_connection.this,
// SplashMenu.class);
// startActivity(intent);
}
use
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
to update your progress and :
publishProgress (Progress... values)
to send updating status to the progress
here
I follow one manual to upload images from Android to FTP. If I try to update a photo that have taken I can't see anything on the FTP file. It creates and the size is ok, but contains nothing. Then i try to upload one little image and this is the result:
(Random image to upload)
(Image uploaded)
The code: `class Sender extends AsyncTask
{
File photo;
public Sender(File photo){
this.photo=photo;
}
protected String doInBackground(String... params)
{
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(InetAddress.getByName("ftp.fercode.com"));
ftpClient.login(xxx","xxx");
Boolean result = ftpClient.changeWorkingDirectory("/img");
Log.e("existeix carpeta?",result.toString() );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream srcFileStream=null;
try {
srcFileStream = new FileInputStream(photo.getAbsolutePath());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//ftpClient.stor(photo.getAbsolutePath());
boolean status = ftpClient.storeFile("/img/imagePrueba.jpeg",
srcFileStream);
Log.e("Status", String.valueOf(status));
srcFileStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}`
What I'm doing wrong? Thx a lot
That happens because I upload the image like ASCII and not binary. It's just a configuration parameter:
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
I am using FTP to upload a file. This works great. This file contains information what the app should do.
So I am doing the following:
1) Download the file with Apache FTP Client (seems to work fine)
2) Try to read out the file with a BufferedReader and FileReader.
The problem:
I get a NullPointerException while reading the file. I guess that this is a timing problem.
The code has this structure:
...
getFile().execute();
BufferedReader br = new BufferedReader(...);
How can I solve this problem?
I have to use a seperate Thread (AsyncTask) to download the file because otherwise it will throw a NetworkOnMainThread Exception.
But how can I wait until the file is completely downloaded without freezing the UI?
I cannot use the BufferedReader inside AsyncTask because I use GUI elements and I have to run the interactions on the GUI Thread, but I have no access to it from AsyncTask. RunOnUiThread does not work as well because I am inside a BroadcastReceiver.
Some code:
private class GetTask extends AsyncTask{
public GetTask(){
}
#Override
protected Object doInBackground(Object... arg0) {
FTPClient client = new FTPClient();
try {
client.connect("*****");
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
client.login("*****", "*****");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream( "/sdcard/"+userID+".task" );
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
resultOk &= client.retrieveFile( userID+".task", fos );
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}/**
try {
client.deleteFile(userID+".task");
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
**/
try {
client.disconnect();
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
return null;
}
}
The Broadcastreceiver class:
public class LiveAction extends BroadcastReceiver {
...
private Context cont;
FileReader fr = null;
BufferedReader br;
#Override
public void onReceive(Context context, Intent intent)
{
cont = context;
...
new GetTask().execute();
try {
Thread.sleep(3000);
}
catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fr = new FileReader("/sdcard/"+userID+".task");
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
br = new BufferedReader(fr)
String strline = "";
try {
while ((strline = br.readLine()) != null){
if(strline.equals("taskone")){
//Some GUI Tasks
}
....
This is the relevant code.
I think the best approach would be to read the file's contents from the doInBackground inside the AsyncTask and then output an object which contains the info you need on the onPostExecute method of the async stask and then manipulate your UI.
private AsyncTask<String,Void,FileInfo> getFile(){
return new AsyncTask<String,Void,FileInfo>{
protected FileInfo doInBackground(String url){
FileInfo finfo = new FileInfo(); // FileInfo is a custom object that you need to define that has all the stuff that you need from the file you just downloaded
// Fill the custom file info object with the stuff you need from the file
return finfo;
}
protected void onPostExecute(FileInfo finfo) {
// Manipulate UI with contents of file info
}
};
}
getFile().execute();
Another option is to call another AsyncTask from onPostExecute that does the file parsing but I would not recommend it
I would try some thing like this:
private class GetTask extends AsyncTask{
LiveAction liveAction;
public GetTask(LiveAction liveAction){
this.liveAction = liveAction;
}
...
#Override
protected void onPostExecute(String result) {
liveAction.heyImDoneWithdownloading();
}
}
Ps: why the Thread.sleep(5000)?
public class LiveAction extends BroadcastReceiver {
...
public void heyImDoneWithdownloading(){
//all the things you want to do on the ui thread
}
}
I try to create a client server socket beetwen my droid(client) and my PC(server), when i am in local(over wifi) it work perfectely, but when il try over 3G i get this exception when the server try to get clientsocket.getOutputStream()
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
What's the probleme, do eny one know the solution of this?
help please :-(
The Server
public class Server {
ServerSocket serverSocket;
public LinkedBlockingQueue<CDRecCourseDisplay> recCours;
public LinkedList<ClientMail> clientMails;
static Server server;
public static Server getInstance(){
if(server == null){
server = new Server();
}
return server;
}
Server() {
// TODO Auto-generated constructor stub
try {
serverSocket = new ServerSocket(54444);
recCours = new LinkedBlockingQueue<CDRecCourseDisplay>(10);
clientMails = new LinkedList<ClientMail>();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.start();
}
private void start(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true){
try {
Socket socket = serverSocket.accept();
new Thread(new Client(socket)).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public Client(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
if(socket == null) return;
try {
InputStream i = socket.getInputStream();
OutputStream o = socket.getOutputStream();
in = new DataInputStream(i);
out = new DataOutputStream(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test Message");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
Log.d("MESSAGE", buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
}
and the client
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public void run() {
// TODO Auto-generated method stub
boolean conected = false;
while(!conected){
try {
Thread.sleep(500);
socket = new Socket("213.233.216.25", 54444);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
conected = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
}
}
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
log.d("MESSAGE", buf);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test message from the phone");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
Most networks (Wifi and 3G) use NAT. NAT allows outbound connections, but prevents inbound (internet to device) connections.
When your server and device are both on the same network, as in your case, then this works as you are not traversing NAT gateway.
Rationale: what you are trying to do (connecting from internet to device) will not work in most networks.