Android Weather app crashing-network error - java

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.

Related

RuntimeException by using Google Youtube Api v3 in my android app

I want to get the list of videos from Youtube channel.
You will see below the class to connect to Youtube and my Activity that interacts with this class. I get an exception "java.lang.RuntimeException: Unable to start activity VideoListActivity" when calling YouTube.Search.List.execute();
I am new in android, so I think there is a stupid mistake. Please help to find it, or maybe suggest the another way to get data from Youtube.
YoutubeConnector class
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class YoutubeConnector {
private static YouTube youtube;
private static YouTube.Search.List query;
public static final String KEY = DeveloperKey.DEVELOPER_KEY;
public static List<VideoItem> search() throws IOException {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {
}
}).setApplicationName(R.string.app_name).build();
query = youtube.search().list("id,snippet");
query.setKey(KEY);
query.setType("video");
query.setChannelId("**************");
query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();
List<VideoItem> items = new ArrayList<VideoItem>();
for (SearchResult result : results) {
VideoItem item = new VideoItem();
item.setTitle(result.getSnippet().getTitle());
item.setDescription(result.getSnippet().getDescription());
item.setThumbnailURL(result.getSnippet().getThumbnails().getDefault().getUrl());
item.setId(result.getId().getVideoId());
items.add(item);
}
return items;
}
}
VideoListActivity class
public class VideoListActivity extends ListActivity{
List<VideoItem> videoFileList;
public class VideoAapter extends ArrayAdapter{
//.....................
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
setListAdapter(new VideoAapter(VideoListActivity.this, R.layout.list_item_video, videoFileList));
}
}
Logcat
06-16 18:14:56.926 30817-30817/com.example.alex.youtubecanal W/art: Failed to find OatDexFile for DexFile /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex ( canonical path /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex) with checksum 0x7eb43558 in OatFile /data/data/com.example.alex.youtubecanal/cache/slice-slice_5-classes.dex
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isShipBuild true
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SMARTBONDING_FEATURE_ENABLED is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal D/AndroidRuntime: Shutting down VM
06-16 18:14:57.641 30817-30817/com.example.alex.youtubecanal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alex.youtubecanal, PID: 30817
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.alex.youtubecanal/com.example.alex.youtubecanal.VideoListActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3133)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:245)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:128)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:370)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:93)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.example.alex.youtubecanal.YoutubeConnector.search(YoutubeConnector.java:37)
at com.example.alex.youtubecanal.VideoListActivity.onCreate(VideoListActivity.java:58)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243) 
at android.app.ActivityThread.access$1000(ActivityThread.java:218) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6917) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
You need to run the YoutubeConnector.search outside of onCreate() in an Async Thread. This basically means that the method is stalling the program and will cause the program to crash or hang. To fix, create a new class called Search for example:
SearchClass.java:
import android.os.AsyncTask;
import java.io.IOException;
public class Search extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String a){
VideoListActivity.context.updateAdapter();
}
}
VideoListActivity.java:
public class VideoListActivity extends ListActivity{
static List<VideoItem> videoFileList;
static Context context;
public class VideoAapter extends ArrayAdapter{
//.....................
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Search search= new Search();
search.execute(new String[]{});
}
public void updateAdapter(ArrayList<String> list) {
setListAdapter(new VideoAapter(VideoListActivity.this,R.layout.list_item_video, videoFileList));
}
}
Hopefully this will work :). If it does not, just post the error, and we'll get back. Good luck!
It looks like the problem is coming from a NetworkOnMainThreadException. Check out this example. Hope it helps!

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

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();
}
}

ASyncTask with progressdialog and button

I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}

IBM Worklight - Unable to get network signal strength in Android

