I am trying to get the MAC address of my android device without relying on myWifiInfo.getMacAddress()
Following is the code I use:
try{
InetAddress inet = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(inet);
byte[] address = ni.getHardwareAddress();
}
catch(Exception e){
Log.d("MyActivity",e.toString());
}
I get the following exception:
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.rethrowAsSocketException(NetworkInterface.java:212)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:178)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.getByName(NetworkInterface.java:118)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.getNetworkInterfacesList(NetworkInterface.java:270)
08-01 06:10:56.239: WARN/System.err(23164): at java.net.NetworkInterface.getByInetAddress(NetworkInterface.java:228)
08-01 06:10:56.239: WARN/System.err(23164): at com.example.MyActivity$MyAsyncTask.doInBackground(MyActivity.java:82)
08-01 06:10:56.247: WARN/System.err(23164): at com.example.MyActivity$MyAsyncTask.doInBackground(MyActivity.java:43)
08-01 06:10:56.247: WARN/System.err(23164): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-01 06:10:56.247: WARN/System.err(23164): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-01 06:10:56.247: WARN/System.err(23164): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-01 06:10:56.247: WARN/System.err(23164): at java.lang.Thread.run(Thread.java:856)
08-01 06:10:56.247: WARN/System.err(23164): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
08-01 06:10:56.247: WARN/System.err(23164): at libcore.io.Posix.socket(Native Method)
08-01 06:10:56.247: WARN/System.err(23164): at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
08-01 06:10:56.247: WARN/System.err(23164): at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:163)
08-01 06:10:56.247: WARN/System.err(23164): ... 12 more
I have given the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The exception is thrown from the following line in the code above:
NetworkInterface ni = NetworkInterface.getByInetAddress(inet);
When I log the inet address, I get the same as localhost/127.0.0.1
Can someone please point out the reason for this issue and the solution for the same?
Any help is much appreciated
You can also try following Bluetooth API code to get the MAC address,
private BluetoothAdapter btAdapther;
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
String deviceMacAddress = mBtAdapter.getAddress();
Permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
You can read /sys/class/net/eth0/address as a text file and this file contains the ethernet-MAC-address of eth0 interface, if your device have ethernet hardware.
Sample code may help you:
public String getMac()
{
StringBuffer fileData = new StringBuffer(1000);
try {
BufferedReader reader = new BufferedReader(new FileReader("/sys/class/net/eth0/address"));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getMacAddressFromEtcFile(){
try {
return loadFileAsString("/sys/class/net/eth0/address").toUpperCase().substring(0, 17);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static String loadFileAsString(String filePath) throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while((numRead = reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
Related
I am using wifi direct to send file between two android phones.
sender code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
outputStream = socket.getOutputStream();
inputStream = new FileInputStream(exportTempFile);
byte[] buf = new byte[socket.getSendBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
return 0;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
receiver code:
OutputStream outputStream = null;
InputStream inputStream = null;
try {
tempDir = new File(context.getCacheDir(), "temp");
if (!tempDir.exists()) {
tempDir.mkdir();
}
File file = new File(tempDir, "temp.zip");
file.createNewFile();
outputStream = new FileOutputStream(file);
inputStream = socket.getInputStream();
byte[] buf = new byte[socket.getReceiveBufferSize()];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
outputStream.flush();
}
return file;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
However, I always get "W/System.err" at the receiver side when running bytestream.copy . I wonder if I did something wrong. Did I close socket too early so the other side can not get data?
error is as below:
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
10-15 17:13:50.162 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:420)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at cc.megaman.led.service.ImportManager$ImportTask.doInBackground(ImportManager.java:377)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-15 17:13:50.172 13921-14306/cc.megaman.led W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:140)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
10-15 17:13:50.182 13921-14306/cc.megaman.led W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
I need to write the registration credentials into a file during registration and during login will check that file for credentials. but on registration button click nothing is performing.
Manifest file contains this permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
the registration.java part:
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String user=username.getText().toString();
String pwd=password.getText().toString();
String cpwd=confirm.getText().toString();
if(user.equals("")||pwd.equals("")||cpwd.equals("")){
Toast.makeText(getApplicationContext(), "Fields cannot be Blank", Toast.LENGTH_SHORT).show();
}
else if(pwd.equals(cpwd)){
String data=user+","+pwd+":";
try {
FileOutputStream fout = new FileOutputStream(Environment.getExternalStorageDirectory()+"/myapp/userregister.txt/", true);
fout.write(data.getBytes());
Toast.makeText(getApplicationContext(), "Succesfully Register", Toast.LENGTH_SHORT).show();
Intent a=new Intent(getApplicationContext(),LoginActivity.class);
startActivity(a);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(!pwd.equals(cpwd)){
Toast.makeText(getApplicationContext(), "Password not match.. Try again!", Toast.LENGTH_SHORT).show();
}
}
});
In LoginActivity.java
if(username.equals("") || password.equals("")){
Toast.makeText(getApplicationContext(), "Fields Cannot be Blank", Toast.LENGTH_SHORT).show();
}else{
String reply=FileManipulator.authenticateUser(username, password);
if(reply.equals("user")){
Intent gotoNextActivity=new Intent(getApplicationContext(),HomeActivity.class);
startActivity(gotoNextActivity);
}else{
Toast.makeText(getApplicationContext(), "Invalid User.... Try again",Toast.LENGTH_SHORT).show();
}
}
FileManipulator class authenticateUser function:
public static String authenticateUser(String user, String pass){
String data="";
String data1 = "";
try{
FileInputStream fin=new FileInputStream(Path.userregister);
byte[] b=new byte[fin.available()];
fin.read(b);
data=new String(b);
String st=user+","+pass+":";
if(data.contains(st)){
data1="user";
}
}catch(Exception e){
e.printStackTrace();
}
return data1;
}
The log cat shows
09-02 05:48:06.292: D/dalvikvm(1964): GC_CONCURRENT freed 240K, 12% free 2838K/3200K, paused 5ms+32ms, total 177ms
09-02 05:48:06.802: I/Choreographer(1964): Skipped 36 frames! The application may be doing too much work on its main thread.
09-02 05:48:10.362: I/Choreographer(1964): Skipped 32 frames! The application may be doing too much work on its main thread.
09-02 05:48:20.872: W/System.err(1964): java.io.FileNotFoundException: /mnt/sdcard/myapp/userregister.txt: open failed: EACCES (Permission denied)
09-02 05:48:20.872: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:416)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
09-02 05:48:20.882: W/System.err(1964): at com.example.text.RegActivity$1.onClick(RegActivity.java:49)
09-02 05:48:20.892: W/System.err(1964): at android.view.View.performClick(View.java:4204)
09-02 05:48:20.892: W/System.err(1964): at android.view.View$PerformClick.run(View.java:17355)
09-02 05:48:20.902: W/System.err(1964): at android.os.Handler.handleCallback(Handler.java:725)
09-02 05:48:20.912: W/System.err(1964): at android.os.Handler.dispatchMessage(Handler.java:92)
09-02 05:48:20.912: W/System.err(1964): at android.os.Looper.loop(Looper.java:137)
09-02 05:48:20.912: W/System.err(1964): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invokeNative(Native Method)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invoke(Method.java:511)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-02 05:48:20.922: W/System.err(1964): at dalvik.system.NativeStart.main(Native Method)
09-02 05:48:20.932: W/System.err(1964): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.Posix.open(Native Method)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
09-02 05:48:20.952: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:400)
09-02 05:48:20.952: W/System.err(1964): ... 14 more
I'm a newbie to android and java..please help me to find the error.
1) Add android.permission.WRITE_EXTERNAL_STORAGE in AndroidManifest.xml file.
2) Always check for the availability of external storage before writing/reading by :
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
} else {
// Can't read or write
}
3) Create a directory, then make your file in it.
File dir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp");
dir.mkdirs();
File file = new File(dir, "userregister.txt");
NOTE :
If you are using Android 4.4 KitKat, Apps are not allowed to write to secondary external storage devices, except in their package-specific directories
The reason from http://source.android.com/devices/tech/storage/index.html
The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.
i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}
I have this doInBackground method which records audio streams from the internet. The main work is being done inside while (len != -1) { }. This works fine however the buffer = new byte[] doesn't work as I expected - when the connection is interrupted the IOException is called immidiately and the buffer is not used anymore. How can I make this buffer to "feed" my code till it is empty? I want to have the same behavior like it is in audio players; so first when you connect to the stream (it is buffering), then playing and if the connection is interrupted it is still playing from the buffer (till it is empty).
Recorder:
protected Boolean doInBackground(String... StringUrls) {
boolean fdetermined = false;
Environment env = new Environment();
Calendar c = Calendar.getInstance();
BufferedOutputStream bufOutstream = null;
buffer = new byte[1024 * 10];
int len=-1;
InputStream in = null;
URLConnection conn = null;
try{
conn = new URL(StringUrls[0]).openConnection();
conn.setConnectTimeout(5000);
in = conn.getInputStream();
len = in.read(buffer);
File dir = new File(env.getExternalStorageDirectory() + "/somewhere");
if (!dir.exists()) {
dir.mkdir();
}
filename = env.getExternalStorageDirectory()+"/somewhere/file";
bufOutstream = new BufferedOutputStream(new FileOutputStream(new File(filename)));
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
}
}
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
IO Exception:
12-16 14:37:16.999 31950-32021/com.app.example W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.059 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:542)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
12-16 14:37:17.109 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
12-16 14:37:17.119 31950-32021/com.app.example W/System.err﹕ at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at libcore.net.http.UnknownLengthHttpInputStream.read(UnknownLengthHttpInputStream.java:41)
12-16 14:37:17.149 31950-32021/com.app.example W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:376)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at com.app.example.Recorder$RecordTask.doInBackground(Recorder.java:288)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-16 14:37:17.189 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)
12-16 14:37:17.199 31950-32021/com.app.example W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:131)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
12-16 14:37:17.209 31950-32021/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:503)
I have added finally block below:
while (len != -1) {
if(in != null && buffer != null && bufOutstream != null) {
try {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) {
Recorder.this.stopSelf();
break;
}
} catch (IOException e) {
e.printStackTrace();
conn = null;
in = null;
}
finally{
//do your work here. This block will execute no matter of what exception is thrown
try{
if(bufOutstream != null) {
bufOutstream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Hello i'm new to android development and this is my first app. I try to connect to a database but when the emulator starts the application stops unexpectedly. Everything in eclipse is fine but when i run the emulator it stops. Here is the code:
public class Antallaktika extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
String targetname;
String targetsku;
String targetprice;
int responseCode;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.antallaktika);
setTitle("Ανταλλακτικά");
try {
URL url = new URL("http://machina.gr/antallaktika.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
}
catch (Exception e) {}
try{
if(isNetworkAvailable()==true && responseCode == HttpURLConnection.HTTP_OK){
new LoadData().execute();
}
else{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
}
catch(Exception e){
}
}
public class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(Antallaktika.this, ""," Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try{
ListView listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Antallaktika.this,al.toArray(new String[al.size()]),al1.toArray(new String[al1.size()]),al2.toArray(new String[al2.size()])));
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://machina.gr/antallaktika.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
targetname=json_data.getString("targetname");
targetsku=json_data.getString("targetsku");
targetprice = json_data.getString("targetprice");
al.add(targetname);
al1.add(targetsku);
al2.add(targetprice);
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
and the logcat is:
08-01 20:51:36.042: E/AndroidRuntime(375): FATAL EXCEPTION: AsyncTask #1
08-01 20:51:36.042: E/AndroidRuntime(375): java.lang.RuntimeException: An error occured while executing doInBackground()
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.lang.Thread.run(Thread.java:1019)
08-01 20:51:36.042: E/AndroidRuntime(375): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.Handler.<init>(Handler.java:121)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.widget.Toast.<init>(Toast.java:68)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.widget.Toast.makeText(Toast.java:231)
08-01 20:51:36.042: E/AndroidRuntime(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:161)
08-01 20:51:36.042: E/AndroidRuntime(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:1)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-01 20:51:36.042: E/AndroidRuntime(375): ... 4 more
08-01 20:51:37.142: E/WindowManager(375): Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375): android.view.WindowLeaked: Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375): at android.view.ViewRoot.<init>(ViewRoot.java:258)
08-01 20:51:37.142: E/WindowManager(375): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-01 20:51:37.142: E/WindowManager(375): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-01 20:51:37.142: E/WindowManager(375): at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-01 20:51:37.142: E/WindowManager(375): at android.app.Dialog.show(Dialog.java:241)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:107)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:90)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:85)
08-01 20:51:37.142: E/WindowManager(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.onPreExecute(Antallaktika.java:85)
08-01 20:51:37.142: E/WindowManager(375): at android.os.AsyncTask.execute(AsyncTask.java:391)
08-01 20:51:37.142: E/WindowManager(375): at com.pythagoras.machina.gr.Antallaktika.onCreate(Antallaktika.java:67)
08-01 20:51:37.142: E/WindowManager(375): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-01 20:51:37.142: E/WindowManager(375): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 20:51:37.142: E/WindowManager(375): at android.os.Looper.loop(Looper.java:130)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 20:51:37.142: E/WindowManager(375): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 20:51:37.142: E/WindowManager(375): at java.lang.reflect.Method.invoke(Method.java:507)
08-01 20:51:37.142: E/WindowManager(375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 20:51:37.142: E/WindowManager(375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 20:51:37.142: E/WindowManager(375): at dalvik.system.NativeStart.main(Native Method)
you are trying to access UI functionality from a thread other than the UI thread (i guess it is the Toast). that is not possible. see here for info on how to run code on the UI thread.