简体   繁体   English

Android:从Mysql填充操作栏微调器

[英]Android: Populate action bar spinner from Mysql

As I say in the question title, I'm trying to populate my Home Activity action bar spinner with items from my mysql database... I'm callyng my private GetFeeds Class (AsyncTask extended class) to get what I want from database in the onCreate method from the activity.. and I'm getting the results correctly, but then the app stops and closes, I can't even see the activity in the phone... 正如我在问题标题中所说的那样,我正在尝试使用mysql数据库中的项目填充“我的家庭活动”操作条微调器...我正在调用自己的私有GetFeeds类(AsyncTask扩展类)来从数据库中获取所需的内容活动中的onCreate方法..我正确地获得了结果,但是随后应用程序停止并关闭,我什至无法在电话中看到活动...

my HomeActivity: 我的家庭活动:

public class HomeActivity extends ActionBarActivity implements
    ActionBar.OnNavigationListener {

InternetConnectivityManager icm;
ProgressDialog pDialog;
BDFunctions bdfunctions;

String[] feeds;

/**
 * The serialization (saved instance state) Bundle key representing the
 * current dropdown position.
 */
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

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

    // Set up the action bar to show a dropdown list.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    icm = new InternetConnectivityManager(getApplicationContext());

    new GetFeeds().execute();

    // Set up the dropdown list navigation in the action bar.
    actionBar.setListNavigationCallbacks(
    // Specify a SpinnerAdapter to populate the dropdown list.
            new ArrayAdapter<String>(actionBar.getThemedContext(),
                    android.R.layout.simple_list_item_1,
                    android.R.id.text1, feeds), this);
}

private class GetFeeds extends AsyncTask<Void, Void, JSONObject> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pDialog = new ProgressDialog(HomeActivity.this);
        pDialog.setMessage("A vrificar os grupos onde estas inserido...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected JSONObject doInBackground(Void... arg0) {
        bdfunctions = new BDFunctions(getApplicationContext());
        JSONObject json = bdfunctions.getFeeds();
        return json;
    }

    protected void onPostExecute(JSONObject json) {
        // dismiss the dialog after getting the result
        pDialog.dismiss();
        if(json != null) {

            try {
                if (json.getString(JSONKeys.KEY_SUCCESS) != null) {
                    String res = json.getString(JSONKeys.KEY_SUCCESS); 
                    if(Integer.parseInt(res) == 1){

                        JSONArray jsonFeeds = json.getJSONArray("feeds");
                        feeds = new String[jsonFeeds.length()];
                        for(int i=0; i<jsonFeeds.length(); i++) {
                            JSONObject feedOBJ = (JSONObject) jsonFeeds.get(i);
                            feeds[i] = feedOBJ.getString("descricao");
                        }

                    }else{

                        Toast.makeText(getApplicationContext(), json.getString(JSONKeys.KEY_ERROR_MSG), Toast.LENGTH_LONG).show();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Ocorreu um erro com o servidor", Toast.LENGTH_LONG).show();
        }
    }
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Restore the previously serialized current dropdown position.
    if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
        getSupportActionBar().setSelectedNavigationItem(
                savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    // Serialize the current dropdown position.
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
            .getSelectedNavigationIndex());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, 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);
}

@Override
public boolean onNavigationItemSelected(int position, long id) {
    // When the given dropdown item is selected, show its contents in the
    // container view.
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.container,
                    PlaceholderFragment.newInstance(position + 1)).commit();
    return true;
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container,
                false);
        TextView textView = (TextView) rootView
                .findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
}

} }

The Logcat says the error is caused by java.lan.NullPointerException at this line: Logcat说此错误是由以下行中的java.lan.NullPointerException引起的:

new ArrayAdapter<String>(actionBar.getThemedContext(),
                    android.R.layout.simple_list_item_1,
                    android.R.id.text1, feeds), this);

I've tried to move the setListNavigationCallbacks method and all that it's inside to the onPostExecute method from my private class so I only populate the spinner when I finish getting the results.. but it gives me an error, I can't put the setListNavigationCallbacks there.. How should I do this ? 我试图将setListNavigationCallbacks方法及其所有内容从我的私有类移到onPostExecute方法中,所以我只在完成结果后才填充微调框。但这给我一个错误,我无法放置setListNavigationCallbacks那里..我应该怎么做?

Thanks 谢谢

The GetFeeds task executes asynchronously. GetFeeds任务异步执行。 That means that you cannot create the ArrayAdapter until it's finished (or the feeds array will be null, hence the exception). 这意味着您无法创建ArrayAdapter直到完成为止(否则feeds数组将为null,因此是例外)。

You should move the call to setListNavigationCallbacks() into the task's onPostExecute() method. 您应该setListNavigationCallbacks()的调用移到任务的onPostExecute()方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM