1.java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.


(转载)DDMS中的log也无法定位到准确的出错位置。检查错误可以从下面几点入手:
1、检查Thread,确定没有在Background thread中直接调用adapter,如果有,请移除相关代码到Handler中处理;
2、尽量将数据放在adapter类中管理,不需要的时候清除信息(勤写clear()),及时用notifyDataSetChanged()刷新;
3、在Activity或者Fragment合适的位置(onPause/onStop)要及时检查thread,有adapter数据处理相关的应马上停止;
4、这个错误经常出现在Activity休眠起来之后,主要还是使用adapter不太小心造成的。如果实在找不到原因,在onPause()函数中停止所有的background thread,并且在onResume()函数最前面清空adapter中的数据,并且adapter.notifyDataSetChanged()。然后重新更新加载数据,这样一般可以解决问题。

把  listview的adapter数据更新和dapter.notifyDataSetChanged()必须同时放到单独一个线程里,报错基本是都是这个原因,有人把adapter里的数据更新了,但是 dapter.notifyDataSetChanged()     放到一个单独线程去更新,结果出现notifyDataSetChanged更新同步的问题




2.android java.lang.reflect.UndeclaredThrowableException

把 mController.openShare(getActivity(), false); 里边的getActivity()换成getParent()就好了。因为我是在ActivityGroup中调用

试下重新添加一下res资源文件


3.android异常——aapt.exe已停止工作

   在android开发时,当build项目时,发生如下异常:
aapt.exe已停止工作,其他无任何错误提示,发生这个错误一般是资源文件或是xml文件中有错误造成的。

解决方法:
clean一下,可以发现console中会有错误提示,然后根据错误提示解决。


我的的情况:
[2013-04-20 14:35:50 - BigBoy] Error in an XML file: aborting build.
很明显是xml中有错误,但并未提示是哪一个xml文件错误,这就需要自己找了。

最后发现在定义属性时,没有加name属性,加上后就正常了

<declare-styleable name="CustomInputControl">


在andriod项目中引用另一个library project时,报

The container 'Android Dependencies' references non existing library 'xxxxxxx' 错误,解决办法是右击library project,选择Build Path->Configure Build Path->Order and Export->Select All将所有包都选上


4.安装Android SDK时遇到Failed to rename directory
   安装Android SDK时遇到Failed to rename directory E:\Java\Android SDK\android-sdk_r06-windows\android-sdk-windows\tools to E:\Java\Android SDK\android-sdk_r06-windows\android-sdk-windows\temp\ToolPackage.old01
   这样的问题?总是提示无法改名?
   解决方法如下:
   1、备份tools文件夹
   2、将temp文件夹下的tools_r11-windows.zip解压并改名为tools并替换原来的tools
   3、重新启动SDK Setup
   好了,问题解决了,打开sdk就可以看到正在下载platform和api了。
   备注:我的SDK是android-sdk_r06-windows.zip,如果是低版本的话,temp文件夹下面会有一个ToolPackage.new01文件夹,把这个文件夹也改名为tools并替换原来的tools即可。


5.sdk manager更新失败,显示Download interrupted: read timed out,应该如何解决?

这样的话只需要访问相关文件,下载下来再替换掉相关文件,然后重新执行安装相关组件就好了。

https://dl-ssl.google.com/android/repository/android-2.3.3_r02-linux.zip

下载地址是这样的,前面的dl-ssl.google.com/android/repository/ 是固定格式,后面的文件名直接接上就好。用迅雷下载很快的。

下载成功以后把文件替换掉temp里面的文件内容就好,然后重新执行安装~  瞬间完成!!!

http://www.cnblogs.com/houzk/p/3627394.html


6. android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

Context中有一个startActivity方法,Activity继承自Context,重载了startActivity方法。如果使用Activity的startActivity方法,不会有任何限制,而如果使用Context的startActivity方法的话,就需要开启一个新的task,遇到上面那个异常的,都是因为使用了Context的startActivity方法。解决办法是,加一个flag。

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


7.An internal error occurred during: "Initializing Java Tooling" MyEclipse 出错


删除当前工作目录下的WORKSPACE_HOME/.metadata/.plugins/org.eclipse.core.resources/.project,然后重新启动Eclipse


