AsyncTask task onPostExecute() not executing? Tried all answer already present on stackoverflow - java

Hi Developers and friends,
I am working on an android application, which required to read JSON url. I am using AsyncTask. But I dont know why the onPostExecute() is not executing. I successfully parse the json. The only thing left is to return the string (having parse json text).
Here is my code:
package com.vijay.jsonwizard.demo.activities;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.vijay.jsonwizard.demo.R;
import com.vijay.jsonwizard.activities.JsonFormActivity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private static final int REQUEST_CODE_GET_JSON = 1;
private static final String TAG = "MainActivity";
private static final String DATA_JSON_PATH = "http://jatinderbhola.in/phppractice/data.json";
String json;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_start).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, JsonFormActivity.class);
BackgroundTask task = new BackgroundTask();
task.execute();
if (json != null) {
intent.putExtra("json", json);
startActivityForResult(intent, REQUEST_CODE_GET_JSON);
} else {
Toast.makeText(getApplicationContext(), "Error!!", Toast.LENGTH_LONG).show();
}
}
});
}
private class BackgroundTask extends AsyncTask < String, String, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String...params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(DATA_JSON_PATH)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
try {
//Log.d("Respose", response.body().string());
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String data) {
set_json(data);
}
}
private void set_json(String s) {
// json = s;
Toast.makeText(getApplicationContext(), "I'm in!!", Toast.LENGTH_LONG).show();
}
}
Thanks and advance.
no exception:
this is what android monitor displaying:
01-28 13:42:17.117 1450-1450/com.vijay.jsonwizard.demo I/art: Not late-enabling -Xcheck:jni (already on)
01-28 13:42:17.117 1450-1450/com.vijay.jsonwizard.demo I/art: Late-enabling JIT
01-28 13:42:17.119 1450-1450/com.vijay.jsonwizard.demo I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
01-28 13:42:17.147 1450-1450/com.vijay.jsonwizard.demo W/System: ClassLoader referenced unknown path: /data/app/com.vijay.jsonwizard.demo-1/lib/x86
01-28 13:42:17.309 1450-1477/com.vijay.jsonwizard.demo D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-28 13:42:17.411 1450-1477/com.vijay.jsonwizard.demo I/OpenGLRenderer: Initialized EGL, version 1.4
01-28 13:42:17.805 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 31.806ms
01-28 13:42:17.935 1450-1477/com.vijay.jsonwizard.demo W/EGL_emulation: eglSurfaceAttrib not implemented
01-28 13:42:17.935 1450-1477/com.vijay.jsonwizard.demo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7600e0, error=EGL_SUCCESS
01-28 13:42:17.991 1450-1450/com.vijay.jsonwizard.demo I/Choreographer: Skipped 38 frames! The application may be doing too much work on its main thread.
01-28 13:43:25.890 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 5.563ms
01-28 13:49:09.646 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 6.337ms
01-28 13:56:08.565 1450-1477/com.vijay.jsonwizard.demo W/EGL_emulation: eglSurfaceAttrib not implemented
01-28 13:56:08.566 1450-1477/com.vijay.jsonwizard.demo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7603e0, error=EGL_SUCCESS
01-28 13:56:11.892 1450-1477/com.vijay.jsonwizard.demo E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4053c00

move the next code to PostExecute stage:
Intent intent = new Intent(MainActivity.this, JsonFormActivity.class);
if (json != null) {
intent.putExtra("json", json);
startActivityForResult(intent, REQUEST_CODE_GET_JSON);
} else {
Toast.makeText(getApplicationContext(), "Error!!", Toast.LENGTH_LONG).show();
}
}

Related

stuck in getting arraylist from another class in android

