将字符串数组传递给另一个活动

时间:2014-09-02 13:56:50

标签: android string android-activity nullpointerexception

我从我的parse对象获取数据,数据显示在各种视图中。 但是,每当我点击showMenu按钮时我的应用程序崩溃(onClick方法是showMenu) 这是我的代码

public class SingleRestraunt extends ActionBarActivity {
    private GoogleMap map;
    TextView resteName, resteCuisine, resteLocation, resteAddress, restePrice,
            resteTimings, restePayment, resteRating, resteWebsite;
    String restName, obj, restCuisine, restLocation, restAddress, restPrice,
            restTimings, restPayment, restRating, restWebsite;
    String[] menu = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_restraunt);
        resteName = (TextView) findViewById(R.id.restrauntName);
        resteCuisine = (TextView) findViewById(R.id.restrauntCuisine);
        resteLocation = (TextView) findViewById(R.id.restrauntLocation);
        resteAddress = (TextView) findViewById(R.id.restrauntAddress);
        restePrice = (TextView) findViewById(R.id.restrauntPrice);
        resteTimings = (TextView) findViewById(R.id.restrauntTimings);
        restePayment = (TextView) findViewById(R.id.restrauntPayment);
        resteRating = (TextView) findViewById(R.id.restrauntRating);
        resteWebsite = (TextView) findViewById(R.id.restrauntWebsite);

        Intent i = getIntent();
        obj = i.getStringExtra("restId");
        getDetails(obj);

    }

    private void getDetails(String obj) {

        ParseQuery<ParseObject> query = ParseQuery.getQuery("resdb");
        query.getInBackground(obj, new GetCallback<ParseObject>() {

            @Override
            public void done(ParseObject object, ParseException e) {
                if (e == null) {
                    restName = object.getString("name");
                    restCuisine = object.getString("cuisine");
                    restLocation = object.getString("locality");
                    restAddress = object.getString("address");
                    restPrice = object.getString("price");
                    restTimings = object.getString("timings");
                    restPayment = object.getString("accepted");
                    restRating = object.getString("ratings");
                    restWebsite = object.getString("URL");
                    JSONArray test = object.getJSONArray("menu");
                    for (int i = 0; i < test.length(); i++) {
                        try {
                            String menu1 = (String) test.get(i);
                            if (menu1 == null)
                                menu[i] = menu1;
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                    addData();

                } else {
                    e.printStackTrace();
                }
            }
        });

    }

    public void addData() {
        resteName.setText(restName);
        resteCuisine.setText(restCuisine);
        resteLocation.setText(restLocation);
        resteAddress.setText(restAddress);
        restePrice.setText(restPrice);
        resteTimings.setText(restTimings);
        restePayment.setText(restPayment);
        resteRating.setText(restRating);
        resteWebsite.setText(restWebsite);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.single_restraunt, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void Review(View v) {
        Intent i = new Intent(SingleRestraunt.this, ReviewPage.class);
        i.putExtra("RestName", restName);
        startActivity(i);
    }

    public void Offer(View v) {
        Intent i = new Intent(SingleRestraunt.this, OfferPage.class);
        i.putExtra("RestName", restName);
        startActivity(i);
    }

    public void showMenu(View v) {

        Bundle b = new Bundle();
        b.putStringArray("menuList", menu);
        Intent i = new Intent(SingleRestraunt.this, MenuActivity.class);
        i.putExtras(b);
        startActivity(i);
    }

    public void Share(View v) {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = ("Hey! I visited "
                + restName
                + " recommended to me by the Gastronoma App! Visit their site here " + restWebsite);
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "Subject Here");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }

}

只有当我点击showMenu按钮时,应用程序才会崩溃。直到这一点,应用程序工作正常。所有其他按钮也完美地完成了预期的任务。应用程序崩溃时显示的错误是

09-02 09:54:22.307: E/AndroidRuntime(3278): Process: com.example.gastronomaapp, PID: 3278
09-02 09:54:22.307: E/AndroidRuntime(3278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.gastronomaapp/com.example.gastronomaapp.MenuActivity}: java.lang.NullPointerException

打开任何建议。按要求添加我已添加MenuActivity代码和清单文件

public class MenuActivity extends Activity {
    WebView web = (WebView) findViewById(R.id.webView1);
    TextView next = (TextView) findViewById(R.id.next);
    TextView prev = (TextView) findViewById(R.id.prev);
    int i = 0;

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

        Bundle b = this.getIntent().getExtras();
        String[] array = b.getStringArray("menuList");
        getMenu(array);
    }

    public void getMenu(final String[] array) {
        String menu = array[i];
        web.loadUrl(menu);
        visibility(i, array);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                i++;
                String menu = array[i];
                web.loadUrl(menu);
                visibility(i, array);
            }

        });
        prev.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                i--;
                String menu = array[i];
                web.loadUrl(menu);
                visibility(i, array);
            }

        });
    }

    private void visibility(int i, String[] array) {
        if (i == 0)
            prev.setVisibility(View.GONE);
        if (i == array.length - 1)
            next.setVisibility(View.GONE);
    }

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gastronomaapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="com.example.gastronomaapp.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <uses-permission android:name="com.example.gastronomaapp.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <!--
         <application>
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>








    -->
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ResterauntList"
            android:label="@string/title_activity_resteraunt_list" >
        </activity>
        <activity
            android:name=".Map"
            android:label="@string/title_activity_map" >
        </activity>
        <activity
            android:name=".Button1List"
            android:label="@string/title_activity_button1_list" >
        </activity>
        <activity
            android:name=".SingleRestraunt"
            android:label="@string/title_activity_single_restraunt" >
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAaC-32WynuOO6stpRaK6LSxRMwCuvgdE4" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".ReviewPage"
            android:label="@string/title_activity_review_page" >
        </activity>
        <activity
            android:name=".OfferPage"
            android:label="@string/title_activity_offer_page" >
        </activity>
        <activity
            android:name=".ImageMenu"
            android:label="@string/title_activity_image_menu" >
        </activity>
        <activity
            android:name=".MenuActivity"
            android:label="@string/title_activity_menu" >
        </activity>
    </application>

</manifest>

2 个答案:

答案 0 :(得分:2)

您必须执行以下操作:

Intent i = new Intent("Activity")
i.putExtra(key, ArrayName)

Intent i = getIntent();
String[] array = i.getExtras().getString(keyname);

就是这样。

答案 1 :(得分:0)

NPE 可能是因为以下原因引起的:

  1. menu数组已声明但未初始化。它应该是:

      String menu [] = new String [SIZE_OF_MY_MENU_ARRAY];
    
  2. 确保menu数组非空
  3. 在您的代码中,

    if (menu1 == null)
         menu[i] = menu1; // <--- Null value is assigned to your array. Avoid that
    

  4. 原始回答

    如果您要将字符串数组从 ActivityA.java 转移到 ActivityB.java

    ActivityA.java

    String [] myStringArray = // Declare Here...
    
    Bundle b=new Bundle();
    b.putStringArray("MY_KEY", myStringArray);
    Intent i=new Intent(context, ActivityA);
    i.putExtras(b);
    

    ActivityB.java

    中读取字符串数组
    Bundle b=this.getIntent().getExtras();
    String[] myStringArray =b.getStringArray("MY_KEY");
    

    您在问题中也使用了类似的语法。