由于对字符串数组的动态访问导致程序崩溃

时间:2013-01-17 09:59:02

标签: android xml-parsing android-asynctask

我创建了一个应用程序来解析数据并将其放入字符串数组中。我在后台做这个任务。我想要实现的是,读取后台进程已解析的任何数据的字符串。为了做到这一点,我已经使数组静态,我试图从另一个类中读取它,但我的程序失败,出现以下错误。有谁可以看看,帮助我。感谢。

01-17 09:43:07.927: E/AndroidRuntime(1167): FATAL EXCEPTION: main
01-17 09:43:07.927: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pro1/com.example.pro1.Secactivity}: java.lang.NullPointerException
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5039)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:511)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
01-17 09:43:07.927: E/AndroidRuntime(1167): Caused by: java.lang.NullPointerException
01-17 09:43:07.927: E/AndroidRuntime(1167):     at com.example.pro1.Secactivity.onCreate(Secactivity.java:29)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5104)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-17 09:43:07.927: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-17 09:43:07.927: E/AndroidRuntime(1167):     ... 11 more

这是我执行asynctask的主要类:

public class MainActivity extends Activity {
    EditText uid;
    EditText password;
    Button submit;
    static String Sarray1[] = new String[50];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button)findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                uid = (EditText)findViewById(R.id.id);
                password = (EditText)findViewById(R.id.password);
                String userid = uid.getText().toString();
                String pwd = password.getText().toString();
                Loginauth log = new Loginauth();
                if(!userid.equals("")&&!pwd.equals(""))
                {
                    String result = log.Login(userid,pwd);
                    if(result.equals(""))
                    {
                        Toast toast = Toast.makeText(getApplicationContext(), "Login Error: Check id and Password", Toast.LENGTH_LONG);
                        toast.show();
                    }
                    else
                    {
                        Toast toast = Toast.makeText(getApplicationContext(), "Login Successfull", Toast.LENGTH_SHORT);
                        toast.show();
                        SAXParserActivity ab = new SAXParserActivity();
                        ab.execute();
                        for (int j = 0; j<15;j++)
                    {
                        Log.d("Array",Sarray1[j].toString());
                    }
                        startActivity(new Intent("com.example.pro1.ABC"));
                    }

                }
                else
                {
                    Toast toast = Toast.makeText(getApplicationContext(), "Invalid id or password", Toast.LENGTH_LONG);
                    toast.show();
                }

            }
        });


    }
    class SAXParserActivity extends AsyncTask<Void,Void,Void> {

        XMLGettersSetters data;
        @Override
        protected Void doInBackground(Void... params) {
            Log.i("Abe","Abe");
            try {
                SAXParserFactory saxPF = SAXParserFactory.newInstance();
                SAXParser saxP = saxPF.newSAXParser();
                XMLReader xmlR = saxP.getXMLReader();
                URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml"); // URL of the XML             
                XMLHandler myXMLHandler = new XMLHandler();
                xmlR.setContentHandler(myXMLHandler);
                xmlR.parse(new InputSource(url.openStream()));

            } catch (Exception e) {
                System.out.println(e);
            }

            data = XMLHandler.data;                 
            for (int i = 0; i < data.getTitle().size(); i++) {

                Sarray1[i] =data.getTitle().get(i);
                //System.out.printf("Sarray",Sarray[i].toString());
                //Log.d("Abe",Sarray);
                //Sarray1[i]=Sarray;

                Log.d("Abe",Sarray1[i].toString());
            }

            return null;
        }
    }


}

以下是我尝试访问数组的类:

package com.example.pro1;


import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TabHost;

public class Secactivity extends FragmentActivity {
    TabHost tHost;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);

    tHost = (TabHost) findViewById(android.R.id.tabhost);
    tHost.setup();
    String array[] = new String[50];
    for(int i = 0;i<MainActivity.Sarray1.length;i++)
    {
        array[i] = MainActivity.Sarray1[i];
        Log.d("Secactivity",MainActivity.Sarray1[i]);
    }

    /** Defining Tab Change Listener event. This is invoked when tab is changed */
    TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() {

            @Override
            public void onTabChanged(String tabId) {
                android.support.v4.app.FragmentManager fm =   getSupportFragmentManager();
                Protab1 androidFragment = (Protab1) fm.findFragmentByTag("ST");
                Protab2 appleFragment = (Protab2) fm.findFragmentByTag("CSI");
                android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

                /** Detaches the androidfragment if exists */
                if(androidFragment!=null)
                    ft.detach(androidFragment);

                /** Detaches the applefragment if exists */
                if(appleFragment!=null)
                    ft.detach(appleFragment);

                /** If current tab is android */
                if(tabId.equalsIgnoreCase("ST")){

                    if(androidFragment==null){      
                        /** Create AndroidFragment and adding to fragmenttransaction */
                        ft.add(R.id.realtabcontent,new Protab1(), "ST");                        
                    }else{
                        /** Bring to the front, if already exists in the fragmenttransaction */
                        ft.attach(androidFragment);                     
                    }

                }else{  /** If current tab is apple */
                    if(appleFragment==null){
                        /** Create AppleFragment and adding to fragmenttransaction */
                        ft.add(R.id.realtabcontent,new Protab2(), "CSI");                       
                    }else{
                        /** Bring to the front, if already exists in the fragmenttransaction */
                        ft.attach(appleFragment);                       
                    }
                }
                ft.commit();                
            }
        };


        /** Setting tabchangelistener for the tab */
        tHost.setOnTabChangedListener(tabChangeListener);

        /** Defining tab builder for Andriod tab */
    TabHost.TabSpec tSpecAndroid = tHost.newTabSpec("ST");
    tSpecAndroid.setIndicator("ST");        
    tSpecAndroid.setContent(new DummyTabContent(getBaseContext()));
    tHost.addTab(tSpecAndroid);


    /** Defining tab builder for Apple tab */
    TabHost.TabSpec tSpecApple = tHost.newTabSpec("CSI");
    tSpecApple.setIndicator("CSI");        
    tSpecApple.setContent(new DummyTabContent(getBaseContext()));
    tHost.addTab(tSpecApple);

}   

}

1 个答案:

答案 0 :(得分:0)

不要像这样使用大小合适的Array

static String Sarray1[] = new String[50];

将其更改为ArrayList

ArrayList<String> Sarray1 = new ArrayList<String>();

然后使用add data来使用传真,

Sarray1.add(data.getTitle().get(i));

在您的情况下,如果您使用MainActivity.Sarray1.length循环,那么即使只有10个数据条目,它仍将始终运行 50次。因此,剩余索引的获取null values会有所变化。