I’m making a project in which i get data through api and stored it in arraylist but when i return it, it is empty.
Can Anyone Help Me Out?
Here is the Main Activity
package com.example.trivia;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.trivia.Data.Async;
import com.example.trivia.Data.setQ;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private CardView c;
private Button t_btn,f_btn;
private ImageButton next,prev;
private List<question>q;
private TextView set;
private int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c=findViewById(R.id.cardView);
t_btn=findViewById(R.id.true_btn);
f_btn=findViewById(R.id.false_btn);
next=findViewById(R.id.next);
prev=findViewById(R.id.prev);
set=findViewById(R.id.setq);
//ArrayList<question> dummy = new ArrayList<question>();
//AppController.OnCreate();
q=new setQ().getData(new Async() {
#Override
public void finish(ArrayList<question> c) {
set.setText(c.get(count).getQ());
// Log.d("test", "onCreate: "+c);
}
});
Log.i("in main", "Main: "+q.size());
}
}
the code of setQ class
package com.example.trivia.Data;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import org.json.JSONException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class setQ {
ArrayList<question> q =new ArrayList<question>();
JSONArray r;
private String url="https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<question> getData(final Async call) {
final JsonArrayRequest jarr = new JsonArrayRequest(Request.Method.GET, url, (JSONArray)null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
r=response;
for (int i = 0; i < response.length(); i++) {
try {
JSONArray a = response.getJSONArray(i);
question k = new question(a.getString(0), a.getBoolean(1));
//Log.i("list", "onResponse: "+k.getAns());
q.add(k);
// Log.i("response", "onResponse: " +a.get(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
if(call!=null) {
call.finish( q);
}
//return q;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Log.i("error ",""+AppController.getInstance());
AppController.getInstance().addToRequestQueue(jarr);
return q;
// return q;
}
}
output
07/11 23:55:18: Launching 'app' on Pixel 3 API 21.
$ adb shell am start -n "com.example.trivia/com.example.trivia.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 15594 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.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.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
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
I/error: com.example.trivia.controller.AppController#24777a64
***I/in main: Main: 0***
D/OpenGLRenderer: Render dirty regions requested: true
D/: HostConnection::get() New Host Connection established 0x7f28894105c0, tid 15594
D/Atlas: Validating map...
I/art: Background sticky concurrent mark sweep GC freed 5802(428KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 2MB/2MB, paused 8.789ms total 42.738ms
D/: HostConnection::get() New Host Connection established 0x7f28950b0e40, tid 15624
I/OpenGLRenderer: Initialized EGL, version 1.4
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0x7f2894773200: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
glUtilsParamSize: unknow param 0x00008824
D/OpenGLRenderer: Enabling debug mode 0
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
I/Choreographer: Skipped 62 frames! The application may be doing too much work on its main thread.
Implement the callback pattern.
Create a new Interface file:
Interface MyVolleyResponse {
void onResponse(JSONArray response);
void onError(VolleyError error);
}
Your activity should implement this, as follows:
public class MainActivity extends AppCompatActivity implements MyVolleyResponse {...}
Add the new methods to your activity:
void onResponse(JSONArray response) {
// process your response here, building your question array...
}
void onError(VolleyError error) {
// handle errors here...
}
Change your Volley responses within SetQ:
public void onResponse(JSONArray response) {
callback.onResponse(response);
}
public void onErrorResponse(VolleyError error) {
callback.onError(error);
}
Create a constructor within SetQ to set the callback:
private MyVolleyResponse callback;
SetQ(MyVolleyResponse callback) {
this.callback = callback;
}
Call this constructor in your activity with:
SetQ volley = new SetQ(this);
Change the signnature of getData to just:
void getData() {...}
And run the Volley call with volley.getData().
Remove all AsyncTask objects in your code, because Volley is already asynchronous.

Activity layout lagging behind until before next transition to another activity

The problem is that, during transition from firstActivity to thisServiceActivity, the screen will freeze and then turn black. If service has performed it process and send the broadcast and receive by the broadcast receiver of thisServiceActivity, then it will finally show the layout of the thisServiceActivity and quickly transition to ResultActivity.
Is it because there is something I do wrong in its UI thread? I try to find similar discussion to this problem but can't find it.
firstActivity class will start a new activity which is thisServiceActivity class. thisServiceActivity have a layout that show a progressbar and textview. At the same time, it will start a service class name as myForegroundService with pending intent notification.
If the process in the service completed, the service will send a local broadcast that will be pickup by thisServiceActivity using broadcast receiver and it then stop the service and transition to resultActivity and finish its activity.
public class firstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_activity);
}
//using button onclick
public void startActivity(View view) {
Intent startService = new Intent(this, thisServiceActivity.class);
startActivity(startService);
}
}
package example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class thisServiceActivity extends AppCompatActivity {
Intent goToResult, stopMyService, startMyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_this_service);
LocalBroadcastManager.getInstance(this).registerReceiver(myForegroundReceiver,
new IntentFilter("end-of-process"));
startService();
}
public void startService() {
startMyService = new Intent(this, myForegroundService.class);
ContextCompat.startForegroundService(this, startMyService);
}
public void stopService() {
stopMyService = new Intent(this, myForegroundService.class);
stopService(stopMyService);
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(myForegroundReceiver);
super.onDestroy();
}
private BroadcastReceiver myForegroundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive", "Received");
stopService();
goToResult = new Intent(getApplication(), ResultActivity.class);
startActivity(goToResult);
finish();
}
};
}
package example.myapplication;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.concurrent.ExecutionException;
import static example.myapplication.App.CHANNEL_ID;
public class myForegroundService extends Service {
Boolean process;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Service Running", "True");
Intent toThisServiceActivity = new Intent(this, thisServiceActivity.class);
PendingIntent servicePendingIntent = PendingIntent.getActivity(this, 0, toThisServiceActivity, 0);
Notification notify = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Sit back and relax, process is in progress")
.setContentText("You look more charming if you have patient, please wait")
.setContentIntent(servicePendingIntent)
.build();
startForeground(1, notify);
try {
process = new MyLoop().execute().get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
if (process) {
Intent killswitch = new Intent("end-of-process");
Log.i("Finish", "Service");
LocalBroadcastManager.getInstance(this).sendBroadcast(killswitch);
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private class MyLoop extends AsyncTask<Void, String, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
for (int i = 0; i < 10; i++) {
publishProgress("i = " + i);
SystemClock.sleep(1000);
}
return true;
}
#Override
protected void onProgressUpdate(String... values) {
String value = values[0];
Log.i("Foreground Service", value);
}
}
}
Logcat output
02/25 17:41:41: Launching 'app' on Google.
$ adb shell am start -n "example.myapplication/example.myapplication.firstActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 5060 on device '-google-192.168.42.106:5555'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Zygote: seccomp disabled by setenforce 0
I/e.myapplicatio: Late-enabling -Xcheck:jni
W/e.myapplicatio: Unexpected CPU variant for X86 using defaults: x86
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
I/example.myapplication: type=1400 audit(0.0:1122): avc: denied { write } for comm=45474C20496E6974 name="property_service" dev="tmpfs" ino=9335 scontext=u:r:untrusted_app:s0:c96,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=1
type=1400 audit(0.0:1123): avc: denied { connectto } for comm=45474C20496E6974 path="/dev/socket/property_service" scontext=u:r:untrusted_app:s0:c96,c256,c512,c768 tcontext=u:r:init:s0 tclass=unix_stream_socket permissive=1
D/vndksupport: Loading /vendor/lib/egl/libGLES_emulation.so from current namespace instead of sphal namespace.
E/libEGL: load_driver(/vendor/lib/egl/libGLES_emulation.so): dlopen failed: library "/vendor/lib/egl/libGLES_emulation.so" not found
D/vndksupport: Loading /vendor/lib/egl/libEGL_emulation.so from current namespace instead of sphal namespace.
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/vndksupport: Loading /vendor/lib/egl/libGLESv1_CM_emulation.so from current namespace instead of sphal namespace.
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/vndksupport: Loading /vendor/lib/egl/libGLESv2_emulation.so from current namespace instead of sphal namespace.
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 (light greylist, reflection)
W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
D/OpenGLRenderer: Skia GL Pipeline
D/: HostConnection::get() New Host Connection established 0xe7b6d5c0, tid 5087
I/RenderThread: type=1400 audit(0.0:1124): avc: denied { connectto } for path=006C6F63616C5F6F70656E676C scontext=u:r:untrusted_app:s0:c96,c256,c512,c768 tcontext=u:r:local_opengl:s0 tclass=unix_stream_socket permissive=1
W/: Unrecognized GLES max version string in extensions:
W/: Process pipe failed
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/EGL_emulation: eglCreateContext: 0xe1fc8e20: maj 2 min 0 rcv 2
D/vndksupport: Loading /vendor/lib/hw/android.hardware.graphics.mapper#2.0-impl.so from current namespace instead of sphal namespace.
D/vndksupport: Loading /vendor/lib/hw/gralloc.vbox86.so from current namespace instead of sphal namespace.
E/EGL_emulation: tid 5087: eglSurfaceAttrib(1354): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe1fc8d60, error=EGL_BAD_MATCH
I/Choreographer: Skipped 31 frames! The application may be doing too much work on its main thread.
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#112c025
E/EGL_emulation: tid 5087: eglSurfaceAttrib(1354): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe0846b60, error=EGL_BAD_MATCH
I/Service Running: True
I/Finish: Service
W/ViewRootImpl[thisServiceActivity]: Dropping event due to no window focus: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x48, repeatCount=0, eventTime=7949110, downTime=7949110, deviceId=-1, source=0x101 }
W/ViewRootImpl[thisServiceActivity]: Cancelling event due to no window focus: KeyEvent { action=ACTION_UP, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x68, repeatCount=0, eventTime=7950511, downTime=7949110, deviceId=-1, source=0x101 }
I/Choreographer: Skipped 625 frames! The application may be doing too much work on its main thread.
I/chatty: uid=10096(example.myapplication) identical 7 lines
W/ViewRootImpl[thisServiceActivity]: Cancelling event due to no window focus: KeyEvent { action=ACTION_UP, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x68, repeatCount=0, eventTime=7950511, downTime=7949110, deviceId=-1, source=0x101 }
I/OpenGLRenderer: Davey! duration=10603ms; Flags=0, IntendedVsync=7941734767100, Vsync=7952151433350, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=7952160308707, AnimationStart=7952160414256, PerformTraversalsStart=7952161151710, DrawStart=7952165102838, SyncQueued=7952174190092, SyncStart=7952180127743, IssueDrawCommandsStart=7952180180543, SwapBuffers=7952293099225, FrameCompleted=7952343853615, DequeueBufferDuration=63000, QueueBufferDuration=161000,
I/Foreground Service: i = 0
i = 1
I/Foreground Service: i = 2
i = 3
I/OpenGLRenderer: Davey! duration=10618ms; Flags=0, IntendedVsync=7941734767100, Vsync=7952151433350, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=7952160308707, AnimationStart=7952160414256, PerformTraversalsStart=7952161151710, DrawStart=7952344526709, SyncQueued=7952345327938, SyncStart=7952355852722, IssueDrawCommandsStart=7952355900616, SwapBuffers=7952356170648, FrameCompleted=7952363877516, DequeueBufferDuration=148000, QueueBufferDuration=246000,
I/Foreground Service: i = 4
I/Foreground Service: i = 5
i = 6
i = 7
i = 8
I/Foreground Service: i = 9
I/onReceive: Received
Process 5060 terminated.
You're blocking the UI thread for 10 seconds by waiting for the result of your AsyncTask:
process = new MyLoop().execute().get();
The Javadoc for get() states:
Waits if necessary for the computation to complete, and then retrieves its result.
This is eliminating any advantage to running it on a background thread and causing your app to freeze. If you need to do something with the result, you should do it in AsyncTask.onPostExecute.

