尝试在空对象引用上调用虚拟方法'void android.widget.ImageButton.setOnClickListener'

时间:2018-07-11 11:31:45

标签: android json node.js

我想通过单击音频图像进行搜索并说出我要搜索的内容,但是我遇到了尝试在空对象上调用虚拟方法'void android.widget.ImageButton.setOnClickListener'的常见错误参考,我不知道为什么要得到它

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.xbxvxe.rndfy, PID: 4436
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xbxvxe.rndfy/com.xbxvxe.rndfy.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                      at android.os.Handler.dispatchMessage(Handler.java:106)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at com.xbxvxe.rndfy.activity.MainActivity.onCreate(MainActivity.java:176)
                      at android.app.Activity.performCreate(Activity.java:7009)
                      at android.app.Activity.performCreate(Activity.java:7000)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
                      at android.os.Handler.dispatchMessage(Handler.java:106) 
                      at android.os.Looper.loop(Looper.java:164) 
                      at android.app.ActivityThread.main(ActivityThread.java:6494) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

在此行btnSpeak.setOnClickListener(new View.OnClickListener()

中出现此错误

我的课是这样的:

public class MainActivity extends AppCompatActivity{

    // URL
    String URL= AppConfig.URL_GetFolders;
    ArrayList<String> Folders;

    // list view
    ListView lv;
    // Search EditText
    EditText inputSearch;
    private ImageButton btnSpeak;
    private final int REQ_CODE_SPEECH_INPUT = 100;
    ArrayAdapter<String> lvArrayAdapter;

    // Hashmap
    HashMap<Integer,String> lvMap = new HashMap<Integer, String>();


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.folder_activity);

        Folders=new ArrayList<>();

        // declaring listview refs
        lv= (ListView) findViewById(R.id.folder_Name);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

        // List view section
        loadlvFolders(URL);

        lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String folder = lv.getItemAtPosition( lv.getSelectedItemPosition()).toString();
                String id = lvMap.get(lv.getSelectedItemPosition());

            Toast.makeText(getApplicationContext(),folder,Toast.LENGTH_LONG).show();

                String newReq= new StringBuilder().append(AppConfig.URL_GetFoldersFK).append(id).toString();
                Log.d("Request show",newReq);

                Intent intent = new Intent(MainActivity.this, BuildingsListActivity.class);
                // Sending value to another activity using intent.
                intent.putExtra("FolderId", newReq);
                startActivity(intent);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // DO Nothing here
            }
        });

        // hide the action bar
        btnSpeak.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                promptSpeechInput();
            }
        });
        /*** Enabling Search Filter* */
        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                MainActivity.this.lvArrayAdapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });
        init(savedInstanceState);

    }

    // listview function

    private void loadlvFolders (String url) {
        RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray=jsonObject.getJSONArray("data");


                    for(int i=0;i<jsonArray.length();i++){
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        String dossier = jsonObject1.getString("nom");
                        String id = jsonObject1.getString("id");

                        lvMap.put(i,id);

                        Folders.add(dossier);

                    }

                    ArrayAdapter<String> lvArrayAdapter = new ArrayAdapter<String>
                            (MainActivity.this, android.R.layout.simple_list_item_1, Folders);

                    lv.setAdapter(lvArrayAdapter);

                }catch (JSONException e){
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        int socketTimeout = 30000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);
        requestQueue.add(stringRequest);
    }

    /**
     * Showing google speech input dialog
     * */
    private void promptSpeechInput() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                getString(R.string.speech_prompt));
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
                    getString(R.string.speech_not_supported),
                    Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * Receiving speech input
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    inputSearch.setText(result.get(0));
                }
                break;
            }

        }
    }


}

2 个答案:

答案 0 :(得分:1)

这意味着您的ImageButton没有正确初始化。 请检查您的xml,您已正确遵循xml中提到的名称。

答案 1 :(得分:0)

尝试使用ImageView而不是ImageButton并将其设置为onClickListner。