8、android.content.res.Resources$NotFoundException: String resource ID #0x0 

做Android应用开发的朋友有时候会遇到这样的Bug,, 

android.content.res.Resources$NotFoundException: String resource ID #0x0 找不到资源文件ID #0x0

原因分析如下:

遇到这种情况,很有可能是把一个int型业务数据的 设置setText()或者类似的方法中, 这样Android系统就会主动去资源文件当中寻找, 但是它不是一个资源文件ID, 所以就会报出这个bug。 将int型业务数据,转换成String类型即可。



9、Caused by: java.lang.ClassCastException: android.widget.TextView

1、project -- > clean ,就好了。

2、修改了一下xml,加减了几个空格,再保存



10、ViewPager: Can't Change Tag of Fragment


问题描述:

在应用里用到了ViewPager和FragmentPagerAdapter 实现多页(>20页)滑动,每一页都是一个Fragment,给ViewPager注册一个OnPageChangeListener,当知道某一个Fragment被选中时,开始调用其刷新数据的方法。

并有一目录,点击某个条目时,调用 ViewPager 的 setCurrentItem(position) ,页面跳转到指定页,但是此时奇怪的是注册的 OnPageChangeListener#onPageSelected 居然没有被调用,表现为选中的页面没有刷新数据。

这时候往右侧滑动几页没问题,再往左侧滑动几页就一定会报出异常:

java.lang.IllegalStateException: Can’t change tag of fragment PageFragment{42ef29a8 #14 id=0x7f060052 android:switcher:2131099730:22}: was android:switcher:2131099730:22 now android:switcher:2131099730:17

分析原因:

经过一番排查,发现问题出现的原因在于我的FragmentPagerAdapter 内部维护的List集合造成的,因为我想自己来控制一下Fragment内部数据的销毁,并且使Fragment得到重用。

但是,在往List集合中,add(fragment)的时候,没有注意FragmentPagerAdapter#getItem(position)传入的位置和实例化fragment所存放在List中的位置!

导致,List中会有可能出现存在两个指针指向相同的Fragment,表现出来的样子就是报异常“Can’t change tag of fragment”,并且不会调用其刷新数据的方法,因为其isShow被标记为true了。

解决方法:

判断一下position与List的当前大小即可。

当List大小比position大时,意味着,要从里取。

反之则表示,要在List对应position的location放一个Fragment。


    private List<PageFragment> pages;

    //...

    public PageFragment getItem(int position) {

        PageFragment page = null;

        if (pages.size() > position) {

            page = pages.get(position);

            if (page != null) {

                return page;

            }

        }


        while (position>=pages.size()) {

            pages.add(null);

        }

        page = PageFragment.newPage(pageList.get(position),position);

        pages.set(position, page);

        return page;

    }


11、

解决AsyncTask引发的RejectedExecutionException



AsyncTask是google为易用和有效的异步操作UI线程的所开发的一个封装类。使用者可以很轻易的使用其进行后台操作,然后将结果传给UI线程,而不需要使用Thread和Handler。


这样好用的一个类,显然可以在ListView异步加载图片时大显身手,本着这样的想法,笔者瞬间就完成了一段这样的模拟代码:


Adapter的getView方法:


复制代码

 1         @Override

 2         public View getView(int pos, View view, ViewGroup viewGroup) {

 3             if (view == null) {

 4                 view = getLayoutInflater().inflate(R.layout.test2_list_item,

 5                         null);

 6             }

 7             ImageView p_w_picpathView = (ImageView) view.findViewById(R.id.p_w_picpathView);

 8             //这里每次都new出一个新的AsyncTask,进行执行。

 9             new TestAsyncTask(p_w_picpathView, pos).execute(new Object());

10             TextView itemView = (TextView) view.findViewById(R.id.itemView);

11             itemView.setText("测试数据" + pos);

12             return view;

13         } 

复制代码

TestAsyncTask:


复制代码

 1 private class TestAsyncTask extends AsyncTask {

 2         private ImageView p_w_picpathView;

 3         private int index;

 4 

 5         public TestAsyncTask(ImageView p_w_picpathView, int index) {

 6             this.p_w_picpathView = p_w_picpathView;

 7             this.index = index;

 8         }

 9 

10         @Override

11         protected Object doInBackground(Object... arg0) {

12             // 模拟长时间的运算;大多数情况下是等待进行网络请求。

13             long sum = 0;

14             for (int i = 0; i <= 10000 * 100; i++) {

15                 sum += i * 1l;

16             }

17             return null;

18         }

19 

20         @Override

21         protected void onPostExecute(Object result) {

22             //模拟已经获得了网络请求的图片

23             p_w_picpathView.setImageBitmap(BitmapFactory.decodeResource(

24                     getResources(), R.drawable.p_w_picpath01, null));

25         }

26     }

复制代码

运行调试,图片一个一个全都加载出来,没有问题,正当我疯狂的向下翻动着,妄图享受一下列表迅速滑动的快感的时候,一个无情的错误弹了出来。


04-17 11:22:52.009: E/AndroidRuntime(22792): FATAL EXCEPTION: main

04-17 11:22:52.009: E/AndroidRuntime(22792): java.util.concurrent.RejectedExecutionException: pool=128/128, queue=10/10

04-17 11:22:52.009: E/AndroidRuntime(22792): at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1961)

