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);
Related
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();
}
}
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.
I have made my application using android SDK 2.2 version and now when I am running my app on android SDK 4.0.3 it's not running.
I have given the min and the max sdk in the manifest file.
I am new in android and want to run my app for the lower and higher versions both. Can anybody tell me how can I do this. Any help is appreciated.
Code for splash class
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final SplashScreen sPlashScreen = this;
// thread for displaying the SplashScreen
splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
finish();
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
stop();
}
}
};
splashTread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized(splashTread){
splashTread.notifyAll();
}
}
return true;
}
}
EDIT: My logcat
06-07 10:24:18.710: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:18.760: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:18.890: D/dalvikvm(1461): GC_FOR_ALLOC freed 45K, 4% free 6541K/6787K, paused 74ms
06-07 10:24:18.900: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.333MB for 921616-byte allocation
06-07 10:24:19.010: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.100: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:19.140: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 5% free 7440K/7751K, paused 5ms+5ms
06-07 10:24:19.240: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7440K/7751K, paused 97ms
06-07 10:24:19.240: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.723MB for 409936-byte allocation
06-07 10:24:19.320: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7841K/8199K, paused 61ms
06-07 10:24:19.589: D/gralloc_goldfish(1461): Emulator without GPU emulation detected.
06-07 10:24:19.669: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.779: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:24.600: W/dalvikvm(1461): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
06-07 10:24:24.600: E/AndroidRuntime(1461): FATAL EXCEPTION: Thread-78
06-07 10:24:24.600: E/AndroidRuntime(1461): java.lang.UnsupportedOperationException
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1076)
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1063)
06-07 10:24:24.600: E/AndroidRuntime(1461): at com.Cricket_trivia.in.SplashScreen$1.run(SplashScreen.java:40)
06-07 10:24:26.209: D/dalvikvm(1461): GC_FOR_ALLOC freed 1037K, 15% free 7022K/8199K, paused 62ms
06-07 10:24:26.209: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.509MB for 614416-byte allocation
06-07 10:24:26.440: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 8% free 7621K/8199K, paused 4ms+5ms
06-07 10:24:26.610: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:26.640: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
The reason why your app is crashing on 4.0.3 but not 2.2 is most likely because you are performing an expensive operation on the UI thread. Blocking the UI thread is very bad practice... don't do it!! Previous versions of Android (i.e. pre-ICS versions) didn't care when you did this and let your app run as is. In 4.0 and above, however, the OS checks against this and crashes your app if you ever perform a potentially expensive operation on the UI thread (such as a network connection, etc.).
You have provided basically no information on what the problem is in your question, so that's all I can really do to help you out.
Edit:
Does something like this work?
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
}
return true;
}
Don't you threads because it is creating the problem in the higher version. Use the code below to show the splash screen.
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
MyCount counter = new MyCount(4000, 4000);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
counter.start();
}
public class MyCount extends CountDownTimer
{
public MyCount(long csecond, long countDownInterval)
{
super(csecond, countDownInterval);
}
#Override
public void onFinish() {
finish();
Intent intent = new Intent();
intent.setClass(SplashScreen.this, K_trivia_cricketActivity.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}
}
I think it will work for you
I have a simple code that is supposed to do one task, when the button is clicked download a file, save it to the SD card, and open it. Everything works except during the download, for larger files, the connection drops and the progress bar hangs - almost always at 20%. I have searched and searched and cannot figure out what to do to keep the connection alive and allow the download to complete. Any ideas how to keep the connection alive so the download completes instead of stalling at 20%?
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DownloadTestActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgressDialog = new ProgressDialog(DownloadTestActivity.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/file.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.doc");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[8192];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
private void showPdf() {
// TODO Auto-generated method stub
if(mProgressDialog != null){
mProgressDialog.dismiss();
}
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.doc");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/msword");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/msword");
startActivity(intent);
}
}
}
Edit with logcat information:
--------- beginning of /dev/log/system
W/InputManagerService( 199): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4137b898
--------- beginning of /dev/log/main
D/AndroidRuntime(20673):
D/AndroidRuntime(20673): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20673): CheckJNI is OFF
D/AndroidRuntime(20673): Calling main entry com.android.commands.pm.Pm
D/AndroidRuntime(20673): Shutting down VM
D/dalvikvm(20673): GC_CONCURRENT freed 101K, 82% free 467K/2560K, paused 1ms+0ms
D/dalvikvm(20673): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20673): NOTE: attach of thread 'Binder Thread #3' failed
D/AndroidRuntime(20687):
D/AndroidRuntime(20687): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20687): CheckJNI is OFF
D/AndroidRuntime(20687): Calling main entry com.android.commands.am.Am
I/ActivityManager( 199): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.myapp/.Activity} from pid 20687
D/AndroidRuntime(20687): Shutting down VM
D/dalvikvm(20687): GC_CONCURRENT freed 102K, 81% free 489K/2560K, paused 0ms+0ms
D/jdwp (20687): Got wake-up signal, bailing out of select
D/dalvikvm(20687): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20687): NOTE: attach of thread 'Binder Thread #3' failed
D/dalvikvm(20698): Late-enabling CheckJNI
I/ActivityManager( 199): Start proc com.myapp for activity com.myapp/.Activity: pid=20698 uid=10102 gids={1015, 3003}
I/dalvikvm(20698): Turning on JNI app bug workarounds for target SDK version 10...
V/PhoneStatusBar( 271): setLightsOn(true)
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Displayed com.myapp/.Activity: +197ms
W/InputManagerService( 199): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#4199ed28 (uid=10098 pid=20011)
I/ActivityManager( 199): START {cmp=com.myapp/.Choice} from pid 20698
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
V/PhoneStatusBar( 271): setLightsOn(true)
I/ActivityManager( 199): Displayed com.myapp/.Choice: +93ms
D/ANDRO_ASYNC(20698): Lenght of file: 736768
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
W/NetworkStats( 199): found non-monotonic values; saving to dropbox
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Force stopping package com.myapp uid=10102
I/ActivityManager( 199): Killing proc 20698:com.myapp/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.myapp/.Choice}: app died, no saved state
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
I/ActivityManager( 199): Force finishing activity ActivityRecord{418450c8 com.myapp/.Activity}
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
W/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp/.Activity (server)' ~ Consumer closed input channel or an error occurred. events=0x8
E/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp.Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 199): Attempted to unregister already unregistered input channel '417b41f0 com.myapp/com.myapp.Activity (server)'
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41c7ffc8 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
I/WindowManager( 199): WIN DEATH: Window{4175b280 com.myapp/com.myapp.Choice paused=false}
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41758028 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
W/InputManagerService( 199): Got RemoteException sending setActive(false) notification to pid 20698 uid 10102
D/dalvikvm(20011): GC_CONCURRENT freed 460K, 32% free 9468K/13767K, paused 3ms+4ms
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
I've tried to download your file a few times, looks like download stalls for a few seconds here and there, and it might trigger a timeout in your application. Try to specify timeouts explicitly in range 10-20 seconds.
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet get = new HttpGet("your url comes here");
protected String[] doInBackground(Void... v) {
HttpParams httpParameters = new BasicHttpParams();
// set the timeout in milliseconds until a connection is established
// the default value is zero, that means the timeout is not used
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// set the default socket timeout (SO_TIMEOUT) in milliseconds
// which is the timeout for waiting for data
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient.setParams(httpParameters);
try {
HttpEntity entity = httpclient.execute( get ).getEntity();
FileOutputStream output = new FileOutputStream(outputFile);
entity.writeTo(output);
output.close();
// return something, maybe?
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return null;
}
What seems to be the problem is that process 199 in your logcat seem to be your activity, but then it shows:
I/ActivityManager( 199): Force stopping package com.viperean.atcassistant uid=10102
I/ActivityManager( 199): Killing proc 20698:com.viperean.atcassistant/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.viperean.atcassistant/.atcChoice}: app died, no saved state
(and the second line shows that it is killing your asynctask...).
I don't think there is anything wrong with the download code by itself. I think you should look more in the activity (what are you doing during that time beside that asynctask, what are you displaying on the screen...etc...).
Seems also that you are pretty low in heap space.
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
Those are from the garbage collection and happen just before your app crashed, maybe that could be a problem too?
every thread in Android is being killed by the system if it doesn't respond for more than five minutes. maybe you should consider downloading as a service or overriding the onProgress and get the thread to stay alive
I'm trying to show an about page to the users of my wallpaper app when they click the about button however i get leaked window errors in a log cat and the activity quits before it shows the dialog.
Here is the code:
/*
*
* Sensational Wallpapers Pack 1
*
* Wallpaper Designed by AZ2ENVY
*
*/
package com.death2all110.SensationalWallpapers1;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.widget.Button;
import android.content.DialogInterface;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import com.death2all110.SensationalWallpapers1.R;
public class wallpaper extends Activity implements AdapterView.OnItemSelectedListener,
OnClickListener {
private Gallery mGallery;
private ImageView mImageView;
private boolean mIsWallpaperSet;
private Bitmap mBitmap;
private ArrayList<Integer> mThumbs;
private ArrayList<Integer> mImages;
private WallpaperLoader mLoader;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
findWallpapers();
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setCallbackDuringFling(false);
findViewById(R.id.set).setOnClickListener(this);
mImageView = (ImageView) findViewById(R.id.wallpaper);
Button alert = (Button) findViewById(R.id.about_page);
alert.setOnClickListener(this);
}
private void findWallpapers() {
mThumbs = new ArrayList<Integer>(24);
mImages = new ArrayList<Integer>(24);
final Resources resources = getResources();
final String packageName = getApplication().getPackageName();
addWallpapers(resources, packageName, R.array.wallpapers);
addWallpapers(resources, packageName, R.array.extra_wallpapers);
}
private void addWallpapers(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra + "_small",
"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
mImages.add(res);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel(true);
mLoader = null;
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel();
}
mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
}
/*
* When using touch if you tap an image it triggers both the onItemClick and
* the onTouchEvent causing the wallpaper to be set twice. Ensure we only
* set the wallpaper once.
*/
private void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(mImages.get(position));
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e("Paperless System", "Failed to set wallpaper: " + e);
}
}
public void onNothingSelected(AdapterView parent) {
}
private class ImageAdapter extends BaseAdapter {
private LayoutInflater mLayoutInflater;
ImageAdapter(wallpaper context) {
mLayoutInflater = context.getLayoutInflater();
}
public int getCount() {
return mThumbs.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if (convertView == null) {
image = (ImageView) mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
} else {
image = (ImageView) convertView;
}
int thumbRes = mThumbs.get(position);
image.setImageResource(thumbRes);
Drawable thumbDrawable = image.getDrawable();
if (thumbDrawable != null) {
thumbDrawable.setDither(true);
} else {
Log.e("Paperless System", String.format(
"Error decoding thumbnail resId=%d for wallpaper #%d",
thumbRes, position));
}
return image;
}
}
public void onClick(View v) {
selectWallpaper(mGallery.getSelectedItemPosition());
}
public void onClick1(View about) {
// If "About was clicked.....
if (about == findViewById(R.id.about_page)) {
// Prepare the alert box!!
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set message to display...
alertbox.setMessage("Test.....");
// Add a neutral button to the alert box AND assign a listener for said button...
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener(){
// click listener for box
public void onClick(DialogInterface arg0, int arg1){
// Button was clicked!!
Toast.makeText(getApplicationContext(), "Dialog closed successfully!", Toast.LENGTH_LONG).show();
}
});
// show it!!!
alertbox.show();
}
}
class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
BitmapFactory.Options mOptions;
WallpaperLoader() {
mOptions = new BitmapFactory.Options();
mOptions.inDither = false;
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
protected Bitmap doInBackground(Integer... params) {
if (isCancelled()) return null;
try {
return BitmapFactory.decodeResource(getResources(),
mImages.get(params[0]), mOptions);
} catch (OutOfMemoryError e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap b) {
if (b == null) return;
if (!isCancelled() && !mOptions.mCancel) {
// Help the GC
if (mBitmap != null) {
mBitmap.recycle();
}
final ImageView view = mImageView;
view.setImageBitmap(b);
mBitmap = b;
final Drawable drawable = view.getDrawable();
drawable.setFilterBitmap(true);
drawable.setDither(true);
view.postInvalidate();
mLoader = null;
} else {
b.recycle();
}
}
void cancel() {
mOptions.requestCancelDecode();
super.cancel(true);
}
}
}
Here is the logcat:
I/ActivityManager( 59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.death2all110.SensationalWallpapers1/.wallpaper }
I/ActivityManager( 59): Displayed activity com.death2all110.SensationalWallpapers1/.wallpaper: 474 ms (total 474 ms)
D/dalvikvm( 286): GC freed 1448 objects / 151304 bytes in 131ms
D/dalvikvm( 106): GC freed 2485 objects / 144824 bytes in 245ms
D/dalvikvm( 59): threadid=15: bogus mon 1+0>0; adjusting
D/dalvikvm( 59): GC freed 3666 objects / 207344 bytes in 360ms
D/dalvikvm( 59): GC freed 459 objects / 21096 bytes in 357ms
E/WindowManager( 286): Activity com.death2all110.SensationalWallpapers1.wallpaper has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44c0f3d0 that was originally added here
E/WindowManager( 286): android.view.WindowLeaked: Activity com.death2all110.SensationalWallpapers1.wallpaper has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44c0f3d0 that was originally added here
E/WindowManager( 286): at android.view.ViewRoot.<init>(ViewRoot.java:227)
E/WindowManager( 286): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
E/WindowManager( 286): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
E/WindowManager( 286): at android.view.Window$LocalWindowManager.addView(Window.java:424)
E/WindowManager( 286): at android.app.Dialog.show(Dialog.java:239)
E/WindowManager( 286): at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
E/WindowManager( 286): at com.death2all110.SensationalWallpapers1.wallpaper.onClick(wallpaper.java:244)
E/WindowManager( 286): at android.view.View.performClick(View.java:2364)
E/WindowManager( 286): at android.view.View.onTouchEvent(View.java:4179)
E/WindowManager( 286): at android.widget.TextView.onTouchEvent(TextView.java:6541)
E/WindowManager( 286): at android.view.View.dispatchTouchEvent(View.java:3709)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
E/WindowManager( 286): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
E/WindowManager( 286): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
E/WindowManager( 286): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
E/WindowManager( 286): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager( 286): at android.os.Looper.loop(Looper.java:123)
E/WindowManager( 286): at android.app.ActivityThread.main(ActivityThread.java:4363)
E/WindowManager( 286): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager( 286): at java.lang.reflect.Method.invoke(Method.java:521)
E/WindowManager( 286): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
E/WindowManager( 286): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
E/WindowManager( 286): at dalvik.system.NativeStart.main(Native Method)
D/dalvikvm( 286): GC freed 1704 objects / 168544 bytes in 330ms
Not only does it have a leaked window, but when that button is clicked it also sets the wallpaper...
Any help would be greatly appreciated
change this
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
with
AlertDialog.Builder alertbox = new AlertDialog.Builder(yourActivity.this);
EDITED:
Button alert = (Button) findViewById(R.id.about_page);
alert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do ur logic
});
make above change to your button click
The error shows that you are using the bad context here,
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
Try to use the right context here,
getApplicationContext(); or getParent() may solve your issue...
Thanks,
Suri Sahani.