Below is my Java implementation. The idea is to display myUtilString in an edit text in order to see the signal strength in a Hybrid android app while in a WL.NativePage, but I get nothing.
I have tested the app on a real device, changing to 2G, 3G and LTE but I don't receive anything. I have implemented a function called onSignalStrengthsChanged, but I cant figure out what is wrong.
In LogCat there is nothing of interest; maybe onSignalStrengthsChanged never is fired.
package com.AndroidShowNativePage;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import android.telephony.gsm.GsmCellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.CellLocation;
import android.webkit.WebView;
public class HelloNative extends Activity {
EditText editText = null;
EditText editText1 = null;
String myUtilString = "";
private TelephonyManager tm ;
private DroidPhoneStateListener listener;
private GsmCellLocation location;
public void GSM(Activity activity, WebView view) {
tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
listener = new DroidPhoneStateListener(view);
location = new GsmCellLocation();
}
public void listen() {
tm.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
//TODO
//tm.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTH);
//tm.listen(listener, PhoneStateListener.LISTEN_CELL_LOCATION);
//tm.listen(listener, PhoneStateListener.LISTEN_DATA_ACTIVITY);
}
public void unlisten() {
tm.listen(listener, PhoneStateListener.LISTEN_NONE);
}
public int getCid() {
return location.getCid();
}
public int getLac() {
return location.getLac();
}
/*
* ???? public int getPsc() { return location.getPsc(); }
*/
private class DroidPhoneStateListener extends PhoneStateListener {
private WebView view;
DroidPhoneStateListener(WebView view) {
this.view = view;
}
#Override
public void onCellLocationChanged(CellLocation location) {
myUtilString = ( "onCellLocationChanged: " + location.toString());
// view.loadUrl("javascript:droid.Accelerometer.onUpdate();
}
#Override
public void onDataConnectionStateChanged(int state, int networkType) {
myUtilString =( "onDataConnectionStateChanged: " + state + ":" + networkType);
}
#Override
public void onSignalStrengthsChanged(SignalStrength s) {
super.onSignalStrengthsChanged(s);
String r = s.getGsmSignalStrength() + ":" + s.getCdmaDbm() + ":"
+ s.getCdmaEcio() + ":" + s.getEvdoDbm() + ":"
+ s.getEvdoEcio() + ":" + s.getEvdoSnr() + ":"
+ s.getGsmBitErrorRate();
myUtilString = ("hello Change('" + r.toString()+ "');");
}
#Override
public void onSignalStrengthChanged(int asu) {
myUtilString = ( "onSignalStrengthChanged: " + asu);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String name = getIntent().getStringExtra("nameParam");
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
TextView textView1 = new TextView(this);
textView1.setText("Name received from JavaScript :: " + name);
TextView textView2 = new TextView(this);
textView2.setText("Enter the phone number");
editText = new EditText(this);
editText.setText("1234567890");
editText1 = new EditText(this);
editText1.setText("any measure on dBd");
Button submitButton = new Button(this);
submitButton.setText("Return to the Web App");
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = editText.getText().toString();
Intent phoneNumberInfo = new Intent();
phoneNumberInfo.putExtra("phoneNumber", phoneNumber);
setResult(RESULT_OK, phoneNumberInfo);
finish();
}
});
Button submitMeasure = new Button(this);
submitMeasure.setText("Go measure");
submitMeasure.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
editText1.setText( myUtilString );
}
});
linearLayout.addView(textView1);
linearLayout.addView(textView2);
linearLayout.addView(editText);
linearLayout.addView(submitButton);
linearLayout.addView(submitMeasure);
linearLayout.addView(editText1);
}
}
here is LogCat:
05-08 12:06:30.140: D/SoftKeyboardDetect(1078): Ignore this event
05-08 12:06:31.190: D/WLDroidGap(1078): Started copying files to local storage...
05-08 12:06:48.800: D/dalvikvm(1078): GC_FOR_ALLOC freed 494K, 15% free 3318K/3896K, paused 35ms, total 35ms
05-08 12:06:59.950: D/dalvikvm(1078): GC_FOR_ALLOC freed 370K, 16% free 3319K/3908K, paused 34ms, total 34ms
05-08 12:07:10.540: D/WLDroidGap(1078): Finished copying files to local storage...
05-08 12:07:10.550: D/WLDroidGap(1078): no need to check web resource integrity
05-08 12:07:10.690: D/CordovaWebView(1078): >>> loadUrl(file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:10.690: D/PluginManager(1078): init()
05-08 12:07:10.730: D/CordovaWebView(1078): >>> loadUrlNow()
05-08 12:07:12.560: D/CordovaActivity(1078): onMessage(onPageStarted,file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:14.610: D/CordovaWebViewClient(1078): onPageFinished(file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:14.610: D/CordovaActivity(1078): onMessage(onPageFinished,file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:16.650: D/CordovaActivity(1078): onMessage(spinner,stop)
05-08 12:07:17.250: D/CordovaActivity(1078): onMessage(spinner,stop)
05-08 12:07:17.260: W/PluginManager(1078): THREAD WARNING: exec() call to App.show blocked the main thread for 21ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.400: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:17.400: D/CordovaActivity(1078): onMessage(networkconnection,3g)
05-08 12:07:17.420: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:17.660: D/dalvikvm(1078): GC_FOR_ALLOC freed 458K, 14% free 3365K/3908K, paused 36ms, total 39ms
05-08 12:07:17.710: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.writePref blocked the main thread for 95ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.780: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.writePref blocked the main thread for 35ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.790: D/CordovaWebView(1078): >>> loadUrl(file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:17.810: D/PluginManager(1078): init()
05-08 12:07:17.810: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.loadSkin blocked the main thread for 29ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.820: D/CordovaWebView(1078): >>> loadUrlNow()
05-08 12:07:18.020: D/CordovaActivity(1078): onMessage(onPageStarted,file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:23.320: D/CordovaActivity(1078): onMessage(spinner,stop)
05-08 12:07:23.370: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:23.400: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:23.400: D/CordovaActivity(1078): onMessage(networkconnection,3g)
05-08 12:07:24.010: D/CordovaWebViewClient(1078): onPageFinished(file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:24.010: D/CordovaActivity(1078): onMessage(onPageFinished,file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:24.240: I/Choreographer(1078): Skipped 32 frames! The application may be doing too much work on its main thread.
05-08 12:07:24.440: D/AndroidShowNativePage(1078): wlclient init started
05-08 12:07:24.530: D/AndroidShowNativePage(1078): Read cookies: null
05-08 12:07:24.560: D/AndroidShowNativePage(1078): CookieMgr read cookies: {}
05-08 12:07:24.870: W/AndroidShowNativePage(1078): Your application is using the WL.OptionsMenu API. Note that, if your application targets Android 3.0 (API level 11) or higher, WL.OptionsMenu might have no effect, depending on the device.
05-08 12:07:24.970: W/PluginManager(1078): THREAD WARNING: exec() call to DeviceAuth.getDeviceUUID blocked the main thread for 24ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:25.000: D/AndroidShowNativePage(1078): addDeviceIDHeader deviceIDSuccessCallback
05-08 12:07:25.050: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.writePref blocked the main thread for 21ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:25.080: D/AndroidShowNativePage(1078): connectOnStartup finalizeInit
05-08 12:07:25.190: D/AndroidShowNativePage(1078): before: app init onSuccess
05-08 12:07:25.310: D/AndroidShowNativePage(1078): after: app init onSuccess
05-08 12:07:25.350: D/AndroidShowNativePage(1078): added onPause event handler
05-08 12:07:25.370: D/AndroidShowNativePage(1078): wlclient init success
05-08 12:26:11.550: D/CordovaActivity(1078): Paused the application!
05-08 12:26:11.550: D/CordovaWebView(1078): Handle the pause
05-08 12:26:11.650: W/PluginManager(1078): THREAD WARNING: exec() call to NativePage.show blocked the main thread for 151ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:26:12.620: I/Choreographer(1078): Skipped 60 frames! The application may be doing too much work on its main thread.
05-08 12:26:13.040: D/AndroidShowNativePage(1078): Flush called
05-08 12:26:17.070: I/Choreographer(1078): Skipped 75 frames! The application may be doing too much work on its main thread.
Do you get any errors either in Eclipse console or in the LogCat view? Provide the output from LogCat, that should help. Edit the question with this information.
The following permission needs to be added to AndroidManifest.xml as well:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Edit:
There is also the following tutorial to get signal strength: http://www.firstdroid.com/2010/05/12/get-provider-gsm-signal-strength/
I've followed it, and it worked for me in the Android emulator.
This is my Java implementation:
package com.testapp;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class HelloNative extends Activity {
TelephonyManager tm;
MyPhoneStateListener MyListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyListener = new MyPhoneStateListener();
tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
Button submitButton = new Button(this);
submitButton.setText("Return to the Web App");
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_OK);
finish();
};
});
linearLayout.addView(submitButton);
}
private class MyPhoneStateListener extends PhoneStateListener
{
/* Get the Signal strength from the provider, each time there is an update */
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
super.onSignalStrengthsChanged(signalStrength);
Toast.makeText(getApplicationContext(), "Signal strength is: "
+ String.valueOf(signalStrength.getGsmSignalStrength()), Toast.LENGTH_SHORT).show();
}
};
}

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