I am establishing server-client communication between Android app and ESP8266 NodeMCU-1.0. The ESP is creating server on specified network and the mobile is connecting to same network.
For testing purpose I am sending "try123" string when the send button is pressed. And receiving appropriate response on the serial monitor of IDE (i.e. data is received on server). But the server response which is "Test_successful" string. I am sending this string to client using client.print. In app I am toasting the server response.
The problem is that if I am making the HTTP request using browser using the locally generated URL, then the response "Test_successful" is visible. But In app toast it's showing empty and while debugging it's showing error Unexpected line status.
ESP code (server side):
#include <ESP8266WiFi.h>
const char* ssid = "DARSHAN95";
const char* password = "12345678";
//const char* ssid = "TP-LINK_42C148";
//const char* password = "";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
// Match the request
//client.flush();
delay(100);
// Send the response to the client
client.print("Test_Sucessfull");
delay(200);
Serial.println("Client disonnected");
}
Android App code:
Please ignore the text input block on the and its code.
package com.example.access.test123;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
EditText Message;
Button Send;
String data;
HttpURLConnection http;
String sendingMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Message = (EditText) findViewById(R.id.message);
Send = (Button) findViewById(R.id.send);
Send.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
HttpAsync task = new HttpAsync();
task.execute();
}
});
}
public void sendDataMethod() throws UnsupportedEncodingException{
sendingMessage = Message.getText().toString();
String data = "Error";
BufferedReader reader = null;
//Sending Data
try{
String ip = "http://192.168.43.76/?try123";
//String address = ip + sendingMessage;
//URL url = new URL(address);
URL url = new URL(ip);
URLConnection conn = url.openConnection();
http = (HttpURLConnection)conn;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);
http.setDoInput(true);
//Server Response
int i = http.getResponseCode();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
data = sb.toString();
}
catch(IOException e){;
Log.d("Error2", e.toString());
}
finally {
try{
if(reader != null) {
reader.close();
}
}
catch (IOException ex){
Log.d("Error3", ex.toString());
}
}
}
private class HttpAsync extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object[] objects) {
try {
sendDataMethod();
}
catch (UnsupportedEncodingException e) {
Log.d("Error", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
}
}
Debugging results:
02/07 22:40:23: Launching app
$ adb install-multiple -r -t A:\New folder\Test123\app\build\intermediates\split-apk\debug\dep\dependencies.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_1.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_2.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_3.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_6.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_9.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_8.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_7.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_4.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_5.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_0.apk A:\New folder\Test123\app\build\outputs\apk\debug\app-debug.apk
Split APKs installed
$ adb shell am start -n "com.example.access.test123/com.example.access.test123.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Connecting to com.example.access.test123
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1436)
W/System: ClassLoader referenced unknown path: /data/app/com.example.access.test123-2/lib/arm64
I/art: Starting a blocking GC HeapTrim
I/InstantRun: starting instant run server: is main process
I/art: Starting a blocking GC Instrumentation
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = null, this = DecorView#3280086[]
D/WindowClient: Add to mViews: DecorView#3280086[MainActivity], this = android.view.WindowManagerGlobal#d5cc9ee
D/OpenGLRenderer: Dumper init 4 threads <0x7c6a19ee40>
D/OpenGLRenderer: <com.example.access.test123> is running.
D/OpenGLRenderer: CanvasContext() 0x7c6773f880
D/ViewRootImpl[MainActivity]: hardware acceleration is enabled, this = ViewRoot{500151c com.example.access.test123/com.example.access.test123.MainActivity,ident = 0}
V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{500151c com.example.access.test123/com.example.access.test123.MainActivity,ident = 0}, this = DecorView#3280086[MainActivity]
D/OpenGLRenderer: CanvasContext() 0x7c6773f880 initialize window=0x7c73e55e00, title=com.example.access.test123/com.example.access.test123.MainActivity
D/Surface: Surface::allocateBuffers(this=0x7c73e55e00)
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/OpenGLRenderer: Created EGL context (0x7c6a19f600)
D/OpenGLRenderer: ProgramCache.init: enable enhancement 1
I/OpenGLRenderer: Get disable program binary service property (0)
I/OpenGLRenderer: Initializing program atlas...
I/ProgramBinary/Service: ProgramBinaryService client side disable debugging.
I/ProgramBinary/Service: ProgramBinaryService client side disable binary content debugging.
D/ProgramBinary/Service: BpProgramBinaryService.getReady
D/ProgramBinary/Service: BpProgramBinaryService.getProgramBinaryData
I/OpenGLRenderer: Program binary detail: Binary length is 249276, program map length is 124.
I/OpenGLRenderer: Succeeded to mmap program binaries. File descriptor is 74, and path is /dev/ashmem.
I/OpenGLRenderer: No need to use file discriptor anymore, close fd(74).
D/OpenGLRenderer: Initializing program cache from 0x0, size = -1
D/MALI: eglCreateImageKHR:513: [Crop] 0 0 896 1344 img[896 1344]
D/Surface: Surface::connect(this=0x7c73e55e00,api=1)
W/libEGL: [ANDROID_RECORDABLE] format: 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/OpenGLRenderer: CacheTexture 3 upload: x, y, width height = 0, 0, 189, 441
D/OpenGLRenderer: ProgramCache.generateProgram: 0
D/OpenGLRenderer: ProgramCache.generateProgram: 34359738371
D/OpenGLRenderer: ProgramCache.generateProgram: 5242945
D/OpenGLRenderer: ProgramCache.generateProgram: 5242944
D/OpenGLRenderer: ProgramCache.generateProgram: 240518168576
D/OpenGLRenderer: ProgramCache.generateProgram: 68724719680
V/InputMethodManager: onWindowFocus: android.support.v7.widget.AppCompatEditText{8687c92 VFED..CL. .F....ID 228,66-851,212 #7f070042 app:id/message} softInputMode=288 first=true flags=#81810100
D/OpenGLRenderer: ProgramCache.generateProgram: 103084458052
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: [socket][0] connection /192.168.43.76:80;LocalPort=-1(0)
[ 02-07 22:40:39.251 29396:29665 D/ ]
[Posix_connect Debug]Process com.example.access.test123 :80
I/System.out: [socket][/192.168.43.1:49348] connected
I/System.out: [OkHttp] sendRequest>>
I/System.out: [OkHttp] sendRequest<<
D/Error2: java.net.ProtocolException: Unexpected status line: Test_Sucessfull
D/WindowClient: Add to mViews: android.widget.LinearLayout{3957537 V.E...... ......I. 0,0-0,0}, this = android.view.WindowManagerGlobal#d5cc9ee
D/OpenGLRenderer: CanvasContext() 0x7c56092d40
D/ViewRootImpl[Toast]: hardware acceleration is enabled, this = ViewRoot{f7a400d Toast,ident = 1}
D/Surface: Surface::allocateBuffers(this=0x7c58339e00)
D/OpenGLRenderer: CanvasContext() 0x7c56092d40 initialize window=0x7c58339e00, title=Toast
D/Surface: Surface::connect(this=0x7c58339e00,api=1)
W/libEGL: [ANDROID_RECORDABLE] format: 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
D/OpenGLRenderer: ProgramCache.generateProgram: 1
D/Surface: Surface::disconnect(this=0x7c58339e00,api=1)
D/Surface: Surface::disconnect(this=0x7c58339e00,api=1)
D/WindowClient: Remove from mViews: android.widget.LinearLayout{3957537 V.E...... ......ID 0,0-156,140}, this = android.view.WindowManagerGlobal#d5cc9ee
I/art: Do partial code cache collection, code=28KB, data=28KB
I/art: After code cache collection, code=27KB, data=28KB
I/art: Increasing code cache capacity to 128KB
Note: At D/Error2: java.net.ProtocolException: Unexpected status line: Test_Sucessfull
The string is received but with above error.
Results:
IDE monitor displaying data sent from client i.e. app
Finally Found the solution, the error was with the syntax of the response packet sent from ESP side
so just replaced
client.print("Test_Successfull");
with
client.print("HTTP/1.1 200 OK\r\nConnection: Closed\r\n\r\nTest_Successful");
Related
Trying Android development after some time, I am trying to download a zip file from FTP but even after repeat tries, still get FileNotFound Exception when i try to write the file in FileOutputStream. The file clearly exists on local storage as I am printing it 2-3 times (please check output log)
MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.apache.commons.net.ftp.FTPFile;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "";
Spinner drop;
Button btn;
String[] items;
FTPFile[] file;
ArrayAdapter adapter;
ProgressDialog mProgressDialog;
String dwnFile = "";
String localFilePath;
File localFile;
FTPOps ftp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
drop = (Spinner) findViewById(R.id.spinner);
items = new String[]{"hello"};
String path = Environment.getExternalStorageDirectory().toString();
System.out.println("Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
}
items = new String[]{"Select the file", "01.zip", "04.zip", "05.zip", "06.zip", "07.zip", "08.zip", "09.zip",};
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, items);
drop.setAdapter(adapter);
btn.setOnClickListener(v -> {
dwnFile = drop.getSelectedItem().toString().equals("Select the file") ? "" : drop.getSelectedItem().toString();
if (dwnFile != "") {
Context context = this;
localFilePath = Environment.getExternalStorageDirectory() + "/" + "ebooks";
localFile = new File(localFilePath + "/" + dwnFile);
System.out.println(localFile.mkdir() ? "File created" : "Not created file");
if (localFile.exists()) {
System.out.println("File created");
} else {
System.out.println("File edxists already");
}
System.out.println(localFile.getPath());
Toast toast = Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_LONG);
toast.show();
ftp = new FTPOps(localFile, context, dwnFile);
String msg = (ftp.runDownloadAndUnziping()) ? "Downloaded" : "Error in downloding";
toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
}
The Mainactivity gives a drop down to select from list of files and sends the data to another class for FTP downlaod.
FTPOps.java
package com.example.myapplication;
import android.content.Context;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FTPOps {
File localFile;
Context context;
FTPClient ftp;
String fileName;
public FTPOps(File localFile, Context context, String dwnFile) {
this.localFile = localFile;
this.context = context;
ftp = new FTPClient();
this.fileName = dwnFile;
}
public boolean runDownloadAndUnziping() {
setUpFTP();
return true;
}
private void setUpFTP() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ftp.connect("some$$$$url");
ftp.login("someID", "somePassword");
showToast("Login into FTP Successful");
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("Downlaod in progress for " + fileName);
System.out.println("Local file is " + localFile.getPath());
FileOutputStream fo = new FileOutputStream(localFile.getPath());
if (fo == null) {
System.out.println("fo is null");
}
boolean r = ftp.retrieveFile(fileName, fo);
if (r) {
System.out.println("Operation success");
}
fo.close();
} catch (IOException e) {
e.printStackTrace();
showToast("Login Failed");
}
}
private void showToast(String msg) {
System.out.println(msg);
}
});
t.start();
}
}
My Output log:
06/13 01:13:00: Launching 'app' on Nexus 6 API 30.
Install successfully finished in 1 s 683 ms.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 13263 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
I/System.out: Path: /storage/emulated/0
I/System.out: Android
Music
Podcasts
Ringtones
Alarms
Notifications
Pictures
Movies
I/System.out: Download
DCIM
Audiobooks
Documents
D/HostConnection: HostConnection::get() New Host Connection established 0xf24e9f30, tid 13290
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf24ead30: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xf24ead30: ver 2 0 (tinfo 0xf28370f0) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xf24ea390, tid 13290
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3f9d95000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2
I/Choreographer: Skipped 40 frames! The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=760ms; Flags=0, IntendedVsync=24852661746550, Vsync=24853328413190, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=24853340948720, AnimationStart=24853340988320, PerformTraversalsStart=24853341581320, DrawStart=24853343717920, SyncQueued=24853344351620, SyncStart=24853344908520, IssueDrawCommandsStart=24853345141720, SwapBuffers=24853352646720, FrameCompleted=24853423084920, DequeueBufferDuration=981700, QueueBufferDuration=1455800, GpuCompleted=0,
W/e.myapplicatio: Accessing hidden field Landroid/widget/AbsListView;->mIsChildViewEnabled:Z (greylist, reflection, allowed)
D/OpenGLRenderer: endAllActiveAnimators on 0xec08c3d0 (DropDownListView) with handle 0xc3041870
I/System.out: Not created file
I/System.out: File edxists already
I/System.out: /storage/emulated/0/ebooks/06.zip
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10155; state: ENABLED
I/System.out: Login into FTP Successful
I/System.out: Downlaod in progress for 06.zip
***I/System.out: Local file is /storage/emulated/0/ebooks/06.zip***
**W/System.err: java.io.FileNotFoundException: /storage/emulated/0/ebooks/06.zip: open failed: ENOENT (No such file or directory)**
at libcore.io.IoBridge.open(IoBridge.java:492)
at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:125)
at com.example.myapplication.FTPOps$1.run(FTPOps.java:50)
at java.lang.Thread.run(Thread.java:923)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
... 4 more
I/System.out: Login Failed
I remember earlier the download used to work like this, but I read some posts about storage access issues, so I updated my manifest appropriately with:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
android:requestLegacyExternalStorage="true">
But result is same.
Now I need help in understanding:
Why do I get FileNotFoundException when file exists, as It can be seen printed on screen just before it crashes
Even the Toast which I remember used to work earlier is not working at all in MainActivity.java
Also I need to unzip the downloaded file, if anyone has a better suggestion for a new library or it still works the old way ?
This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 2 years ago.
Iam making a weather app but whenever Iam not entering or entering wrong city name in EditText the app crashes even though I have used try and catch blocks for error handling.The below is the java,xml code and the logs where it is showing a runtime error.
Java
package com.atul.whatstheweather;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView weatherInfo;
public class Content extends AsyncTask<String, Void ,String>
{
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherData = jsonObject.getString("weather");
JSONArray array = new JSONArray(weatherData);
for(int i=0;i<array.length();i++)
{
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
weatherInfo.setText("Weather: "+main+"\n\n"+"Description: "+description);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
weatherInfo = (TextView)findViewById(R.id.textView);
}
public void clicked(View view)
{
Content content = new Content();
content.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=c20cea76c84b519d67d4e6582064db92");
Log.i("clicked","is working");
}
}
In the Logs given below it is showing Runtime error
Run Logs
05/03 17:35:25: Launching app
Cold swapped changes.
$ adb shell am start -n "com.atul.whatstheweather/com.atul.whatstheweather.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18757 on device xiaomi-redmi_note_3-9b51ac51
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
W/ResourceType: No package identifier when getting name for resource number 0x00000000
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
I/InstantRun: Instant Run Runtime started. Android package is com.atul.whatstheweather, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AccessibilityManager: current package=com.atul.whatstheweather, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#9df51ef
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce6e4fc
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build : a7823f5, I59a6815413
Build Date : 09/23/16
OpenGL ES Shader Compiler Version: XE031.07.00.00
Local Branch : mybranch22028469
Remote Branch : quic/LA.BR.1.3.3_rb2.26
Remote Branch : NONE
Reconstruct Branch : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
I/clicked: is working
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.atul.whatstheweather, PID: 18757
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:356)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:266)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:60)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
I/Process: Sending signal. PID: 18757 SIG: 9
Application terminated.
App crashes because you are calling Toast in background thread.
Replace your Toast line in catch block Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show(); with :
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
});
Just delete the Toast.makeText
Just wanted to see if anyone could help me out or point me in the right direction. I'm learning how to make a simple music player where the user clicks on list view items and it streams the mp3. There's a play button up top and next and previous song buttons (haven't added seek functionality yet). However it keeps crashing when I select new song. Here's my activity code:
public class AudioActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> musicList;
ArrayAdapter adapter;
MediaPlayer player;
ImageButton prev;
ImageButton play;
ImageButton next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
prev = (ImageButton) findViewById(R.id.previous);
play = (ImageButton) findViewById(R.id.play);
next = (ImageButton) findViewById(R.id.next);
listView = findViewById(R.id.musiclist);
musicList = new ArrayList<>();
musicList.add("song");
musicList.add("song1");
musicList.add("song2");
musicList.add("song3");
musicList.add("song4");
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, musicList);
listView.setAdapter(adapter);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
String url = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
try {
player.stop();
//player.release();
player.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 1:
url = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3";
try {
player.stop();
//player.release();
player.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
player.start();
}
});
}
public void onPlayBtnClicked(){
if(!player.isPlaying())
{
player.start();
}else
{
player.pause();
}
}
}
04/05 00:08:09: Launching app
$ adb shell am start -n "com.example.brads.group08/com.example.brads.group08.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.example.brads.group08.test | com.example.brads.group08
Waiting for application to come online: com.example.brads.group08.test | com.example.brads.group08
Waiting for application to come online: com.example.brads.group08.test | com.example.brads.group08
Connecting to com.example.brads.group08
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/ActivityThread: Application com.example.brads.group08 is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/zygote: Debugger is active
Connected to the target VM, address: 'localhost:8600', transport: 'socket'
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/chatty: uid=10091(com.example.brads.group08) identical 4 lines
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1448)
I/InstantRun: starting instant run server: is main process
D/OpenGLRenderer: HWUI GL Pipeline
[ 04-05 04:08:16.176 10444:10464 D/ ]
HostConnection::get() New Host Connection established 0xa5a26b40, tid 10464
I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/EGL_emulation: eglCreateContext: 0xa5a70f60: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
I/zygote: Do partial code cache collection, code=21KB, data=30KB
I/zygote: After code cache collection, code=21KB, data=30KB
I/zygote: Increasing code cache capacity to 128KB
I/zygote: Do partial code cache collection, code=31KB, data=56KB
I/zygote: After code cache collection, code=31KB, data=56KB
I/zygote: Increasing code cache capacity to 256KB
I/zygote: JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
I/zygote: Do full code cache collection, code=116KB, data=72KB
I/zygote: After code cache collection, code=90KB, data=45KB
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
W/MediaPlayer: Use of stream types is deprecated for operations other than volume control
W/MediaPlayer: See the documentation of setAudioStreamType() for what to use instead with android.media.AudioAttributes to qualify your playback use case
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
D/EGL_emulation: eglMakeCurrent: 0xa5a70f60: ver 2 0 (tinfo 0xa83b2680)
E/MediaPlayerNative: stop called in state 1, mPlayer(0x0)
E/MediaPlayerNative: error (-38, 0)
V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService#89d8a5e): Cookies: null
V/MediaHTTPService: makeHTTPConnection: CookieManager created: java.net.CookieManager#a4007a4
V/MediaHTTPService: makeHTTPConnection(android.media.MediaHTTPService#89d8a5e): cookieHandler: java.net.CookieManager#a4007a4 Cookies: null
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/Choreographer: Skipped 163 frames! The application may be doing too much work on its main thread.
E/MediaPlayer: Error (-38,0)
I/zygote: Do partial code cache collection, code=123KB, data=81KB
I/zygote: After code cache collection, code=123KB, data=81KB
I/zygote: Increasing code cache capacity to 512KB
V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService#7615caf): Cookies: null
E/MediaPlayerNative: attachNewPlayer called in state 64
E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: java.lang.IllegalStateException
at android.media.MediaPlayer.nativeSetDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1172)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1160)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1127)
at com.example.brads.group08.AudioActivity$1.onItemClick(AudioActivity.java:65)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3127)
at android.widget.AbsListView.onTouchUp(AbsListView.java:4054)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3813)
at android.view.View.dispatchTouchEvent(View.java:11776)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2962)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2643)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:448)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1829)
at android.app.Activity.dispatchTouchEvent(Activity.java:3307)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:410)
at android.view.View.dispatchPointerEvent(View.java:12015)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4795)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4609)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4293)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4350)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6661)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6635)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6596)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6764)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:186)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:325)
at android.os.Looper.loop(Looper.java:142)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.brads.group08, PID: 10444
java.lang.IllegalStateException
at android.media.MediaPlayer.nativeSetDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1172)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1160)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1127)
at com.example.brads.group08.AudioActivity$1.onItemClick(AudioActivity.java:65)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3127)
at android.widget.AbsListView.onTouchUp(AbsListView.java:4054)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3813)
at android.view.View.dispatchTouchEvent(View.java:11776)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2962)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2643)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2968)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2657)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:448)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1829)
at android.app.Activity.dispatchTouchEvent(Activity.java:3307)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:410)
at android.view.View.dispatchPointerEvent(View.java:12015)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4795)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4609)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4293)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4350)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6661)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6635)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6596)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6764)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:186)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:325)
at android.os.Looper.loop(Looper.java:142)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
I'm try to play a loading animation on my loading screen, and I read somewhere that android doesn't support gifs so either you have to break in into frames and then play it or we can use the Movie class.
Heres the leading activity -
package com.myapp.mehul.login.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.myapp.mehul.login.MYGIFView;
import com.myapp.mehul.login.MainActivity;
import com.myapp.mehul.login.R;
import com.myapp.mehul.login.app.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/**
* Created by mehul on 2/6/16.
*/
public class LoadingScreen extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 1000;
/** Called when the activity is first created. */
private Socket mSocket;
String you;
String opponentId;
String username;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new MYGIFView(getApplicationContext()));
//initialise the socket
mSocket.connect();
//call add user
mSocket.emit("add user");
//start a listener for opponent
mSocket.on("opponent", onOpponent);
//initialise the username
username = getIntent().getExtras().getString("username");
}
private Emitter.Listener onOpponent = new Emitter.Listener(){
#Override
public void call(final Object... args){
LoadingScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
you = data.getString("you");
opponentId = data.getString("opponent");
Log.d("LoadingScreen", data.toString());
//setResult(RESULT_OK, i);
finish();
} catch (JSONException e) {
return;
}
Intent i = new Intent(LoadingScreen.this, MainActivity.class);
i.putExtra("opponentId", opponentId);
i.putExtra("you", you);
i.putExtra("username", username);
Log.d("goToChat", username);
startActivity(i);
}
});
}
};
#Override
public void onBackPressed(){
AlertDialog.Builder builder = new AlertDialog.Builder(LoadingScreen.this);
builder.setMessage("I knew you didn't have BALLS.").setCancelable(
false).setPositiveButton("I am a LOSER",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//send the logout information to the server
JSONObject discon = new JSONObject();
try {
discon.put("opponent", opponentId);
discon.put("you", you);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSocket.emit("discon", discon);
mSocket.disconnect();
//finish the current activity.
Intent intent = new Intent(LoadingScreen.this, MainMenu.class);
startActivity(intent);
LoadingScreen.this.finish();
}
}).setNegativeButton("I'll fkin face it",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
In the above code I've set content view by passing it an instance of MYGIFView.class -
Heres MYGIFView.class
package com.myapp.mehul.login;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.view.View;
import java.io.InputStream;
/**
* Created by mehul on 2/7/16.
*/
public class MYGIFView extends View{
Movie movie,movie1;
InputStream is=null,is1=null;
long moviestart;
public MYGIFView(Context context) {
super(context);
is=context.getResources().openRawResource(+ R.drawable.loading);
movie=Movie.decodeStream(is);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
long now=android.os.SystemClock.uptimeMillis();
System.out.println("now="+now);
if (moviestart == 0) { // first time
moviestart = now;
}
System.out.println("\tmoviestart="+moviestart);
int relTime = (int)((now - moviestart) % movie.duration()) ;
System.out.println("time="+relTime+"\treltime="+movie.duration());
movie.setTime(relTime);
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
this.invalidate();
}
}
The loading activity IS creating an instance of MYGIFView.class and it logs the data but then it gives fatal signal 11. I tried to search but I didn't get any answer.
console log -
02-07 12:22:30.321 29092-29092/? I/art: Late-enabling -Xcheck:jni
02-07 12:22:30.341 29092-29102/? I/art: Debugger is no longer active
02-07 12:22:30.422 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.422 29092-29092/? D/LoginActivity: already logged in
02-07 12:22:30.425 29092-29092/? I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71360781
02-07 12:22:30.487 29092-29092/? D/MainMenu: painted again
02-07 12:22:30.490 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.554 29092-29149/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-07 12:22:30.559 29092-29092/? D/Atlas: Validating map...
02-07 12:22:30.596 29092-29149/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030_msm8974_LA.BF.1.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 04/15/15 Wed
Local Branch: mybranch9068252
Remote Branch: quic/LA.BF.1.1.1_rb1.19
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030 + NOTHING
02-07 12:22:30.597 29092-29149/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-07 12:22:30.611 29092-29149/? D/OpenGLRenderer: Enabling debug mode 0
02-07 12:22:30.660 29092-29092/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#387f1572 time:71361016
02-07 12:22:31.898 29092-29092/com.myapp.mehul.login D/go to chat: was called
02-07 12:22:31.899 29092-29092/com.myapp.mehul.login I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71362255
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: now=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: moviestart=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: time=0 reltime=1850
02-07 12:22:32.007 29092-29092/com.myapp.mehul.login A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 29092 (app.mehul.login)
02-07 12:22:32.541 29092-29092/com.myapp.mehul.login W/app.mehul.login: type=1701 audit(0.0:302): auid=4294967295 uid=10250 gid=10250 ses=4294967295 subj=u:r:untrusted_app:s0 reason="memory violation" sig=11
I received a batch for this question which means its being viewed a lot, so I'll answer this question -
What I figured out was the line below was throwing the error -
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
Now the problem is that this error specifically can be caused by lots of reasons, its never a specific reason.. the reason mine wasn't working out was because my device didn't work well with hardware acceleration, so I just had to disable it in the manifest application, like this -
<android:hardwareAccelerated="false">
Now its possible that the reason might not be the same....but the core reason is the same, its memory related, and most chances are its a bug in the firmware of the device or emulator you are testing upon.
In the Manifest set in your activity :
<activity
android:name="LoadingScreen"
android:hardwareAccelerated="false">
</activity>
I got here with the exact same problem but in React Native, so I will put a solution for those who need it too. The error may be triggered by react-native-webview and/or React Navigation. In some cases, like me, you don't want to disable Hardware Acceleration on the whole app, so here's a workaround:
react-native-webview
<WebView
androidHardwareAccelerationDisabled
source={source}
/>
React Navigation 5
<NavigationContainer>
<Stack.Navigator initialRouteName="HomeScreen">
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{
animationEnabled: false,
}}
/>
</Stack.Navigator>
</NavigationContainer>
https://github.com/react-native-webview/react-native-webview/issues/575
I can not initiate the bluetooth connection between Java server(using bluecove 2.1.1 on Windows 7 x64, external bluetooth dongle) and Android client(OS version 2.3.6).
Device discovery works normally, but I cannot connect to service running on PC(BluetoothSocket::connect() throw an exception). Below is a very primitive version of server and client(I use MAC address of bluetooth dongle for reducing code length):
Java Server
import java.io.*;
import javax.microedition.io.*;
import javax.bluetooth.*;
public class RFCOMMServer {
public static void main(String args[]) {
try {
StreamConnectionNotifier service = (StreamConnectionNotifier) Connector
.open("btspp://localhost:"
+ new UUID("0000110100001000800000805F9B34FB",
false).toString() + ";name=helloService");
StreamConnection conn = (StreamConnection) service.acceptAndOpen();
System.out.println("Connected");
DataInputStream in = new DataInputStream(conn.openInputStream());
DataOutputStream out = new DataOutputStream(conn.openOutputStream());
String received = in.readUTF(); // Read from client
System.out.println("received: " + received);
out.writeUTF("Echo: " + received); // Send Echo to client
conn.close();
service.close();
} catch (IOException e) {
System.err.print(e.toString());
}
}
}
Android Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.UUID;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.widget.LinearLayout;
import android.widget.ArrayAdapter;
public class AndroidBluetoothEchoClientActivity extends ListActivity {
LinearLayout layout;
private ArrayAdapter<String> mArrayAdapter;
final Handler handler = new Handler();
final Runnable updateUI = new Runnable() {
public void run() {
mArrayAdapter.add(bluetoothClient.getBluetoothClientData());
}
};
BluetoothClient bluetoothClient;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
this.setListAdapter(mArrayAdapter);
bluetoothClient = new BluetoothClient(handler, updateUI);
bluetoothClient.start();
}
}
class BluetoothClient extends Thread {
BluetoothAdapter mBluetoothAdapter;
private String data = null;
final Handler handler;
final Runnable updateUI;
public BluetoothClient(Handler handler, Runnable updateUI) {
this.handler = handler;
this.updateUI = updateUI;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
public String getBluetoothClientData() {
return data;
}
public void run() {
BluetoothSocket clientSocket = null;
// Client knows the MAC address of server
BluetoothDevice mmDevice = mBluetoothAdapter
.getRemoteDevice("00:15:83:07:CE:27");
try {
clientSocket = mmDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mBluetoothAdapter.cancelDiscovery();
clientSocket.connect();
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
out.writeUTF("Hello"); // Send to server
data = in.readUTF(); // Read from server
handler.post(updateUI);
} catch (Exception e) {
}
}
}
Here is core of the problem(I guess):
BluetoothDevice mmDevice = mBluetoothAdapter
.getRemoteDevice("00:15:83:07:CE:27");//normally get device
try {
clientSocket = mmDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));//here also no problem
mBluetoothAdapter.cancelDiscovery();
clientSocket.connect();//here throw an exception
I try to use reflection:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
clientSocket = (BluetoothSocket) m.invoke(device, 1);
but it also not work.
For over a week I can not solve this problem, I would be grateful if you help with the decision.
Here is the log file:
02-27 08:32:33.656: W/ActivityThread(10335): Application edu.ius.rwisman.AndroidBluetoothEchoClient is waiting for the debugger on port 8100...
02-27 08:32:33.687: I/System.out(10335): Sending WAIT chunk
02-27 08:32:33.882: I/System.out(10335): Debugger has connected
02-27 08:32:33.882: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.085: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.289: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.492: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.687: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.890: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:35.093: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:35.296: I/System.out(10335): debugger has settled (1493)
02-27 08:32:35.390: I/ApplicationPackageManager(10335): cscCountry is not German : SER
02-27 08:32:35.875: D/dalvikvm(10335): threadid=9: still suspended after undo (sc=1 dc=1)
02-27 08:32:45.351: D/BluetoothSocket(10335): create BluetoothSocket: type = 1, fd = -1, uuid = [00001101-0000-1000-8000-00805f9b34fb], port = -1
02-27 08:32:45.351: D/BLZ20_WRAPPER(10335): blz20_init: initializing...
02-27 08:32:45.351: D/BTL_IFC_WRP(10335): wsactive_init: init active list
02-27 08:32:45.460: D/BLZ20_WRAPPER(10335): blz20_init: success
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_create: CTRL
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_alloc_new_sock: wrp_alloc_new_sock sub 1
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_create: 43
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_connect: wrp_sock_connect brcm.bt.btlif:9000 (43)
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_connect: BTLIF_MAKE_LOCAL_SERVER_NAME return name: brcm.bt.btlif.9000
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_connect: wrp_sock_connect ret:-1 server name:brcm.bt.btlif.9000
02-27 08:32:45.460: E/BTL_IFC_WRP(10335): ##### ERROR : wrp_sock_connect: connect failed (Connection refused)#####
02-27 08:32:45.460: E/BTL_IFC(10335): ##### ERROR : btl_ifc_ctrl_connect: control channel failed Connection refused#####
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_close_full: wrp_close (43:-1) [brcm.bt.btlif]
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wsactive_del: delete wsock 43 from active list [ad3bc380]
Problem solved, simply verification code on my device and on PC was different, but Windows shown device in paired devices list. I repair device and it works.