改善格式并消除噪音

时间:2015-03-30 16:08:14

标签: java android arrays

当我尝试从为结果启动的活动返回字符串数组时,我的应用程序出现问题。出于某些奇怪的原因,我的应用程序也不会显示操作栏,无论我做什么。我把代码放在下面。

首先启动

MainActivity,然后为结果调用DropDownList

DropDownList.Java

public class DropDownList extends Activity implements View.OnClickListener {
        private ListView lView;
        String[] lv_items;
        ArrayAdapter<String> adapter;
        Button button;

        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.activity_drop_down_list);
            lv_items = getResources().getStringArray(R.array.subjects_List);

            findViewsById();
            lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the  one option from list
            lView.setAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_multiple_choice,    lv_items));
            lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            button.setOnClickListener(this);
        }
        private void findViewsById() {
        lView = (ListView) findViewById(R.id.ListView01);
        button = (Button) findViewById(R.id.submitButton);
     }
//I BELIEVE THIS IS WHERE THE PROBLEMATIC CODE IS
        public void onClick(View v) {
            SparseBooleanArray checked = lView.getCheckedItemPositions();
            ArrayList<String> selectedItems = new ArrayList<String>();
            for (int i = 0; i < checked.size(); i++) {
                int position = checked.keyAt(i);
                if (checked.valueAt(i))
                    selectedItems.add(adapter.getItem(position));
            }
            String[] outputStrArr = new String[selectedItems.size()];

            for (int i = 0; i < selectedItems.size(); i++) {
                outputStrArr[i] = selectedItems.get(i);
            }

            Intent returnIntent = new Intent(getApplicationContext(),
                    MainActivity.class);

            // Create a bundle object
            Bundle b = new Bundle();
            b.putStringArray("selectedItems", outputStrArr);

            // Add the bundle to the intent.
            returnIntent.putExtras(b);

            // start the ResultActivity
            setResult(RESULT_OK, returnIntent);


            /**returnIntent.putExtra("SelectedBook",book);*/
            finish();
        }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, 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();
            //noinspection SimplifiableIfStatement


            switch(id) {
                case R.id.action_ok:


                    break;
                case R.id.about_menu:
                  Toast.makeText(this, "developed by Seyi Oluwasanmi",
                     Toast.LENGTH_SHORT).show();
                    break;
                case R.id.action_settings:
                    Toast.makeText(getApplicationContext(),"Settings Clicked",Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
}

MainActivity.Java

 public class MainActivity extends Activity {

public static final int ReqCode = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageButton addButton = (ImageButton)         findViewById(R.id.add_button);
    ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            // Or read size directly from the view's width/height
            int size =   getResources().getDimensionPixelSize(R.dimen.fab_size);
            outline.setOval(0, 0, size, size);

            addButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent myIntent = new Intent(MainActivity.this,  DropDownList.class);
                    startActivityForResult(myIntent, ReqCode);
                }
            });
        }

    };
    addButton.setOutlineProvider(viewOutlineProvider);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case ReqCode:
            if (resultCode == RESULT_OK) {
                ArraySubs();
                break;
            }
    }
}

public void ArraySubs() {
    Bundle b = getIntent().getExtras();
    String[] subChoices = b.getStringArray("selectedItems");
    ListView lv = (ListView) findViewById(R.id.outputList);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, subChoices);
    lv.setAdapter(adapter);
};


@Override
public boolean onCreateOptionsMenu(Menu menu){
    super.onCreateOptionsMenu(menu);
    MenuInflater blowUp=getMenuInflater();
    blowUp.inflate(R.menu.menu_main,menu);
    return true;
    }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

   switch(id) {
       case R.id.action_ok:

           break;
       case R.id.action_settings:
           Toast.makeText(getApplicationContext(),"Settings Clicked", Toast.LENGTH_SHORT).show();
           break;
   }
        return true;
    }
}

menu.xml文件

 <menu xmlns:android="http://schemas.android.com/apk/res/android"
  <item android:id="@+id/action_ok"
       android:icon="@drawable/ic_menu_done"
       android:title="@string/action_ok"
       android:showAsAction="ifRoom"
 />

<item android:id="@+id/about_menu"
    android:title="@string/about_menu"
    android:showAsAction="ifRoom"
    />

<item android:id="@+id/action_settings"
    android:title="@string/action_settings"
    android:showAsAction="ifRoom"
/>
 </menu>

主题的字符串数组       <string-array name="subjects_List"> <item>Maths</item> <item>English</item> <item>Physics</item> <item>Biology</item> <item>Computing</item> <item>Chemistry</item> <item>French</item> <item>Music</item> <item>Philosophy</item> <item>Art</item> </string-array>

2 个答案:

答案 0 :(得分:0)

我不太确定你的第一个问题但是对于操作栏尝试扩展ActionBarActivity http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html

答案 1 :(得分:0)

对于操作栏问题,让您的活动扩展“ActionBarActivity”而不仅仅是“Activity”,这将是固定的。

对于另一个问题,你的问题在这里:

selectedItems.add(adapter.getItem(position));

因为适配器没有被初始化。

更改以下内容:

@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_drop_down_list);
        lv_items = getResources().getStringArray(R.array.subjects_List);

        findViewsById();
        lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the  one option from list
        lView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice,    lv_items));
        lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        button.setOnClickListener(this);
    }

要:

adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice,    lv_items);
lView.setAdapter(adapter);

这应解决问题。

我注意到另一件事会导致崩溃:

public void ArraySubs() {
Bundle b = getIntent().getExtras();
String[] subChoices = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, subChoices);
lv.setAdapter(adapter);
};

您正在尝试获取MainActivity的意图,该意图不包含该数组。您需要从onActivityResult传递意图。如果额外不存在,将它放在try / catch中也是一个好主意。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case ReqCode:
            if (resultCode == RESULT_OK) {
                ArraySubs(data);
                break;
            }
    }
}

public void ArraySubs(Intent data) {
    try{
        Bundle b = data.getExtras();
        String[] subChoices = b.getStringArray("selectedItems");
        ListView lv = (ListView) findViewById(R.id.lv_list);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, subChoices);
        lv.setAdapter(adapter);
    }
    catch(Exception e){
        Log.e("MainActivity", e.getMessage());
    }
}