空对象引用上的 java.lang.String java.lang.Object.toString()'

标签 java android mysql

我正在使用 mysql 数据库开发一个应用程序,这里我使用 spinner,我想将 spinner 选定的项目存储到数据库中。我正在执行以下代码,但是当我运行该应用程序时,它崩溃并在logcat 即

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String java.lang.Object.toString()” 在 com.example.user.spinnerdemo.MainActivity_D6$1.onClick(MainActivity_D6.java:100)
请给我一个建议,我可以在这里做什么。

//java file
public class MainActivity_D6  extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    private Spinner spinner2, spinner1;
    private String  s_name, s_course;
    //An ArrayList for Spinner Items

    private ArrayList<String> students1;
    private ArrayList<String> students2;

    Button mBtnSave;
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    //JSON Array

    private JSONArray result1, result2, result;

    //TextViews to display details
    private TextView textViewName1;
    private TextView textViewName2;
    private TextView textViewCourse;
    private TextView textViewSession;

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

        //Initializing the ArrayList
        students1 = new ArrayList<String>();
        students2 = new ArrayList<String>();

        //Initializing Spinner


        //Adding an Item Selected Listener to our Spinner
        //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener


        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner2 = (Spinner) findViewById(R.id.spinner2);

        spinner1.setOnItemSelectedListener(this);
        spinner2.setOnItemSelectedListener(this);

        mBtnSave = (Button) findViewById(R.id.button2);

        mBtnSave.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {

        String result = null;
        InputStream is = null;

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                s_name = spinner2.getSelectedItem().toString();
                s_course = spinner1.getSelectedItem().toString();

                nameValuePairs.add(new BasicNameValuePair("s_course",s_course));
                nameValuePairs.add(new BasicNameValuePair("s_name",s_name));


        StrictMode.setThreadPolicy(policy);


        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://example.in/Spinner/insert_s2.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            Log.e("log_tag", "connection success ");
            Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }


        catch(Exception e)
        {
            Log.e("log_tag", "Error in http connection "+e.toString());
            Toast.makeText(getApplicationContext(), "Connection fail",  Toast.LENGTH_SHORT).show();

        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
                Intent i = new Intent(getBaseContext(),DatabaseActivity.class);
                startActivity(i);
            }
            is.close();

            result=sb.toString();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error converting result "+e.toString());
        }


        try{

            JSONObject json_data = new JSONObject(result);

            CharSequence w= (CharSequence) json_data.get("re");

            Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();


        }
        catch(JSONException e)
        {
            Log.e("log_tag", "Error parsing data "+e.toString());
            Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
        }



    }
});

   /*     mBtnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

               // submitForm();

            }
        });*/

        //Initializing TextViews
        textViewName1 = (TextView) findViewById(R.id.textViewName1);
        textViewName2 = (TextView) findViewById(R.id.textViewName2);

        //This method will fetch the data from the URL
        getData1();
        getData2();

    }

 /*   private void submitForm() {

        s_name = spinner2.getSelectedItem().toString();
        //     s_name="aaa";
        s_course = spinner1.getSelectedItem().toString();
        //      s_course="bbb";
        Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
        new InsertActivity(this).execute(s_course, s_name);


    }*/

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    /*    switch (parent.getId()){

            case R.id.spinner1:
               s_course=  parent.getItemAtPosition(position).toString();
                //    getData1();
                // showToast("Spinner1: position=" + position);

                break;


            case R.id.spinner2:
               s_name=  parent.getItemAtPosition(position).toString();
                //    getData2();
                break;
        }*/
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {


    }

/*    private String getName(int position){
        String name="";
        try {
            //Getting object of given index
            JSONObject json = result.getJSONObject(position);

            //Fetching name from that object
            name = json.getString(Config.TAG_NAME);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Returning the name
        return name;
    }
    private String getCourse(int position){
        String course="";
        try {
            JSONObject json = result.getJSONObject(position);
            course = json.getString(Config.TAG_COURSE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return course;
    }*/

    private void getData1() {
        //Creating a string request
        StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response1) {
                        JSONObject j1 = null;
                        try {
                            //Parsing the fetched Json String to JSON Object
                            j1 = new JSONObject(response1);

                            //Storing the Array of JSON String to our JSON Array
                            result1 = j1.getJSONArray(Config.JSON_ARRAY1);

                            //Calling method getStudents to get the students from the JSON Array
                            getStudents1(result1);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error1) {

                    }
                });

        //Creating a request queue
        RequestQueue requestQueue1 = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue1.add(stringRequest1);
    }

    private void getStudents1(JSONArray j1) {
        //Traversing through all the items in the json array
        for (int i = 0; i < j1.length(); i++) {
            try {
                //Getting json object
                JSONObject json1 = j1.getJSONObject(i);

                //Adding the name of the student to array list
                students1.add(json1.getString(Config.TAG_COURSE));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //Setting adapter to show the items in the spinner
        spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_D6.this, android.R.layout.simple_spinner_dropdown_item, students1));
    }



    private void getData2() {
        //Creating a string request
        StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response2) {
                        JSONObject j2 = null;
                        try {
                            //Parsing the fetched Json String to JSON Object
                            j2 = new JSONObject(response2);

                            //Storing the Array of JSON String to our JSON Array
                            result = j2.getJSONArray(Config.JSON_ARRAY);

                            //Calling method getStudents to get the students from the JSON Array
                            getStudents2(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error1) {

                    }
                });

        //Creating a request queue
        RequestQueue requestQueue2 = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue2.add(stringRequest2);
    }

    private void getStudents2(JSONArray j2) {
        //Traversing through all the items in the json array
        for (int i = 0; i < j2.length(); i++) {
            try {
                //Getting json object
                JSONObject json2 = j2.getJSONObject(i);

                //Adding the name of the student to array list
                students2.add(json2.getString(Config.TAG_USERNAME));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //Setting adapter to show the items in the spinner
        spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_D6.this, android.R.layout.simple_spinner_dropdown_item, students2));
    }

}

最佳答案

删除按钮点击监听器下的以下内容

s_name = spinner2.getSelectedItem().toString();
s_course = spinner1.getSelectedItem().toString();

现在,在微调器的 OnItemSelected 重写方法下,添加以下内容

case R.id.spinner1:
    s_course=  spinner1.getItemAtPosition(position).toString();
    break;
case R.id.spinner2:
    s_name = spinner2.getItemAtPosition(position).toString();
    break;

试试这个,如果问题解决了请告诉我

在按钮单击监听器下尝试此操作以及上面的代码

if(s_name.isempty()){
    Toast.makeText(getApplicationContext,"Name is empty",Toast.LENGTH_LONG).show;
}
if(s_course.isempty()){
    Toast.makeText(getApplicationContext,"Course is empty",Toast.LENGTH_LONG).show;
}

删除按钮点击下的所有代码并运行它并让我知道

关于空对象引用上的 java.lang.String java.lang.Object.toString()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38538355/

相关文章:

android - 如何检测相对于移动方向的手机方向

mysql - Docker-Compose 无法连接到 MySQL

java - 启动应用程序时在 Android 上找不到类异常

java - 如何测试Spring Boot优雅关闭?

android - 如何使用 Google Drive Android API 更改在 Google Drive 中创建的文件夹或文件的权限?

android - 如何从 tess-two 中正确提取 text 和 boxRects?

php - 执行SQL查询时出错,如果单独执行则有效

mysql - 将 MySQL 脚本转换为 ORACLE

java - SQL错误,当我在JAVA代码中实现加入

Java 在 Graphics 对象而不是 Color 对象上设置透明度