java.lang.String java.lang.Object.toString()' 在空对象引用上
java.lang.String java.lang.Object.toString()' on a null object reference
我正在开发一个带有 mysql 数据库的应用程序,我在这里使用微调器,我想将微调器选择的项目存储到 database.I 正在执行以下代码,但是当我 运行 它崩溃的应用程序并在 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));
}
}
移除Button click Listener下的以下内容
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;
试试这个,如果问题解决了请告诉我
在 Button click Listener 下尝试使用上述代码
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;
}
删除按钮点击下的所有代码,然后 运行 告诉我
我正在开发一个带有 mysql 数据库的应用程序,我在这里使用微调器,我想将微调器选择的项目存储到 database.I 正在执行以下代码,但是当我 运行 它崩溃的应用程序并在 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));
}
}
移除Button click Listener下的以下内容
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;
试试这个,如果问题解决了请告诉我
在 Button click Listener 下尝试使用上述代码
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;
}
删除按钮点击下的所有代码,然后 运行 告诉我