How to notifyDataSetChanged after Asynctask In Fragment - java

I'm unable to call notifyDataSetChanged without the application crashing.
ListFragment class:
public class ServerListFragment extends ListFragment implements OnTaskCompleteListener {
private AsyncTaskManager mAsyncTaskManager;
private ServersDataSource datasource;
private ArrayList<Server> servers;
private boolean paused = false;
private boolean generateList = true;
private String operation = "";
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(String id);
}
/**
* A dummy implementation of the {#link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
#Override
public void onItemSelected(String id) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ServerListFragment() {
}
/*
* Default list adapter
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retainInstance and survive on configuration changes (rotation)
setRetainInstance(true);
// Create manager and set this activity as context and listener
mAsyncTaskManager = new AsyncTaskManager(getActivity(), this);
// Handle task that can be retained before
mAsyncTaskManager.handleRetainedTask(getActivity().getLastNonConfigurationInstance());
// start async task
getServersServices();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState
.getInt(STATE_ACTIVATED_POSITION));
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
public void notifyDataSetChanged() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
}
public void getServersServices() {
datasource = new ServersDataSource(getActivity());
datasource.open();
datasource.emptyServersTable();
operation = "GetSevers";
mAsyncTaskManager.setupTask(new Task(getResources(), getActivity(), getResources().getString(R.string.refreshing), operation, 0, ""));
}
public void onTaskComplete(Task task) {
if (task.isCancelled()) {
// Report about cancel
if (DEBUG) Log.i(TAG, "ServersStatus onTaskComplete task cancel");
} else {
// Get result
Boolean result = null;
try {
result = task.get();
} catch (Exception e) {
if (DEBUG) Log.e(TAG, "ServersStatus onTaskComplete error: " + e.toString());
}
// Report about result
servers = datasource.getAllServers();
if(servers.size() > 0 && generateList){
DummyContent.setContext(servers);
notifyDataSetChanged();
}
operation = "";
}
generateList = true;
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
if (message.equals("Refresh list")) {
servers = datasource.getAllServers();
getServersServices();
}
}
};
}
Error log:
> 09-30 15:15:39.360: E/AndroidRuntime(14322): FATAL EXCEPTION: main
> 09-30 15:15:39.360: E/AndroidRuntime(14322):
> java.lang.NullPointerException 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> com.ww.www.ServerListFragment.notifyDataSetChanged(ServerListFragment.java:307)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.ww.www.ServerListFragment.onTaskComplete(ServerListFragment.java:385)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.ww.www.core.AsyncTaskManager.onComplete(AsyncTaskManager.java:67)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.ww.www.core.Task.onPostExecute(Task.java:330) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> com.ww.www.core.Task.onPostExecute(Task.java:1) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> android.os.AsyncTask.finish(AsyncTask.java:631) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> android.os.AsyncTask.access$600(AsyncTask.java:177) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> android.os.Handler.dispatchMessage(Handler.java:99) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> android.os.Looper.loop(Looper.java:137) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> android.app.ActivityThread.main(ActivityThread.java:4898) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> java.lang.reflect.Method.invokeNative(Native Method) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> java.lang.reflect.Method.invoke(Method.java:511) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> dalvik.system.NativeStart.main(Native Method)

I can see that you are using the example that eclipse gives regarding master detail flow with the DummyContent class, but you have removed this peace of code which is vital for this code to work
setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
DummyContent.ITEMS));
put it back in the onCreate

Unable to see adapter in your code. Please setAdapter.

I don'd see ListFragment.setListAdapter being called anywhere. Which is the reason for the crash noticed here.
public void notifyDataSetChanged() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
}
Here, you are trying to get the List adapter and call notifyDataSetChanged(). Since there's no list adapter, it will result in NPE.

The problem is probably in this method:
public void notifyDataSetChanged() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
}
I guess that getListAdapter() returns null because I cant see that you are setting any adapter to this ListFragment anywhere.

Related

Android NULL Pointer Exception and Fragment data transmission [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
09-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
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:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}

error on exit activity extends FragmentActivity and contains ViewPager

there is java class extends FragmentActivity, min-sdk is 10
i used ViewPager with FragmentManager to show images in viewpager indicator
some times it shows me error when i want to exit activity
private static ArrayList<PgItem> image_resource;
public static ArrayList<ProjectItem> items = new ArrayList<ProjectItem>();
private static ViewPager v_pager;
private static TitlePageIndicator pagerIndicator;
public static FragmentManager fgmanger;
public static void setSIAdapter(ArrayList<ProjectItem> inputArray , int ex){
switch (ex){
case 0:
Log.i(App.logs.WEBSERVICE, "CertificateAsync >> inputArray.size : " + inputArray.size());
if(!inputArray.isEmpty()) {
items.clear();
items.addAll(inputArray);
image_resource = new ArrayList<PgItem>();
image_resource.clear();
for (int i = 0; i < inputArray.size(); i++) {
String image = ""+inputArray.get(i).getPrjImage();
if(image.trim().length() > 0 && image.replace(""+App.webServiceConfigs.ROOT , "").trim().length() > 0) {
String text = ""+inputArray.get(i).getPrjTitle();
String ext = image.substring(image.lastIndexOf(".") , image.length());
if(!image.toLowerCase().contains("_xl"+ext)){
image = image.replace(ext , "_XL"+ext);
}
PgItem item = new PgItem(image, text);
image_resource.add(item);
Log.i(App.logs.TEST, "image_resource.image_name # " + (image_resource.size()-1) + " : " + image_resource.get(image_resource.size()-1).getImage());
}
}
FragmentAdapter adapter = new FragmentAdapter(fgmanger , image_resource);
if(v_pager != null){
v_pager.setAdapter(adapter); // Error Line
pagerIndicator.setViewPager(v_pager);
pagerIndicator.setTextSize(UIHelpers.textFont-2);
pagerIndicator.setSelectedBold(true);
pagerIndicator.setSelectedColor(Color.parseColor("#595458"));
pagerIndicator.setTextColor(Color.parseColor("#9E9E9E"));
pagerIndicator.setTypeface(Typeface.createFromAsset(App.configs.currentActivity.getAssets(), "yekan.ttf"));
}
//ImagePagerAdapterPg adapter = new ImagePagerAdapterPg(image_resource);
// v_pager.setAdapter(adapter);
}
break;
case -1:
Toast toastProtocol = Toast.makeText(App.configs.context , App.configs.context.getString(R.string.PROTOCOL_EXCEPTION) , Toast.LENGTH_LONG);
toastProtocol.setGravity(Gravity.CENTER, 0, (int) (UIHelpers.width * 0.25));
toastProtocol.show();
if(App.webServiceConfigs.connectionTimeOut <= 18000) {
App.webServiceConfigs.connectionTimeOut += 3000;
}
if(App.webServiceConfigs.socketTimeOut <= 18000) {
App.webServiceConfigs.socketTimeOut += 3000;
}
callWebservice();
break;
case -2:
Toast toastIO = Toast.makeText(App.configs.context , App.configs.context.getString(R.string.IO_EXCEPTION) , Toast.LENGTH_LONG);
toastIO.setGravity(Gravity.CENTER, 0, (int) (UIHelpers.width * 0.25));
toastIO.show();
if(App.webServiceConfigs.connectionTimeOut <= 20000) {
App.webServiceConfigs.connectionTimeOut += 3000;
}
if(App.webServiceConfigs.socketTimeOut <= 20000) {
App.webServiceConfigs.socketTimeOut += 3000;
}
callWebservice();
break;
case -3:
break;
case -4:
break;
}
}
i load images from cache and show to user, then connect to server and update image adapter again.
it shows me error :
05-19 17:56:27.213 9768-9768/com.emaarIt.app.Bernoulli E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1358)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:578)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139)
at android.support.v4.view.ViewPager.setAdapter(ViewPager.java:415)
at com.emaarIt.app.Bernoulli.activities.ProjectGalleryActivity.setSIAdapter(ProjectGalleryActivity.java:225)
at com.emaarIt.app.Bernoulli.webservice.modules.ProjectGalleryAsync.onPostExecute(ProjectGalleryAsync.java:78)
at com.emaarIt.app.Bernoulli.webservice.modules.ProjectGalleryAsync.onPostExecute(ProjectGalleryAsync.java:32)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4441)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Cause:
The problem here is that after your activity got destroyed, the AsyncTask was still working and when it finishes it's work it will call AsyncTask's OnPostExecute() callback method and you are setting the adapter of the ViewPager which contacts the Activity to add the Fragments to the back stack and that can't happen because your activity got destroyed.
Proposed Solution:
You can hold a reference to your AsyncTask object and cancel it on the Activity's onDestroy() callback.
protected void onDestroy() {
super.onDestroy();
// cancel the task
if(asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
asyncTask.cancel(true);
}
}
What AsyncTask.cancel() do?
Calling this method will result in onCancelled(Object) being invoked
on the UI thread after doInBackground(Object[]) returns. Calling this
method guarantees that onPostExecute(Object) is never invoked.

Android internet connection issue

I am writing an app that uses internet, i have given it the following permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NETWORK"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
all is fine when on WIFI but when it connects to H+ 3G or 4G it stops working at a POST or GET. I already put all the tasks that request or post something to the server in a aSyncTask but to no result.
Is there something i am missing?
EDIT:
a activity with code
public class ParkeerActivity extends ActionBarActivity {
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parkeer);
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
datePicker.init(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR), new DatePicker.OnDateChangedListener() {#
Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
updateSpacesLeft();
}
});
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {#
Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
updateSpacesLeft();
}
});
Button reservationBtn = (Button) findViewById(R.id.reservationButton);
reservationBtn.setEnabled(false);
reservationBtn.setOnClickListener(new View.OnClickListener() {#
Override
public void onClick(View v) {
reservationClicked();
}
});
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_parkeer, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void reservationClicked() {
AsyncTask < Void, Void, String > task = new AsyncTask < Void, Void, String > () {#
Override
protected String doInBackground(Void...params) {
String formattedDate = getFormattedDateForUrl();
String selectedTime = getSelectedTime();
EditText commentText = (EditText) findViewById(R.id.editText);
String comment = commentText.getText().toString();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ParkeerActivity.this);
String accessToken = prefs.getString("accessToken", null);
Ion.with(ParkeerActivity.this)
.load("http://-/reservations")
.setBodyParameter("accessToken", accessToken)
.setBodyParameter("date", formattedDate)
.setBodyParameter("time", selectedTime)
.setBodyParameter("comment", comment)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback < Response < JsonObject >> () {#
Override
public void onCompleted(Exception e, Response < JsonObject > result) {
if (result.getHeaders().code() == 201) {
AlertDialog.Builder alert = new AlertDialog.Builder(ParkeerActivity.this);
alert.setMessage("Reservering gelukt");
alert.show();
} else if (result.getHeaders().code() != 201) {
AlertDialog.Builder alert = new AlertDialog.Builder(ParkeerActivity.this);
alert.setMessage("Reservering mislukt");
alert.show();
};
}
});
return null;
}
};
task.execute();
}
it crashes at reservationClicked()
logcat will be posted once i have found a cable to connect my phone to pc
EDIT2: Logcat exception on mobile device (not emulator)
04-18 13:48:48.489 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (296 ms) http://-/parkingspaces/available: Connecting socket
04-18 13:48:48.489 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (0 ms) http://-/parkingspaces/available: Executing request.
04-18 13:48:48.499 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (2 ms) http://-/parkingspaces/available: Connecting socket
04-18 13:48:58.549 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10357 ms) http://-/parkingspaces/available: Response is not cacheable
04-18 13:48:58.559 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10359 ms) http://-/parkingspaces/available: Connection successful
04-18 13:48:58.569 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10078 ms) http://-/parkingspaces/available: Response is not cacheable
04-18 13:48:58.569 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10079 ms) http://-/parkingspaces/available: Connection successful
04-18 13:48:58.579 18475-18475/com.parkeerapp.-.parkeerapp D/AndroidRuntime﹕ Shutting down VM
04-18 13:48:58.579 18475-18475/com.parkeerapp.-.parkeerapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41859da0)
04-18 13:48:58.579 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10386 ms) http://-/parkingspaces/available: Recycling keep-alive socket
04-18 13:48:58.579 18475-18475/com.parkeerapp.indivirtual.parkeerapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.parkeerapp.-.parkeerapp, PID: 18475
java.lang.NullPointerException
at com.parkeerapp.-.parkeerapp.ParkeerActivity$5$1.onCompleted(ParkeerActivity.java:154)
at com.parkeerapp.-.parkeerapp.ParkeerActivity$5$1.onCompleted(ParkeerActivity.java:151)
at com.koushikdutta.async.future.SimpleFuture.handleCallbackUnlocked(SimpleFuture.java:107)
at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:141)
at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:124)
at com.koushikdutta.ion.IonRequestBuilder$1.run(IonRequestBuilder.java:244)
at com.koushikdutta.async.AsyncServer$RunnableWrapper.run(AsyncServer.java:57)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5679)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
04-18 13:48:58.589 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10094 ms) http://-/parkingspaces/available: Recycling keep-alive socket
If you are using Ion this way, you need not use AsyncTask.
You should check result for null before blindly going with it.
I have faced similar issues sometimes. If the connectivity breaks, it sometimes returns result as null.
#Override
public void onCompleted(Exception e, JsonObject result) {
if (e != null) {
// failed.
// return
}
if (result == null) {
// failed
// return
}
}
Sometimes even if the exception is null, result is also null.
the problem has been that there is use of a proxy on 3G and 4G
Ion.with(ParkeerActivity.this)
.load(url )
.proxy(ip_adres, 8080)
did the trick
current problem is google Oauth saying need permission but that will be a new thread

android.view.WindowLeaked for tablet asynctask while trying to set portrait orientation

I have an activity that is displayed in portrait only and in my tablet it causes the following:
android.view.WindowLeaked: Activity com.spicycurryman.getdisciplined10.app.InstalledAppActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{53210b88 V.E..... R.....ID 0,0-1520,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity$LoadApplications.onPreExecute(InstalledAppActivity.java:306)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity.onCreate(InstalledAppActivity.java:105)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I am using an AsyncTask to load a listview of installed apps on the phone and using a progressdialog.
I have researched this problem:
Progress dialog and AsyncTask error
android.view.WindowLeaked exception
Android Error: Window Leaked in AsyncTask
I was able to produce this code so that the whole app doesn't crash and burn, but the exception is still thrown and the activity screen is kind of shaky after the button click and the whole transition is not really smooth.
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
Dismissing the progress dialog or calling finish() doesn't really solve the problem either...
How would I fix this?
Here is most of the AsyncTask code:
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
List<PackageInfo> packageList2 = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
boolean d = isSystemPackage2(pi);
if ((!b || !c ) && d ){
packageList1.add(pi);
}
}
//here you got email and message apps in the
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage3(pi);
boolean c = isSystemPackage4(pi);
if (b || c){
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this);
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
//Inefficient patch to prevent Window Manager error
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
try this :
#Override
public Object onRetainNonConfigurationInstance() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog = null;
}
if (asynTask!= null) {
asynTask.detach();
}
return ayncTask;
}
Declaring a non-static inner AsyncTask in your activity is not a good idea because it holds a reference to the activity and this could be a couse of the leak. However, various configuration changes could cause the OS to destroy and recreate the activity. There are a number of solutions and Rustam's anser is an example.
However, I prefer to user either AsyncTaskLoader or use some sort of asynchronous callback, like a broadcast. The asynchronous callback decouples your AsyncTask from the Activity.

Android Intent : no empty constructor

Hi friends i am having some problems with my code. I am very new to android programming, actually i am an electronics student. i have searched the forum for an answer to this problem but nothing says precisely what i have to do.i have given the log cat which explains my problem.One more thing When i add a empty constructor it shows an error "The blank final field context may not have been initialized" Please help me.
public class TrackService extends IntentService implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
//boolean uploaded = false;
private Context context= getApplicationContext();
String Lat, Long;
// A request to connect to Location Services
private LocationRequest mLocationRequest;
//List<?> pkgAppsList;
//ArrayList<ArrayList<String>> list;
//Context context;
//ArrayList<String> iteminserted = new ArrayList<String>();
private LocationClient mLocationClient;
// ArrayList<ArrayList<String>> UnUploadedData = new
// ArrayList<ArrayList<String>>();
//#Override
//public IBinder onBind(Intent intent) {
//return null;
//}
//public TrackService() {
//super("TrackService");
//}
public TrackService(Context context) {
super("Trackservice");
this.context = context;
}
#Override
public void onCreate() {
super.onCreate();
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
// mLocationRequest
// .setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setInterval(1000 * 60 * 2);// Every 2 minute
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
mLocationClient = new LocationClient(this, this, this);
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
startPeriodicUpdates();
}
/**
* Report location updates to the UI.
*
* #param location
* The updated location.
*/
#Override
public void onLocationChanged(Location location) {
System.out.println(location.getLatitude() + " "+ location.getLongitude());
Lat = location.getLatitude() + "";
Long = location.getLongitude() + "";
//if (isConnectingToInternet())
new UploadLocationInfo().execute();
// if (uploaded)
// this.stopSelf();
}
/**
* In response to a request to start updates, send a request to Location
* Services
*/
private void startPeriodicUpdates() {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
/**
* In response to a request to stop updates, send a request to Location
* Services
*/
private void stopPeriodicUpdates() {
mLocationClient.removeLocationUpdates(this);
}
//public boolean isConnectingToInternet() {
//ConnectivityManager connectivity = (ConnectivityManager) this
// .getSystemService(Context.CONNECTIVITY_SERVICE);
//if (connectivity != null) {
//NetworkInfo[] info = connectivity.getAllNetworkInfo();
//if (info != null)
//for (int i = 0; i < info.length; i++)
//if (info[i].getState() == NetworkInfo.State.CONNECTED) {
//return true;
//}
//}
//return false;
//}
public class UploadLocationInfo extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Uploading Application List
//ArrayList<NameValuePair> LOCATION = new ArrayList<NameValuePair>();
//LOCATION.add(new BasicNameValuePair("LAT", Lat));
//LOCATION.add(new BasicNameValuePair("LONG", Long));
//TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext()
// .getSystemService(getApplicationContext().TELEPHONY_SERVICE);
//IMEI = telephonyManager.getDeviceId();
//LOCATION.add(new BasicNameValuePair("IMEI", IMEI));
double x = Double.parseDouble(Long);
double y = Double.parseDouble(Lat);
EditText text1 = (EditText) ((Activity)context).findViewById(R.id.text1);
text1.setText("lat"+y+"Log"+x);
double a = 48.6800000;
double b = 2.2100000;
float[] results = new float[1];
Location.distanceBetween(y, x, b, a, results);
float distanceInMeters = results[0];
boolean isWithin10m = false;
if( distanceInMeters < 20)
{
isWithin10m = true;
}
System.out.println("Uploading New Location");
if(isWithin10m){
try {
//open a web page
} catch (Exception e) {
e.printStackTrace();
}
}else{
text1.setText("nothing to display");
}
return null;
}
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onDestroy() {
// If the client is connected
System.out.println("Destroy");
if (mLocationClient.isConnected()) {
stopPeriodicUpdates();
}
// After disconnect() is called, the client is considered "dead".
mLocationClient.disconnect();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
}
}
The Logcat details ae given below
07-22 11:49:37.419: D/dalvikvm(5525): Late-enabling CheckJNI
07-22 11:49:37.490: D/dalvikvm(5525): newInstance failed: no <init>()
07-22 11:49:37.490: D/AndroidRuntime(5525): Shutting down VM
07-22 11:49:37.490: W/dalvikvm(5525): threadid=1: thread exiting with uncaught exception (group=0x40d1a930)
07-22 11:49:37.490: E/AndroidRuntime(5525): FATAL EXCEPTION: main
07-22 11:49:37.490: E/AndroidRuntime(5525): java.lang.RuntimeException: Unable to instantiate service com.example.mobiletrackerslave.TrackService: java.lang.InstantiationException: can't instantiate class com.example.mobiletrackerslave.TrackService; no empty constructor
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2513)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.access$1600(ActivityThread.java:141)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.os.Handler.dispatchMessage(Handler.java:99)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.os.Looper.loop(Looper.java:137)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.reflect.Method.invokeNative(Native Method)
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.reflect.Method.invoke(Method.java:511)
07-22 11:49:37.490: E/AndroidRuntime(5525): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-22 11:49:37.490: E/AndroidRuntime(5525): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-22 11:49:37.490: E/AndroidRuntime(5525): at dalvik.system.NativeStart.main(Native Method)
07-22 11:49:37.490: E/AndroidRuntime(5525): Caused by: java.lang.InstantiationException: can't instantiate class com.example.mobiletrackerslave.TrackService; no empty constructor
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.Class.newInstanceImpl(Native Method)
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.Class.newInstance(Class.java:1319)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2510)
07-22 11:49:37.490: E/AndroidRuntime(5525): ... 10 more
07-22 11:49:39.892: D/dalvikvm(5525): Debugger has detached; object registry had 1 entries
use
private Context context= getApplicationContext();
in OnCreate method of your Intent service.as
context= getApplicationContext();
and change
private Context context= getApplicationContext();
to
private Context context;
And the Exception is telling you that you need to implement the default public constructor.
public TrackService() {
super("TrackService");
}
The default public constructor is a constructor with no parameters.
Here you call super() and pass a String that will be used to name the IntentService
You need to add an empty constructor to your class i.e. one that takes no arguments:
Define this constructor in your class
public TrackService() {
super("Trackservice");
}
see here No empty constructor when create a service

Categories