04-17 11:22:52.009: E/AndroidRuntime(22792): at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:794)

04-17 11:22:52.009: E/AndroidRuntime(22792): at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1315)


好吧,现在我理解为啥网络上流传的异步加载图片是用更加繁琐的Thread加Handler形式,而不用AsyncTask了。


难道是AsyncTask有什么用法上的问题,从出错结果来看貌似是达到了某个上限被拒绝了。那我们就从这个java.util.concurrent.RejectedExecutionException错误入手。


翻看java的在线文档RejectedExecutionException,我们看到了这个错误的解释:


复制代码

public class RejectedExecutionException

extends RuntimeException


Exception thrown by an Executor when a task cannot be accepted for execution.


Since:

1.5

See Also:

Serialized Form

复制代码

这个表明是Executor这个类不接受执行task时抛出的异常。而Executor是java1.5之后增加的java.util.concurrent包中操作多线程的主要类。可以执行多个RunnableTask,看来google的AsyncTask就是用的这套API。


了解到这点,我们就可以打开AsyncTask的源码查看它到底是怎么实现的:


打开源码之后,找到execute方法: 


复制代码

 1     /**

 2      * Executes the task with the specified parameters. The task returns

 3      * itself (this) so that the caller can keep a reference to it.

 4      *

 5      * This method must be invoked on the UI thread.

 6      *

 7      * @param params The parameters of the task.

 8      *

 9      * @return This instance of AsyncTask.

10      *

11      * @throws IllegalStateException If {@link #getStatus()} returns either

12      *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.

13      */

14     public final AsyncTask<Params, Progress, Result> execute(Params... params) {

15         if (mStatus != Status.PENDING) {

16             switch (mStatus) {

17                 case RUNNING:

18                     throw new IllegalStateException("Cannot execute task:"

19                             + " the task is already running.");

20                 case FINISHED:

21                     throw new IllegalStateException("Cannot execute task:"

22                             + " the task has already been executed "

23                             + "(a task can be executed only once)");

24             }

25         }

26 

27         mStatus = Status.RUNNING;

28 

29         onPreExecute();

30 

31         mWorker.mParams = params;

32         sExecutor.execute(mFuture);

33 

34         return this;

35     }

复制代码

 找到这里使用的Executor是sExecutor这个属性,这样来到它赋值的地方


复制代码

 1     private static final String LOG_TAG = "AsyncTask";

 2 

 3     private static final int CORE_POOL_SIZE = 5;

 4     private static final int MAXIMUM_POOL_SIZE = 128;

 5     private static final int KEEP_ALIVE = 10;

 6 

 7     private static final BlockingQueue<Runnable> sWorkQueue =

 8             new LinkedBlockingQueue<Runnable>(10);

 9 

10     private static final ThreadFactory sThreadFactory = new ThreadFactory() {

11         private final AtomicInteger mCount = new AtomicInteger(1);

12 

13         public Thread newThread(Runnable r) {

14             return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());

15         }