Unable to get Notification form Scanner

I am working on an application for a Zebra Technologies TC8000 scanner using the DataWedge. I'm using Android Studio 3.5 and flutter for the mobile framework.
I am using a Broadcast Receiver in my main activity and attempting to use a call back in my Dart code.
When I pull the trigger on the scanner, I see the following in logcat:
04-22 11:35:12.946 1009-1009/? D/ScannerPlugin: Scan status changed from SCAN_STATUS_WAITFORTRIGGER to SCAN_STATUS_SCANNING
04-22 11:35:12.946 1009-1009/? D/Client: requested to send: 110 (ScannerStateChanged): SCAN_STATUS_SCANNING
04-22 11:35:12.956 1009-1009/? D/Client: sent: 110 (ScannerStateChanged): SCAN_STATUS_SCANNING
04-22 11:35:12.956 1009-1009/? D/ScannerPlugin: Status:SCANNING;ProfileName:Profile0 (default)
04-22 11:35:12.956 1009-1009/? D/ScannerStateChanged: deserialize: state: SCAN_STATUS_SCANNING
04-22 11:35:12.966 1009-1009/? D/Protocol: parsed 110 (ScannerStateChanged): SCAN_STATUS_SCANNING
04-22 11:35:12.966 1009-1009/? D/SwipeAssistService: handleMessage(110 (ScannerStateChanged): SCAN_STATUS_SCANNING), connected clients: 1
04-22 11:35:13.416 665-665/? E/NotificationService: Not posting notification with icon==0: Notification(pri=0 contentView=com.symbol.datawedge/0x1090064 vibrate=null sound=null defaults=0x0 flags=0x11 kind=[null])
04-22 11:35:13.416 665-665/? E/NotificationService: WARNING: In a future release this will crash the app: com.symbol.datawedge
04-22 11:35:13.436 1009-1009/? D/ScannerPlugin: Scan status changed from SCAN_STATUS_SCANNING to SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/Client: requested to send: 110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/Client: sent: 110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/ScannerPlugin: Status:WAITING;ProfileName:Profile0 (default)
04-22 11:35:13.436 1009-1009/? D/ScannerStateChanged: deserialize: state: SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/Protocol: parsed 110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/SwipeAssistService: handleMessage(110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER), connected clients: 1
The scan beam comes on and the scanner acknowledges the bar code read, but I'm not receiving the event. I'm concerned over the line:
04-22 11:35:13.416 665-665/? E/NotificationService: Not posting notification with icon==0: Notification(pri=0 contentView=com.symbol.datawedge/0x1090064 vibrate=null sound=null defaults=0x0 flags=0x11 kind=[null])
I've checked Zebra's documents and modified my code to register the broadcast receiver. Here is my MainActivity code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import com.goodyear.flutter_plugin.R;
import static android.content.ContentValues.TAG;
public class MainActivity extends FlutterActivity {
private static String INTENT_ACTION;
private static String SCAN_DATA;
private static String CHANNEL;
private static String METHOD;
private static String NOTIFICATION_ACTION;
private static String NOTIFICATION_TYPE_SCANNER_STATUS;
private Result barcodeResult;
private void registerReceivers() {
IntentFilter filter = new IntentFilter();
filter.addAction(NOTIFICATION_ACTION);
registerReceiver(broadcastReceiver, filter);
}
private void unRegisterReceivers() {
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("Barcode", "Inside onCreate");
super.onCreate(savedInstanceState);
INTENT_ACTION = getResources().getString(R.string.activity_intent_filter_action);
SCAN_DATA = getResources().getString(R.string.datawedge_intent_key_data);
CHANNEL = getResources().getString(R.string.barcode_method_channel);
METHOD = getResources().getString(R.string.barcode_method);
NOTIFICATION_ACTION = getResources().getString(R.string.datawedge_notification_action);
NOTIFICATION_TYPE_SCANNER_STATUS = getResources().getString(R.string.datawedge_notification_scanner_status);
registerReceivers();
Bundle b = new Bundle();
b.putString("com.symbol.datawedge.api.APPLICATION_NAME", "com.example.intenttest");
b.putString("com.symbol.datawedge.api.NOTIFICATION_TYPE", "SCANNER_STATUS");
Intent i = new Intent();
i.setAction("com.symbol.datawedge.api.ACTION");
i.putExtra("com.symbol.datawedge.api.REGISTER_FOR_NOTIFICATION", b);//(1)
this.sendBroadcast(i);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, Result result) {
Log.i("Barcode", "Inside onMethodCall");
if (call.method.equals(METHOD)) {
Log.i("Barcode", "Result = " + result);
barcodeResult = result;
}
Log.i("Barcode", "Leaving onMethodCall");
}
}
);
Log.i("Barcode", "Leaving onCreate");
}
#Override
protected void onDestroy() {
unRegisterReceivers();
super.onDestroy();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Barcode", "Inside onReceive");
String action = intent.getAction();
Log.d("Barcode", "#DataWedge-APP# Action: " + action);
switch (action) {
case "com.symbol.datawedge.api.NOTIFICATION_ACTION":
logStatus(intent);
break;
case "com.com.goodyear.ACTION":
readScanData(intent);
break;
}
}
};
private void logStatus(Intent intent) {
if (intent.hasExtra("com.symbol.datawedge.api.NOTIFICATION")) {
Bundle b = intent.getBundleExtra("com.symbol.datawedge.api.NOTIFICATION");
String NOTIFICATION_TYPE = b.getString("NOTIFICATION_TYPE");
if (NOTIFICATION_TYPE != null) {
Log.d("Barcode", "SCANNER_STATUS: status: " + b.getString("STATUS") + ", profileName: " + b.getString("PROFILE_NAME"));
}
}
}
private void readScanData(Intent intent) {
String barCode = intent.getStringExtra(SCAN_DATA);
// String decodedLabelType = intent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
try {
Log.i("Barcode", "Barcode = " + barCode);
barcodeResult.success(barCode);
} catch (Exception e) {
// Catch if the UI does not exist when we receive the broadcast
}
Log.i("Barcode", "Leaving onReceive");
}
}
This is frustrating. The issue does not seem to be in my code as I have set breakpoints in the the onReceive() event and that method does not fire.
Not sure what the issue is.
NOTIFICATION_ACTION is only used to notify your application that the scanner beam is scanning, IDLE etc, it does not actually contain any scan data. I think you are confusing the DataWedge API with the DataWedge Intent Output plugin, I don't have a Flutter example but please take a look at a quick Java tutorial I did on receiving scan data from DataWedge: http://www.darryncampbell.co.uk/2017/12/13/tutorial-scan-with-datawedge-intent-output-on-zebra-devices/
I am pretty sure that error about NotificationService is unrelated to the scanner.
Your log also indicates that you are using Profile0 (default), which is the same I show in the tutorial but you may want to consider creating a dedicated Profile for your app.

