update Main UI Thread or AsyncTask never allowed than where can i update UI thread? [duplicate] - android-asynctask

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
Caused by: android.os.NetworkOnMainThreadException
04-25 13:15:52.362: E/AndroidRuntime(20900): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.io.IoBridge.connect(IoBridge.java:112)
04-25 13:15:52.362: E/AndroidRuntime(20900): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
04-25 13:15:52.362: E/AndroidRuntime(20900): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
04-25 13:15:52.362: E/AndroidRuntime(20900): at java.net.Socket.connect(Socket.java:842)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
04-25 13:15:52.362: E/AndroidRuntime(20900): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
04-25 13:15:52.362: E/AndroidRuntime(20900): at java.net.URLConnection.getContent(URLConnection.java:190)
04-25 13:15:52.362: E/AndroidRuntime(20900): at java.net.URL.getContent(URL.java:447)
04-25 13:15:52.362: E/AndroidRuntime(20900): at biz.xicom.printvintage.HomeScreen$2.run(HomeScreen.java:199)
04-25 13:15:52.362: E/AndroidRuntime(20900): at android.app.Activity.runOnUiThread(Activity.java:4644)
04-25 13:15:52.362: E/AndroidRuntime(20900): at biz.xicom.printvintage.HomeScreen.setview(HomeScreen.java:193)
04-25 13:15:52.362: E/AndroidRuntime(20900): at biz.xicom.printvintage.HomeScreen.onCreate(HomeScreen.java:58)
04-25 13:15:52.362: E/AndroidRuntime(20900): at android.app.Activity.performCreate(Activity.java:5104)
04-25 13:15:52.362: E/AndroidRuntime(20900): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-25 13:15:52.362: E/AndroidRuntime(20900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
code
for (int i = 0; i < image_list.size(); i++) {
LayoutInflater layoutInflator = HomeScreen.this.getLayoutInflater();
LinearLayout childlayout = (LinearLayout) layoutInflator.inflate(
R.layout.image_text_web_services_inflate, mPager, false);
im = (ImageView) childlayout.findViewById(R.id.image_web_service);
t = (TextView) childlayout.findViewById(R.id.text_web_service);
t.setText(HomeScreen.detail_list.get(i));
final int j=i;
runOnUiThread(new Runnable() {
public void run(){
try {
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(
HomeScreen.image_list.get(j))
.getContent());
im.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mPager.addView(childlayout);
}
i read below link:
Load More - Only the original thread that created a view hierarchy can touch its views
android - Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException
Every one said
You are trying to update your Main UI Thread or AsyncTask never allowed that.
then where i can update or show my image.
Also try AsyncTask.
than how to implement on loop

As you are trying to load Images inside Loop, I would suggest you to implement logic of Lazy loading of Images.
Here are some libraries you can give a try:
Lazy List
Universal Image Loader for Android

Use this code It will help,
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

You are calling a web service in UI thread. Android does not allow you to perform network operation in UI thread from API>=3.0.
Solutions:
Load images in a different thread.
new Thread()
{
#Override
public void run()
{
// load image here
super.run();
}
}.start();
Using LazyList would be a great solution for this problem.
You may use AsyncTask too.
class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// Runs on UI thread- Any code you wants
// to execute before web service call. Put it here.
// Eg show progress dialog
}
#Override
protected String doInBackground(String... params) {
// Runs in background thread
String result = //your web service request;
return result;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String resp) {
// runs in UI thread - You may do what you want with response
// Eg Cancel progress dialog - Use result
}
}

Related

Image upload on Phonegap / framework 7 app

I'm creating this app with Phonegap and Framework 7.
In one of my views, i wanted to have a image upload button and i implemented the following code:
<script>
function selectPhoto() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('get picture failed'); },
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY, }
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://pedrofidalgo.pt/upload.php", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
<button class="btngaleria" onclick="selectPhoto();" style="margin-top:3vh; background-color: #5f919d;"> Upload image </button>
I then have a php file on a web server with this code:
<?php
print_r($_FILES);
$new_image_name = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "/uploads/sitios".$new_image_name);
?>
I tried building the APK and when i click the button it simply doesn't do anything. When i tried the app in the browser, the console says that the function i'm calling with the button (selectPhoto) is not defined.. can someone give some guidance please?
You have an error in your code
function fail(error)
{
alert("An error has occurred: Code = " = error.code);
should be
function fail(error)
{
alert("An error has occurred: Code = " + error.code);

Gulp not refresh on changes to imported scss files

Gulp task in jhipster is not refreshing the main.css file when I change imported *.scss files, only if I change main.scss. The watch task in gulp shows me changes but nothing happens.
Gulpfile.js
// Generated on 2016-03-14 using generator-jhipster 2.27.2
/* jshint camelcase: false */
'use strict';
var gulp = require('gulp'),
prefix = require('gulp-autoprefixer'),
cssnano = require('gulp-cssnano'),
usemin = require('gulp-usemin'),
uglify = require('gulp-uglify'),
sass = require('gulp-sass'),
htmlmin = require('gulp-htmlmin'),
imagemin = require('gulp-imagemin'),
ngAnnotate = require('gulp-ng-annotate'),
ngConstant = require('gulp-ng-constant-fork'),
jshint = require('gulp-jshint'),
rev = require('gulp-rev'),
protractor = require('gulp-protractor').protractor,
proxy = require('proxy-middleware'),
es = require('event-stream'),
flatten = require('gulp-flatten'),
del = require('del'),
url = require('url'),
wiredep = require('wiredep').stream,
runSequence = require('run-sequence'),
browserSync = require('browser-sync'),
sourcemaps = require('gulp-sourcemaps'),
KarmaServer = require('karma').Server,
plumber = require('gulp-plumber'),
changed = require('gulp-changed'),
cache = require('gulp-cached'),
handleErrors = require('./gulp/handleErrors'),
util = require('./gulp/utils');
var config = {
app: 'src/main/webapp/',
dist: 'src/main/webapp/dist/',
test: 'src/test/javascript/',
importPath: 'src/main/webapp/bower_components',
scss: 'src/main/scss/',
port: 9000,
apiPort: 8080,
liveReloadPort: 35729
};
gulp.task('clean', function () {
return del([config.dist]);
});
gulp.task('test', ['wiredep:test', 'ngconstant:dev'], function (done) {
//TODO LW UNCOMMENT WORKING ..
/* new KarmaServer({
configFile: __dirname + '/' + config.test + 'karma.conf.js',
singleRun: true
}, done).start();*/
});
gulp.task('protractor', function () {
return gulp.src([config.test + 'e2e/*.js'])
.pipe(plumber({errorHandler: handleErrors}))
.pipe(protractor({
configFile: config.test + 'protractor.conf.js'
}));
});
gulp.task('copy', function () {
return es.merge( // copy i18n folders only if translation is enabled
gulp.src(config.app + 'i18n/**')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(changed(config.dist + 'i18n/'))
.pipe(gulp.dest(config.dist + 'i18n/')),
gulp.src(config.app + 'bower_components/bootstrap/fonts/*.*')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(changed(config.dist + 'assets/fonts/'))
.pipe(gulp.dest(config.dist + 'assets/fonts/')),
gulp.src(config.app + 'assets/**/*.{woff,svg,ttf,eot}')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(changed(config.dist + 'assets/fonts/'))
.pipe(flatten())
.pipe(gulp.dest(config.dist + 'assets/fonts/')));
});
gulp.task('images', function () {
return gulp.src(config.app + 'assets/images/**')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(changed(config.dist + 'assets/images'))
.pipe(imagemin({optimizationLevel: 5}))
.pipe(gulp.dest(config.dist + 'assets/images'))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('sass', function () {
return gulp.src(config.scss + 'main.scss')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(changed(config.app + 'assets/styles', {extension: '.css'}))
.pipe(sass({includePaths: config.importPath}).on('error', sass.logError))
.pipe(gulp.dest(config.app + 'assets/styles'));
});
gulp.task('styles', ['sass'], function () {
return gulp.src(config.app + 'assest/styles')
.pipe(browserSync.reload({stream: true}));
});
gulp.task('install', function (done) {
runSequence('wiredep', 'ngconstant:dev', 'sass', done);
});
gulp.task('serve', function () {
runSequence('install', function () {
var baseUri = 'http://localhost:' + config.apiPort;
// Routes to proxy to the backend. Routes ending with a / will setup
// a redirect so that if accessed without a trailing slash, will
// redirect. This is required for some endpoints for proxy-middleware
// to correctly handle them.
var proxyRoutes = [
'/api',
'/health',
'/configprops',
'/env',
'/v2/api-docs',
'/swagger-ui',
'/configuration/security',
'/configuration/ui',
'/swagger-resources',
'/metrics',
'/websocket/tracker',
'/dump'
];
var requireTrailingSlash = proxyRoutes.filter(function (r) {
return util.endsWith(r, '/');
}).map(function (r) {
// Strip trailing slash so we can use the route to match requests
// with non trailing slash
return r.substr(0, r.length - 1);
});
var proxies = [
// Ensure trailing slash in routes that require it
function (req, res, next) {
requireTrailingSlash.forEach(function (route) {
if (url.parse(req.url).path === route) {
res.statusCode = 301;
res.setHeader('Location', route + '/');
res.end();
}
});
next();
}
]
.concat(
// Build a list of proxies for routes: [route1_proxy, route2_proxy, ...]
proxyRoutes.map(function (r) {
var options = url.parse(baseUri + r);
options.route = r;
options.preserveHost = true;
return proxy(options);
}));
browserSync({
open: false,
port: config.port,
reloadDelay: 1000,
server: {
baseDir: config.app,
middleware: proxies
}
});
gulp.start('watch');
});
});
gulp.task('watch', function () {
gulp.watch('bower.json', ['wiredep']);
gulp.watch(['gulpfile.js', 'build.gradle'], ['ngconstant:dev']);
gulp.watch(config.scss + '**/*.{scss,sass}', ['styles']);
gulp.watch(config.app + 'assets/images/**', ['images']);
gulp.watch(config.app + 'scripts/**/*.js', ['jshint']);
gulp.watch([config.app + '*.html', config.app + 'scripts/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});
gulp.task('wiredep', ['wiredep:test', 'wiredep:app']);
gulp.task('wiredep:app', function () {
var stream = gulp.src(config.app + 'index.html')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(wiredep({
exclude: [/angular-i18n/]
}))
.pipe(gulp.dest(config.app));
return es.merge(stream, gulp.src(config.scss + '*.{scss,sass}')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(wiredep({
exclude: [
/angular-i18n/, // localizations are loaded dynamically
'bower_components/bootstrap/' // Exclude Bootstrap LESS as we use bootstrap-sass
],
ignorePath: /\.\.\/webapp\/bower_components\// // remove ../webapp/bower_components/ from paths of injected sass files
}))
.pipe(gulp.dest(config.scss)));
});
gulp.task('wiredep:test', function () {
return gulp.src(config.test + 'karma.conf.js')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(wiredep({
exclude: [/angular-i18n/, /angular-scenario/],
ignorePath: /\.\.\/\.\.\//, // remove ../../ from paths of injected javascripts
devDependencies: true,
fileTypes: {
js: {
block: /(([\s\t]*)\/\/\s*bower:*(\S*))(\n|\r|.)*?(\/\/\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}))
.pipe(gulp.dest(config.test));
});
gulp.task('build', function (cb) {
runSequence('clean', 'copy', 'wiredep:app', 'ngconstant:prod', 'usemin', cb);
});
gulp.task('usemin', ['images', 'styles'], function () {
return gulp.src([config.app + '**/*.html', '!' + config.app + '#(dist|bower_components)/**/*.html'])
.pipe(plumber({errorHandler: handleErrors}))
.pipe(usemin({
css: [
prefix,
'concat',
cssnano,
rev
],
html: [
htmlmin.bind(htmlmin, {collapseWhitespace: true})
],
js: [
sourcemaps.init,
ngAnnotate,
'concat',
uglify.bind(uglify, {mangle: false}),
rev,
sourcemaps.write.bind(sourcemaps.write, '.')
]
}))
.pipe(gulp.dest(config.dist));
});
gulp.task('ngconstant:dev', function () {
return ngConstant({
dest: 'app.constants.js',
name: 'adminApp',
deps: false,
noFile: true,
interpolate: /\{%=(.+?)%\}/g,
wrap: '/* jshint quotmark: false */\n"use strict";\n// DO NOT EDIT THIS FILE, EDIT THE GULP TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n{%= __ngModule %}',
constants: {
BUILD_CONFIG: {
ENV: 'dev',
VERSION: util.parseVersion()
}
}
})
.pipe(gulp.dest(config.app + 'scripts/app/'));
});
gulp.task('ngconstant:test', function () {
return ngConstant({
dest: 'app.constants.js',
name: 'adminApp',
deps: false,
noFile: true,
interpolate: /\{%=(.+?)%\}/g,
wrap: '/* jshint quotmark: false */\n"use strict";\n// DO NOT EDIT THIS FILE, EDIT THE GULP TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n{%= __ngModule %}',
constants: {
BUILD_CONFIG: {
ENV: 'prod',
VERSION: util.parseVersion()
}
}
})
.pipe(gulp.dest(config.app + 'scripts/app/'));
});
gulp.task('ngconstant:prod', function () {
return ngConstant({
dest: 'app.constants.js',
name: 'adminApp',
deps: false,
noFile: true,
interpolate: /\{%=(.+?)%\}/g,
wrap: '/* jshint quotmark: false */\n"use strict";\n// DO NOT EDIT THIS FILE, EDIT THE GULP TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n{%= __ngModule %}',
constants: {
BUILD_CONFIG: {
ENV: 'prod',
VERSION: util.parseVersion()
}
}
})
.pipe(gulp.dest(config.app + 'scripts/app/'));
});
gulp.task('jshint', function () {
//Custom reporter (in task to have new instance each time)
var jsHintErrorReporter = require('./gulp/jsHintErrorReporter');
return gulp.src(['gulpfile.js', config.app + 'scripts/**/*.js'])
.pipe(plumber({errorHandler: handleErrors}))
.pipe(cache('jshint'))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jsHintErrorReporter());
});
gulp.task('itest', ['protractor']);
gulp.task('default', ['serve']);
main.scss
.main {
max-height: 80%;
}
// include custom variables
#import "app/reset/bootstrap-variables.scss";
#import "app/common/media-queries.scss";
// include bootstrap default mixins
//#import "bootstrap/_mixins";
#import "bootstrap.scss";
// utils
#import "app/utils/utils-background.scss";
#import "app/utils/utils-variables.scss";
// reset (mixins and variables)
#import "app/reset/bootstrap-reset.scss";
// layout
#import "app/layout/layout.scss";
#import "app/layout/header.scss";
#import "app/layout/sidebar.scss";
// Common
#import "app/common/animate.scss";
#import "app/common/font.scss";
#import "app/common/loading-bar.scss";
#import "app/common/print.scss";
#import "app/common/settings.scss";
// Charts
#import "app/charts/charts.scss";
#import "app/charts/easypie.scss";
// forms
#import "app/forms/form-extras.scss";
#import "app/forms/form-imgcrop.scss";
#import "app/forms/form-input.scss";
#import "app/forms/form-switch.scss";
#import "app/forms/form-validation.scss";
#import "app/forms/form-wizard.scss";
#import "app/forms/uiselect.scss";
#import "app/forms/slider.scss";
// grid
#import "app/grid/grid-table.scss";
#import "app/grid/masonry-grid.scss";
#import "app/grid/row-extra.scss";
// icons
#import "app/icons/feather-icons.scss";
// maps
#import "app/maps/gmap.scss";
#import "app/maps/vector-map.scss";
// tables
#import "app/tables/table-ngtable.scss";
#import "app/tables/table-responsive.scss";
#import "app/tables/table-datatables.scss";
// ui
#import "app/ui/alerts.scss";
#import "app/ui/button-extra.scss";
#import "app/ui/button-switch.scss";
#import "app/ui/dropdown-extra.scss";
#import "app/ui/panels-extra.scss";
#import "app/ui/placeholder.scss";
#import "app/ui/points.scss";
#import "app/ui/progress-extra.scss";
// components
#import "app/components/datepicker.scss";
#import "app/components/nestable.scss";
#import "app/components/portlets.scss";
#import "app/components/ripple.scss";
#import "app/components/scrollable.scss";
#import "app/components/toaster.scss";
#import "app/components/typeahead.scss";
#import "app/components/layermorph.scss";
// extras
#import "app/extras/calendar.scss";
#import "app/extras/chat.scss";
#import "app/extras/mailbox.scss";
#import "app/extras/tasks.scss";
#import "app/extras/timeline-2.scss";
#import "app/extras/timeline.scss";
// utils
#import "app/utils/utils.scss";
.form-filter .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
min-width: 154px;
}
.form-filter button {
display: inline-block;
width: auto;
vertical-align: bottom;
margin-bottom: 0px !important;
}
I was with the same problem and right now I had discovered the problem is with "changed" plugin being used inside the sass tasks, just comment:
.pipe(changed(config.app + 'assets/styles', {extension: '.css'}))
In my version of jhipster is .pipe(changed(config.cssDir, {extension: '.css'})) )
That should fix the problem.
You need to watch all your scss files
gulp.watch('your path to your scss files here',['sass']);

Receiving error "connection to ws://localhost:1337/socket.io/1/websocket" was interrupted while the page was loading"

Receiving error "connection to ws://localhost:1337/socket.io/1/websocket" was interrupted while the page was loading" How do i rectify this issue? I tried to close the socket connection before opening this new socket connection, however I am still receiving this error. Please Advise.
You can always close the connection beforeonload,
$(window).on('beforeunload', function(){
socket.close();
});
And you can subscribe to onclose of the websocket to handle the error in javascript like this:
url = "ws://echo.websocket.org";
try {
socket = window['MozWebSocket'] ? new MozWebSocket(url) : new WebSocket(url);
socket.onopen = function(){
console.log('Socket is now open.');
};
socket.onerror = function (error) {
console.error('There was an un-identified Web Socket error');
};
socket.onmessage = function (message) {
console.info("Message: %o", message.data);
};
socket.onclose = function() {
console.info( 'Socket is now closed.' );
}
} catch (e) {
console.error('Sorry, the web socket at "%s" is un-available', url);
}
setTimeout(function(){
socket.send("Hello World");
}, 1000);
Fiddle: http://jsfiddle.net/w5aAK/1/

Phonegap Image Upload works only once

my app needs to upload photos to a server. This works great when uploading the first captured photo. When I capture another photo, the upload fails.
Here is my code:
// Upload files to server
function uploadFile(mediaFile) {
$.mobile.loading( 'show' );
var path = mediaFile;
alert(path);
var options = new FileUploadOptions();
options.mimeType="image/jpeg";
var params = new Object();
params.fullpath = path;
params.eventID = eventID;
options.params = params;
options.chunkedMode = true;
var ft = new FileTransfer();
ft.upload( path, "http://dev.tellthedj.de/db/uploadPhoto.php",
function(result) {
$.mobile.loading( 'hide' );
alert("Foto erfolgreich hochgeladen");
// Geschossenes Foto aus Cache löschen
var file = new FileEntry();
file.fullPath = mediaFile;
file.remove(success, fail);
function success(){
alert("success");
}
function fail(){
alert("cache löschen nicht erfolgreich")
}
},
function(error) {
$.mobile.loading( 'hide' );
alert("Upload nicht erfolgreich. Bitte checke deine Internet-Verbindung: ");
console.log(error.message);
},
options
);
}
mediaFile is the location of the captured photo in cache folder.
The second photo I want to upload always calls "Upload nicht erfolgreich..." and i got this error in LogCat
07-25 08:59:11.980: E/FileTransfer(6783): {"target":"http:\/\/dev.tellthedj.de\/db\/uploadPhoto.php","source":"file:\/\/\/storage\/sdcard0\/Android\/data\/com.phonegap.getting.started\/cache\/1374735548710.jpg","http_status":0,"code":3}
07-25 08:59:11.980: E/FileTransfer(6783): java.io.EOFException
07-25 08:59:11.980: E/FileTransfer(6783): at com.squareup.okhttp.internal.Util.readAsciiLine(Util.java:314)
07-25 08:59:11.980: E/FileTransfer(6783): at com.squareup.okhttp.internal.http.RawHeaders.fromBytes(RawHeaders.java:301)
07-25 08:59:11.980: E/FileTransfer(6783): at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:130)
07-25 08:59:11.980: E/FileTransfer(6783): at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:630)
07-25 08:59:11.980: E/FileTransfer(6783): at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:385)
07-25 08:59:11.980: E/FileTransfer(6783): at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:334)
07-25 08:59:11.980: E/FileTransfer(6783): at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:534)
07-25 08:59:11.980: E/FileTransfer(6783): at org.apache.cordova.core.FileTransfer$3.run(FileTransfer.java:443)
07-25 08:59:11.980: E/FileTransfer(6783): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-25 08:59:11.980: E/FileTransfer(6783): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-25 08:59:11.980: E/FileTransfer(6783): at java.lang.Thread.run(Thread.java:856)
07-25 08:59:11.980: E/FileTransfer(6783): Failed after uploading 25260 of 25260 bytes.
The strange thing is, that the first upload works fine, the second fails with error code 3. The third works, the fourth -> error...
Okay, I just spent the last day or so working through the same issue. What worked for me was to set the header to close the connection.
options.headers = { "Connection":"close" };
Found this answer on the cordova Bug Tracker site:
https://issues.apache.org/jira/browse/CB-2293?focusedCommentId=13696238&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-13696238
Hope that helps, I know how frustrated I was with this one too!
You can use xmlhttprequest level 2 via jquery.
its easy and configure your java file with chrome environment.
so your upload like web .
This is an unfixed bug in the phonegap library, since there were no bug fixes, i had to get it work by my work around (Basically reupload on every alternate failure):
ft.upload(path,
encodeURI("http://yourdomain.com/upload.php"),
function(result) {
alert("Uploaded");
},
function(error) {
ft.upload(path,
encodeURI("http://yourdomain.com/upload.php"),
function(result) {
alert("Uploaded");
},
function(error) {
alert("Error uploading image");
},
{ fileName: name, fileKey: "file", mimeType: "image/jpeg", chunkedMode: false }, true);
},
{ fileName: name, fileKey: "file", mimeType: "image/jpeg", chunkedMode: false }, true);

SenchaTouch2.0 + socket.io : how to use socket.io.js in SenchTouch2.0

in fact, I had try it,and failed. now the code is:
function include(path){
var a=document.createElement("script");
a.type = "text/javascript";
a.src=path;
var head=document.getElementsByTagName("head")[0];
head.appendChild(a);
}
include("app/controller/node_modules/socket.io-client/dist/socket.io.js");
Ext.define('WGTalk.controller.guest', {
extend: 'Ext.app.Controller',
config:{
refs:{
viewMsg:'#viewMsg',
txtMsg:'#txtMsg'
},
control:{
'#btSend':{
tap:'doSend'
}
}
},
launch:function(){
var socket = io.connect('http://localhost:8080');
socket.on('connect',function(){
console.log("connected server");
});
socket.on('disconnect',function(){
console.log("server closed");
});
socket.on('message',function(data) {
console.log('Received a message from the server: ',data);
});
},
doSend:function(){
var msg = this.getTxtMsg().getValue();
var msgStore = this.getViewMsg().getStore();
msgStore.add({name:msg,age:'180'});
this.getTxtMsg().setValue("");
}
});
and the error is: *ReferenceError: Can't find variable: io #"var socket = io.connect('http://localhost:8080');
" *
how can I resolve this error?
In your app.json, to load external javascript resources like socket.io, modify as follows:
/**
* List of all JavaScript assets in the right execution order.
* Each item is an object with the following format:
* ...
*/
"js": [
{
"path": "socket.io.js",
"x-bootstrap": true
},
{
"path": "json.js",
"x-bootstrap": true
},
...
]
If your mobile app is a client, the above .js are client side socket.io.
Declare io socket inside index.html
like this
<script src="http://yourip:port/socket.io/socket.io.js"></script>

Resources