16     };

17 

18     private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,

19             MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);

复制代码

可以看到他是构造了一个ThreadPoolExecutor常量,保证new出多个AsyncTask都是使用这一个Executor。异常应该是它抛出的,我们看下这个类的文档,其中有一段是这样描述的:


复制代码

Rejected tasks

 New tasks submitted in method execute(Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the execute method invokes the rejectedExecution(Runnable, ThreadPoolExecutor) method of its         RejectedExecutionHandler. Four predefined handler policies are provided:


  1.In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.

  2.In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow    down the rate that new tasks are submitted.

  3.In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.

  4.In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried     (which can fail again, causing this to be repeated.)


It is possible to define and use other kinds of RejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies.

复制代码

 原来在Executor的队列和容量都达到最大时,再次增加新的task的时候将会进行拒绝行为,而默认的拒绝行为就是抛出这个RejectedExecutionException异常。


 看到这里顿时恍然了,原来初始化ThreadPoolExecutor没有指定拒绝行为,导致了异常的发生。google,你可以的!


 那解决方案也就诞生了,就是复制一份AsyncTask的源码,自己重写这个初始化方法,增加相应的拒绝策略,后面就有几个可供选择的策略。修改AsyncTask源码如下


1     private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,

2             MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory, new ThreadPoolExecutor.DiscardOldestPolicy());

再次运行,OK,不会再抛出那个异常了。


其实当你看AsyncTask的google官方文档时,你会发现后面有这么一段:


Order of execution

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.


也就是说刚开始,AsyncTask是被限制在一个线程里。从1.6开始,使用了线程池,允许运行多任务同时进行。而到了3.0之后,又被限制在一个线程里为了避免多线程执行的错误。


变3次了,你可以的,google。


为了验证这段话,瞅瞅3.0之后的AsyncTask的源码:


复制代码

    private static final String LOG_TAG = "AsyncTask";


    private static final int CORE_POOL_SIZE = 5;

    private static final int MAXIMUM_POOL_SIZE = 128;

    private static final int KEEP_ALIVE = 1;


    private static final ThreadFactory sThreadFactory = new ThreadFactory() {

        private final AtomicInteger mCount = new AtomicInteger(1);


        public Thread newThread(Runnable r) {

            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());

        }

    };


    private static final BlockingQueue<Runnable> sPoolWorkQueue =

            new LinkedBlockingQueue<Runnable>(10);


    /**

     * An {@link Executor} that can be used to execute tasks in parallel.

     */

    public static final Executor THREAD_POOL_EXECUTOR

            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,

                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);


    /**

     * An {@link Executor} that executes tasks one at a time in serial

     * order.  This serialization is global to a particular process.

     */

    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();


    private static final int MESSAGE_POST_RESULT = 0x1;

    private static final int MESSAGE_POST_PROGRESS = 0x2;


    private static final InternalHandler sHandler = new InternalHandler();

    //这里我们发现到了这个默认的执行器,是下面实现的线性队列。

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

    private final WorkerRunnable<Params, Result> mWorker;

    private final FutureTask<Result> mFuture;


    private volatile Status mStatus = Status.PENDING;

    

    private final AtomicBoolean mCancelled = new AtomicBoolean();

    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();

    

    private static class SerialExecutor implements Executor {

        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();

        Runnable mActive;


        public synchronized void execute(final Runnable r) {

            mTasks.offer(new Runnable() {

                public void run() {

                    try {

                        r.run();

                    } finally {

                        scheduleNext();

                    }

                }

            });

            if (mActive == null) {

                scheduleNext();

            }

        }


        protected synchronized void scheduleNext() {

            if ((mActive = mTasks.poll()) != null) {

                THREAD_POOL_EXECUTOR.execute(mActive);

            }

        }

    } 

复制代码

 这样我们也就可以根据3.0的源码修改我们的AsyncTask里的默认执行器,同样使用SerialExecutor保证只会启用一个线程。另外3.0的AsyncTask多了一个executeOnExecutor(java.util.concurrent.Executor, Object[])方法,如果你希望有多个任务同时启动,也可以使用THREAD_POOL_EXECUTOR执行。