0

我使用线程和支架来下载一些数据,然后显示一个带有按钮的新视图,这些按钮允许您进一步浏览应用程序。但我认为我做错了什么,因为我使用的任何下一个活动都会在 setContentView 行上因空指针异常而崩溃。当我评论这一行时,没有任何问题(所以我猜这意味着该活动在清单中被声明为良好并正常启动)。看起来由于线程的原因,新活动没有地方可以设置内容或其他东西..

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.hera.ontdekdelft.model.JJsonResponse;
import com.hera.ontdekdelft.listclasses.ListData;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class StartUp extends Activity
  {
    private static final String tag = StartUp.class.getName();
     public static final String SERIALIZEDDATA = "SerializedData";
     ProgressBar pbar;
     TextView tv1;
     Drawable background;
     Button btCategory, btMakeMyDay;
     RelativeLayout loadedBackground, loadingBackground;



    @Override
    public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        LoadData task = new LoadData();
        task.execute();


        String language =  Locale.getDefault().getISO3Language();
        background = getBackgroundImage();

            setContentView(R.layout.startup_loading);
            tv1=(TextView)findViewById(R.id.tvloading);
            if(language.equals("nld")){
                tv1.setText("bijwerken");
            }else{
                tv1.setText("loading");
            }
            pbar=(ProgressBar)findViewById(R.id.progressBar1);
            pbar.setVisibility(1);
            loadingBackground=(RelativeLayout)findViewById(R.id.startup_background_loading);
            loadingBackground.setBackgroundDrawable(background);



        }

    public Drawable getBackgroundImage(){
        Drawable d;
        Calendar c = Calendar.getInstance(); 
        int month = c.get(Calendar.MONTH);
        Log.i("month",String.valueOf(month));
        switch (month){
        default: d = getResources().getDrawable(R.drawable.homescreen_summer);break;
        case 0:d = getResources().getDrawable(R.drawable.homescreen_winter);break;
        case 1:d = getResources().getDrawable(R.drawable.homescreen_winter); break;
        case 2:d = getResources().getDrawable(R.drawable.homescreen_spring);break;
        case 3:d = getResources().getDrawable(R.drawable.homescreen_spring);break;
        case 4:d = getResources().getDrawable(R.drawable.homescreen_spring);break;
        case 5:d = getResources().getDrawable(R.drawable.homescreen_summer); break;
        case 6:d = getResources().getDrawable(R.drawable.homescreen_summer); break;
        case 7:d = getResources().getDrawable(R.drawable.homescreen_summer); break;
        case 8:d = getResources().getDrawable(R.drawable.homescreen_autumn); break;
        case 9:d = getResources().getDrawable(R.drawable.homescreen_autumn); break;
        case 10:d = getResources().getDrawable(R.drawable.homescreen_autumn); break;
        case 11:d = getResources().getDrawable(R.drawable.homescreen_winter); break;
        }
        return d;

    }

    private class LoadData extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        protected void onPostExecute(String language) {
            super.onPostExecute(language);
            setContentView(R.layout.startup_loaded); 
            btCategory=(Button)findViewById(R.id.btn_category);
            loadedBackground=(RelativeLayout)findViewById(R.id.startup_background_loaded);
            loadedBackground.setBackgroundDrawable(background);
            if(language.equals("nld")){
                btCategory.setText("Ontdek Delft");
            }else{
                btCategory.setText("Discover Delft");
            }

              //newactivitybutton

            btCategory.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    startActivity(new Intent(StartUp.this, Overview.class));
                    finish();   
                }
            });

        }


        @Override
        protected String doInBackground(Void... params) {
            String language =  Locale.getDefault().getISO3Language();
             AssetManager assetManager = getAssets();
                InputStream inputStream = null;
                try {
                    inputStream = assetManager.open("originalDelftJson.json");
                } catch (IOException e) {
                    Log.e("tag", e.getMessage());
                }
                ObjectMapper objectMapper = new ObjectMapper();
                Log.i("tijdlog","start parsing" );
                try {

                     List<JJsonResponse> jsonResponse = objectMapper.readValue(inputStream, new TypeReference<List<JJsonResponse>>() { });
                        Log.i("tijdlog","einde parsing" );
                        // 
                          final  List<JJsonResponse> myGlobalVariable = jsonResponse;

                          ((ApplicationController)getApplication()).setGlobalData(myGlobalVariable);



                          List<ListData> ld = new ArrayList<ListData>();
                         int selectedPic;
                         JJsonResponse e;
                         int k =0;
                         for(int i=0;i < jsonResponse.size() ;i++){
                             e = jsonResponse.get(i);
                             for(int j=0; j<e.venue.themes.size();j++){
                                 if (e.venue.themes.get(j).mobile == true){
                                     selectedPic = 0;
                                     String tip;
                                     String theme;
                                     if (language.equalsIgnoreCase("nld")){
                                         tip=e.venue.tip; 
                                         theme=e.venue.themes.get(j).name;
                                     }else{
                                         tip=e.venue.tip_en;
                                         theme=e.venue.themes.get(j).name_en;
                                     }
                                     // pic selected pic
                                     String photoUrl = null;
                                     if (e.venue.venue_photos.isEmpty() == false){
                                        for(int l=0; l < e.venue.venue_photos.size() ;l++){
                                             if(e.venue.venue_photos.get(l).selected == true){ 
                                                 selectedPic = l;
                                             }
                                             photoUrl=e.venue.venue_photos.get(selectedPic).medium;
                                         }
                                     }else
                                         {
                                         photoUrl=null; // null no pic--> add link later
                                       }
                                     ld.add(new ListData(e.venue.id, e.venue.name, photoUrl, tip, theme));//nieuwe maken
                                     k++;
                                 }  
                             } 
                         }

                         Collections.sort(ld, ListData.ListDataThemeAndNameComparator); // vergelijken op thema
                         for(int z=0;z < ld.size() ;z++){
                             Log.i("ld nr " + String.valueOf(z), ld.get(z).name + " theme: " + ld.get(z).theme + " & venue id= "+ ld.get(z).venueID);
                         }

                // save
                         ((ApplicationController)getApplication()).setListData(ld);  



                } catch (JsonParseException e) {
                    // XXX Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // XXX Auto-generated catch block
                    e.printStackTrace();
                }
            return language;
        }

    }

}