Android Weather app crashing-network error

I have been developing a weather app through Treehouse and unfortunately no one has been able to help me fix this perticular error.
For some reason no weather data is retrieved on the app. I signed up through forecast IO to get the weather data to the app but nothing appears and the app crashes.
I use my phone as an emulator but I receive no errors in the log. Only when I use the Android Studio emulator do I receive an error in the logcat. Any suggestions ?
Stormy app on gitHub
Github
MainActivity.java file
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
#InjectView(R.id.humidityValue) TextView mHumidityValue;
#InjectView(R.id.precipValue) TextView mPrecipValue;
#InjectView(R.id.summaryLabel) TextView mSummaryLabel;
#InjectView(R.id.iconImageView) ImageView mIconImageView;
#InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
final double latitude = 38.627;
final double longitude = -90.199;
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "8ec5f1674002ab5081cad28e9be10ced";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if(isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
toggleRefresh();
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
updateDisplay();
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught:", e);
}
}
});
}
else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mRefreshImageView.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON:" + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getLong("time"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return new CurrentWeather();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
"PropertyFetcher: AdbCommandRejectedException getting properties for
device 0043d8b5c84ed1f5: device unauthorized.
Please check the confirmation dialog on your device."
Error log
02-10 14:17:31.130 52-52/? I/qemu-props﹕ received: qemu.hw.mainkeys=0
02-10 14:17:33.180 56-56/? I/SurfaceFlinger﹕ SurfaceFlinger's main thread ready to run. Initializing graphics H/W...
02-10 14:18:51.060 624-624/? D/AndroidRuntime﹕ Calling main entry com.android.commands.pm.Pm
02-10 14:19:01.630 548-548/com.android.launcher I/Choreographer﹕ Skipped 346 frames! The application may be doing too much work on its main thread.
02-10 14:19:02.750 437-437/? I/Choreographer﹕ Skipped 1210 frames! The application may be doing too much work on its main thread.
02-10 14:19:04.920 386-386/system_process W/BroadcastQueue﹕ Failure sending broadcast Intent { act=android.intent.action.TIME_TICK flg=0x50000014
(has extras) } android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1059)
at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:421)
at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:507)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:714)
at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:13807)
at android.content.BroadcastReceiver$PendingResult.sendFinished(BroadcastReceiver.java:419)
at android.content.BroadcastReceiver$PendingResult.finish(BroadcastReceiver.java:395)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:785)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at com.android.server.ServerThread.initAndLoop(SystemServer.java:1093)
at com.android.server.SystemServer.main(SystemServer.java:1179)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
02-10 14:19:08.800 386-386/system_process I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
02-10 14:19:19.860 548-548/com.android.launcher I/Choreographer﹕ Skipped 1089 frames! The application may be doing too much work on its main thread.
02-10 14:19:23.320 718-718/com.android.systemui I/Choreographer﹕ Skipped 679 frames! The application may be doing too much work on its main thread.
02-10 14:19:25.100 718-718/com.android.systemui I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-10 14:19:27.700 718-718/com.android.systemui I/Choreographer﹕ Skipped 154 frames! The application may be doing too much work on its main thread.
02-10 14:19:30.720 548-548/com.android.launcher I/Choreographer﹕ Skipped 61 frames! The application may be doing too much work on its main thread.
02-10 14:19:57.300 893-893/? D/AndroidRuntime﹕ Calling main entry com.android.commands.am.Am
02-10 14:19:57.400 386-398/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=aurielvilaire.com.stormy/.MainActivity} from pid 893
02-10 14:19:57.890 386-714/system_process I/ActivityManager﹕ Start proc aurielvilaire.com.stormy for activity aurielvilaire.com.stormy/.MainActivity: pid=928 uid=10054 gids={50054, 3003}
02-10 14:20:00.640 928-928/aurielvilaire.com.stormy D/MainActivity﹕ Main UI code is running!
02-10 14:20:02.170 386-400/system_process I/ActivityManager﹕ Displayed aurielvilaire.com.stormy/.MainActivity: +4s339ms
02-10 14:20:05.540 928-943/aurielvilaire.com.stormy D/MainActivity﹕ 1:20 PM
02-10 14:20:05.600 928-943/aurielvilaire.com.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: aurielvilaire.com.stormy, PID: 928 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at aurielvilaire.com.stormy.MainActivity.updateDisplay(MainActivity.java:154)
at aurielvilaire.com.stormy.MainActivity.access$500(MainActivity.java:31)
at aurielvilaire.com.stormy.MainActivity$2.onResponse(MainActivity.java:122)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
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)
02-10 14:20:05.650 386-397/system_process W/ActivityManager﹕ Force finishing activity aurielvilaire.com.stormy/.MainActivity
02-10 14:20:05.710 386-414/system_process W/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-10 14:20:05.710 386-414/system_process E/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
02-10 14:20:05.720 386-606/system_process W/InputDispatcher﹕ Attempted to unregister already unregistered input channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)'
02-10 14:20:05.720 386-606/system_process I/WindowState﹕ WIN DEATH: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:05.960 386-397/system_process I/WindowManager﹕ Screenshot max retries 4 of Token{b2051338 ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity t2 f}} appWin=Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity EXITING} drawState=4
02-10 14:20:07.260 548-548/com.android.launcher I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ This window was lost: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ mDisplayId=0 mSession=Session{b210e748 928:u0a10054}
mClient=android.os.BinderProxy#b2116298 mOwnerUid=10054
mShowToOwnerOnly=true package=aurielvilaire.com.stormy appop=NONE
mAttrs=WM.LayoutParams{(0,0)(fillxfill) sim=#120 ty=1 fl=#1810100
pfl=0x8 wanim=0x10302a1} Requested w=1080 h=1776 mLayoutSeq=71
mBaseLayer=21000 mSubLayer=0 mAnimLayer=21000+0=21000 mLastLayer=0
mToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mRootToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mAppToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mViewVisibility=0x0 mHaveFrame=true mObscured=true mSeq=0
mSystemUiVisibility=0x0 mPolicyVisibility=false
mPolicyVisibilityAfterAnim=false mAppOpVisibility=true
mAttachedHidden=false mGivenContentInsets=[0,0][0,0]
mGivenVisibleInsets=[0,0][0,0] mConfiguration={1.0 310mcc260mnc en_US
ldltr sw360dp w360dp h567dp 480dpi nrml port finger qwerty/v/v -nav/h
s.5} mHasSurface=true mShownFrame=[0.0,0.0][1080.0,1776.0]
isReadyForDisplay()=false mFrame=[0,0][1080,1776]
last=[0,0][1080,1776] mSystemDecorRect=[0,0][1080,1776]
last=[0,0][1080,1776] Frames: containing=[0,0][1080,1776]
parent=[0,0][1080,1776] display=[0,0][1080,1776]
overscan=[0,0][1080,1920] content=[0,75][1080,1776]
visible=[0,75][1080,1776] decor=[0,0][1080,1920] Cur insets:
overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0] Lst
insets: overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0]
WindowStateAnimator{b20db3d0
aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}:
mSurface=Surface(name=aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity)
mDrawState=HAS_DRAWN mLastHidden=true Surface: shown=false layer=21005
alpha=0.0 rect=(0.0,0.0) 1080.0 x 1776.0 mShownAlpha=1.0 mAlpha=1.0
mLastAlpha=-1.0 mGlobalScale=1.0 mDsDx=1.0 mDtDx=0.0 mDsDy=0.0
mDtDy=1.0 mExiting=false mRemoveOnExit=false mDestroying=true
mRemoved=false
02-10 14:20:52.610 386-606/system_process I/ActivityManager﹕ Start proc com.android.email for broadcast com.android.email/.service.EmailBroadcastReceiver: pid=1049 uid=10024 gids={50024, 3003, 1028, 1015}
02-10 14:20:53.400 1049-1063/com.android.email D/ActivityThread﹕ Loading provider com.android.email.provider;com.android.email.notifier: com.android.email.provider.EmailProvider
02-10 14:20:58.452 386-583/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.522 1049-1103/com.android.email I/Email﹕Observing account changes for notifications
02-10 14:20:58.622 386-432/system_process I/ActivityManager﹕ Start proc com.android.exchange for service com.android.exchange/.service.EmailSyncAdapterService: pid=1104 uid=10025 gids={50025, 3003, 1028, 1015}
02-10 14:20:58.622 386-607/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.882 1049-1065/com.android.email D/dalvikvm﹕ GC_FOR_ALLOC freed 313K, 16% free 3359K/3960K, paused 231ms, total 254ms
02-10 14:21:49.352 718-718/com.android.systemui I/Choreographer﹕ Skipped 32 frames! The application may be doing too much work on its main thread.
After reading through that and looking at your code, I believe the main culprit here is that you are doing to much on the main thread. You should use the android AsyncTask to run especially network connections on a separate thread. For example you might use:
private class DownloadForecast extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
getForecast(); //run all your network intensive methods
return response;
}
#Override
protected void onPostExecute(String result) {
//update all your UI stuff.
}
Can't seem to correctly intent the code. But thats what you should use. Good luck.

