Android-通过广播意图传递长数组

Android-通过广播意图传递长数组,第1张

概述我写了一个小android程序,有一个主要的活动与广播侦听器,我创建了另一个线程.线程搜索素数,并将其加载到一个长数组列表中,然后每3秒通过广播将填充的数组发送到主活动.一切正常,直到我试图从意图中获取更多的长数组.每次都会导致nullpointerexception.我尝试了一个字符串arraylis

我写了一个小android程序,有一个主要的活动与广播侦听器,我创建了另一个线程.线程搜索素数,并将其加载到一个长数组列表中,然后每3秒通过广播将填充的数组发送到主活动.一切正常,直到我试图从意图中获取更多的长数组.每次都会导致nullpointerexception.
我尝试了一个字符串arrayList,它起作用了,但是我很好奇,因为这个意图有一个“ getlongarrayextra”方法.

这是我的代码:

公共类MainActivity扩展了Activity {

public static String broADCAST_THREAD_KEY = "broadcast_key";public static String EXTRAARRAYID = "primes";private static long MAxnuM = 2000000;private PrimeCalculatorThread thread;TextVIEw textVIEw;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);    textVIEw = (TextVIEw) findVIEwByID(R.ID.numberstext);}private broadcastReceiver receiver = new broadcastReceiver() {    public voID onReceive(androID.content.Context context,            androID.content.Intent intent) {        String origitext = textVIEw.getText().toString();        long[] primes = intent.getExtras().getLongArray(EXTRAARRAYID);        Log.d("ASD", "broadcast received" + primes.toString());        StringBuilder builder = new StringBuilder();        if (primes != null) {            for (long prime : primes) {                builder.append(prime + " - ");            }            textVIEw.setText(origitext + "\n" + builder.toString());        }    };};@OverrIDeprotected voID onResume() {    Log.d("ASD", "ONRESUME");    initReceiverAndStartThread();    super.onResume();}private voID initReceiverAndStartThread() {    IntentFilter filter = new IntentFilter(broADCAST_THREAD_KEY);    registerReceiver(receiver, filter);    thread = new PrimeCalculatorThread(getBaseContext(), MAxnuM);    thread.start();    Log.d("ASD", "THREAD STARTED");}

第二个线程:

公共类PrimeCalculatorThread扩展了线程{

private Context context;private long maxnum;List<Long> primes;boolean isrunning;public voID setIsrunning(boolean isrunning) {    this.isrunning = isrunning;}private long counter = 0;private long DELAYBETWEENbroADCAST = 3000;public PrimeCalculatorThread(Context c, long maxnum) {    this.context = c;    this.maxnum = maxnum;    primes = new ArrayList<Long>();}@OverrIDepublic voID run() {    long startTime = System.currentTimeMillis();    long estimatedTime;    isrunning = true;    for (long i = 0; i < maxnum; i++) {        Log.d("ASD", Boolean.toString(isrunning));        if (!isrunning)            break;        Log.d("ASD", i + "");        estimatedTime = System.currentTimeMillis() - startTime;        if (isPrime(i)) {            primes.add(i);            Log.d("ASD", i + "is a prime");        } else {            Log.d("ASD", i + "is not a prime");        }        if (estimatedTime > counter * DELAYBETWEENbroADCAST                + DELAYBETWEENbroADCAST) { // elapsed another period            Log.d("ASD", primes.toString() + " will be sending.");            sendbroadCast();            primes.clear();            counter++;        }        try {                       //for deBUG purposes            Thread.sleep(250);        } catch (InterruptedException e) {            e.printstacktrace();        }    }}private voID sendbroadCast() {    Intent intent = new Intent(MainActivity.broADCAST_THREAD_KEY);    intent.putExtra(MainActivity.EXTRAARRAYID, primes.toArray());    context.sendbroadcast(intent);    Log.d("ASD", "broADCAST SENT" + primes.toString());}boolean isPrime(long n) {    if (n < 2)        return false;    if (n == 2 || n == 3)        return true;    if (n % 2 == 0 || n % 3 == 0)        return false;    long sqrtN = (long) Math.sqrt(n) + 1;    for (long i = 6L; i <= sqrtN; i += 6) {        if (n % (i - 1) == 0 || n % (i + 1) == 0)            return false;    }    return true;}

}

解决方法:

问题在于,您正在管理Long对象的列表,并将其传递到putExtra中,这意味着您正在调用putExtra(String name,Serializable value).然后,您尝试使用getLongArray()获得该值,但是您并没有额外添加任何长数组!要解决此问题,请更换

intent.putExtra(MainActivity.EXTRAARRAYID, primes.toArray());

long[] primesArray = new long[primes.size()];for (int i = 0; i < primes.size(); i++) {    primesArray[i] = primes.get(i);}intent.putExtra(MainActivity.EXTRAARRAYID, primesArray);

这将调用正确的putExtra(String name,long [] value)方法.

总结

以上是内存溢出为你收集整理的Android-通过广播意图传递长数组全部内容,希望文章能够帮你解决Android-通过广播意图传递长数组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1078212.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存