发生我的错误的新活动:

导入android.app.Activity;导入android.os.Bundle;

公共类概述扩展了活动{

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(findViewById(R.layout.splash)); }

}

xml 飞溅;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/splash"
    >


</LinearLayout>

编辑: 我编辑了我的代码。现在使用 AsyncTask,它似乎是下面建议的 LuxuryMode 之类的解决方案,但它也不起作用。setContentView 时仍然相同的 nullpointerexception... 错误日志:

07-24 19:53:50.411: E/AndroidRuntime(29618): FATAL EXCEPTION: main
07-24 19:53:50.411: E/AndroidRuntime(29618): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hera.ontdekdelft/com.hera.ontdekdelft.Overview}: java.lang.NullPointerException
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2787)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2803)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.access$2300(ActivityThread.java:135)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2136)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.os.Looper.loop(Looper.java:144)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.main(ActivityThread.java:4937)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at java.lang.reflect.Method.invokeNative(Native Method)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at java.lang.reflect.Method.invoke(Method.java:521)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at dalvik.system.NativeStart.main(Native Method)
07-24 19:53:50.411: E/AndroidRuntime(29618): Caused by: java.lang.NullPointerException
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.view.ViewGroup.addViewInner(ViewGroup.java:1977)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.view.ViewGroup.addView(ViewGroup.java:1873)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.view.ViewGroup.addView(ViewGroup.java:1853)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:226)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:216)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.Activity.setContentView(Activity.java:1665)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.hera.ontdekdelft.Overview.onCreate(Overview.java:12)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
07-24 19:53:50.411: E/AndroidRuntime(29618):    ... 11 more
4

2 回答 2

1

Android 线程模型中有两条规则:1) 不要阻塞主 (UI) 线程 2) 不要从主 (UI) 线程之外操作 UI。您似乎对第二条规则有疑问。您可以尝试使用 Activity#runOnUiThread(Runnable) 而不是使用该处理程序,但总的来说,您正在做的事情真的很混乱,而且通常是一个糟糕的主意:) 此外,除非我遗漏了什么,否则您的处理程序到底如何如果您在启动线程后对其进行初始化,是否可以在启动线程中使用它?您似乎依赖于某种方式的线程调度,这也是一个坏主意。

很可能,您需要使用的是AsyncTask. 立即在 onCreate 中设置您的内容视图,然后执行您AsyncTask下载数据的内容。然后在您的任务的 onPostExecute 中,执行任何必要的相关 UI 更改。

更新 -

在 onPostExecute 中,立即调用 super。另外,不要通过调用来启动您的活动 startActivity(new Intent ("com.hera.ontdekdelft.OVERVIEW"));,而应该是startActivity(new Intent(Startup.this, Overview.class));

此外,从堆栈跟踪的外观来看,当您尝试启动新 Activity 时会发生崩溃。所以我会在第 12 行查看问题所在。

更新 -

正如我在下面的讨论中指出的那样:

您不能将 Activity 的 contentView 设置为 findViewById(whatever)。findViewById 查看当前的 contentView 并尝试找到与您传入的 id 匹配的视图。但是您还没有设置任何 contentview,所以没有什么可找到的。因此,当您尝试将 contentview 设置为调用 findViewById 返回的空视图时,您会因空指针而崩溃!您需要将视图设置为该 Activity 的任何视图。setContentView(R.layout.overview_layout) 或 setContentView(new OverviewView(this))

于 2012-07-24T14:20:54.380 回答
0

setContentView(..) 是Activity的一种方法。你不能在你Runnable的 中调用它,它超出了范围。结果是一个空指针。

您在 Runnable 中设置 contentView 的方法相当奇怪。也许会稍微改变您的设计?也许您可以创建多个 Activity 而不是切换 1 个 Activity 的布局..

于 2012-07-24T14:21:35.903 回答