Android Custom Carrier Label nullpointerexception

I've added AOKP's Custom Carrier Label options to my rom and everything works with the exception of getting a Settings fc when OK is clicked in the dialog window...The customlabeltextsummary is updated correctly and the carrier is changed as it should be...
Settings.java :
package com.android.settings.cyanogenmod;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.view.IWindowManager;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.provider.Settings;
import android.text.Spannable;
import android.util.Log;
import android.view.IWindowManager;
import android.view.Display;
import android.view.LayoutInflater;
import android.widget.EditText;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SystemSettings extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener{
private static final String TAG = "SystemSettings";
private static final String KEY_POWER_BUTTON_TORCH = "power_button_torch";
private CheckBoxPreference mPowerButtonTorch;
private static final String KEY_CHRONUS = "chronus";
private static final String PREF_FORCE_DUAL_PANEL = "force_dualpanel";
private static final String PREF_CUSTOM_CARRIER_LABEL = "custom_carrier_label";
Preference mCustomLabel;
Context mContext;
String mCustomLabelText = null;
CheckBoxPreference mDualpane;
private boolean torchSupported() {
return getResources().getBoolean(R.bool.has_led_flash);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.system_settings);
mCustomLabel = findPreference(PREF_CUSTOM_CARRIER_LABEL);
updateCustomLabelTextSummary();
// Dont display the lock clock preference if its not installed
removePreferenceIfPackageNotInstalled(findPreference(KEY_CHRONUS));
mPowerButtonTorch = (CheckBoxPreference) findPreference(KEY_POWER_BUTTON_TORCH);
if (torchSupported()) {
mPowerButtonTorch.setChecked((Settings.System.getInt(getActivity().
getApplicationContext().getContentResolver(),
Settings.System.POWER_BUTTON_TORCH, 0) == 1));
} else {
getPreferenceScreen().removePreference(mPowerButtonTorch);
}
mDualpane = (CheckBoxPreference) findPreference(PREF_FORCE_DUAL_PANEL);
mDualpane.setOnPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mPowerButtonTorch) {
boolean enabled = mPowerButtonTorch.isChecked();
Settings.System.putInt(getContentResolver(), Settings.System.POWER_BUTTON_TORCH,
enabled ? 1 : 0);
return true;
} else if (preference == mCustomLabel) {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.custom_carrier_label_title);
alert.setMessage(R.string.custom_carrier_label_explain);
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(mCustomLabelText != null ? mCustomLabelText : "");
alert.setView(input);
alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = ((Spannable) input.getText()).toString();
Settings.System.putString(getActivity().getContentResolver(),
Settings.System.CUSTOM_CARRIER_LABEL, value);
updateCustomLabelTextSummary();
Intent i = new Intent();
i.setAction("com.android.settings.LABEL_CHANGED");
mContext.sendBroadcast(i);
}
});
alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
ContentResolver cr = getActivity().getContentResolver();
if (preference == mDualpane) {
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.FORCE_DUAL_PANEL,
((CheckBoxPreference)preference).isChecked() ? 0 : 1);
return true;
}
return false;
}
private boolean removePreferenceIfPackageNotInstalled(Preference preference) {
String intentUri=((PreferenceScreen) preference).getIntent().toUri(1);
Pattern pattern = Pattern.compile("component=([^/]+)/");
Matcher matcher = pattern.matcher(intentUri);
String packageName=matcher.find()?matcher.group(1):null;
if(packageName != null) {
try {
getPackageManager().getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
Log.e(TAG,"package "+packageName+" not installed, hiding preference.");
getPreferenceScreen().removePreference(preference);
return true;
}
}
return false;
}
private void updateCustomLabelTextSummary() {
mCustomLabelText = Settings.System.getString(getActivity().getContentResolver(),
Settings.System.CUSTOM_CARRIER_LABEL);
if (mCustomLabelText == null || mCustomLabelText.length() == 0) {
mCustomLabel.setSummary(R.string.custom_carrier_label_notset);
} else {
mCustomLabel.setSummary(mCustomLabelText);
}
}
}
logcat :
W/System.err(13551): Removed 2131231241
W/System.err(13551): Removed 2131231255
D/dalvikvm( 3528): GC_CONCURRENT freed 384K, 16% free 2993K/3552K, paused 2ms+4ms, total 33ms
D/dalvikvm(13551): GC_CONCURRENT freed 190K, 10% free 3282K/3644K, paused 2ms+8ms, total 37ms
D/AndroidRuntime(13551): Shutting down VM
W/dalvikvm(13551): threadid=1: thread exiting with uncaught exception (group=0x40d12600)
E/AndroidRuntime(13551): FATAL EXCEPTION: main
E/AndroidRuntime(13551): java.lang.NullPointerException
E/AndroidRuntime(13551): at com.android.settings.cyanogenmod.SystemSettings$1.onClick(SystemSettings.java:143)
E/AndroidRuntime(13551): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
E/AndroidRuntime(13551): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13551): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(13551): at android.app.ActivityThread.main(ActivityThread.java:5191)
E/AndroidRuntime(13551): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13551): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(13551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
E/AndroidRuntime(13551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
E/AndroidRuntime(13551): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 1108): Force finishing activity com.android.settings/.SubSettings
W/ActivityManager( 1108): Activity pause timeout for ActivityRecord{40ff74b8 u0 com.android.settings/.SubSettings}
D/dalvikvm(13124): GC_FOR_ALLOC freed 411K, 22% free 3616K/4608K, paused 28ms, total 34ms
I/Process (13551): Sending signal. PID: 13551 SIG: 9
W/InputDispatcher( 1108): channel '41188140 com.android.settings/com.android.settings.SubSettings (server)' ~ Consumer closed input channel or an error occurred. events=0x9
I/WindowState( 1108): WIN DEATH: Window{41369d90 u0 com.android.settings/com.android.settings.SubSettings}
I/ActivityManager( 1108): Process com.android.settings (pid 13551) has died.
E/InputDispatcher( 1108): channel '41188140 com.android.settings/com.android.settings.SubSettings (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 1108): channel '40ffd998 com.android.settings/com.android.settings.Settings (server)' ~ Consumer closed input channel or an error occurred. events=0x9
E/InputDispatcher( 1108): channel '40ffd998 com.android.settings/com.android.settings.Settings (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 1108): Attempted to unregister already unregistered input channel '41188140 com.android.settings/com.android.settings.SubSettings (server)'
W/InputDispatcher( 1108): Attempted to unregister already unregistered input channel '40ffd998 com.android.settings/com.android.settings.Settings (server)'
I/WindowState( 1108): WIN DEATH: Window{41188140 u0 com.android.settings/com.android.settings.SubSettings}
I/WindowState( 1108): WIN DEATH: Window{40ffd998 u0 com.android.settings/com.android.settings.Settings}
I/ActivityManager( 1108): Start proc com.android.settings for activity com.android.settings/.Settings: pid=13575 uid=1000 gids={41000, 1015, 1028, 3002, 3001, 3003, 3007}
W/WindowManager( 1108): Rebuild removed 7 windows but added 6
W/WindowManager( 1108): This window was lost: Window{41369d90 u0 com.android.settings/com.android.settings.SubSettings EXITING}
W/WindowManager( 1108): mDisplayId=0 mSession=Session{41e7d3b0 13551:1000} mClient=android.os.BinderProxy#4108dde8
line 143 is as follows :
mContext.sendBroadcast(i);
anyone got an idea whats going on here?
mContext is null, since it is declared at the top of your class, but never given anything to hold.
You could probably use getActivity() in place of mContext since this is a Fragment and Activity is a Context subclass.
This means
mContext.sendBroadcast(i);
should be
getActivity().sendBroadcast(i);

Categories