使用edittext时出现NullPointer异常

时间:2015-07-21 08:43:14

标签: java android exception

我想将这个van值存储在本地主机数据库中,但遗憾的是停止工作请帮助

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class UserOptions extends OnscreenActivity {
    protected Button subButton;
     EditText vNumber;
     InputStream is=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionbar = getActionBar();
        actionbar.hide();
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        vNumber = (EditText)findViewById(R.id.editText1);

        setContentView(R.layout.activity_user_options);
        Spinner Schoolspin = (Spinner) findViewById(R.id.spinner1);
        // Create an ArrayAdapter using the string array and a default spinner
        // layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.school_names,
                android.R.layout.simple_spinner_item);

        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        Schoolspin.setAdapter(adapter);

        Spinner stateSpin = (Spinner) findViewById(R.id.spinner2);
        // Create an ArrayAdapter using the string array and a default spinner
        // layout
        ArrayAdapter<CharSequence> adapterstate = ArrayAdapter
                .createFromResource(this, R.array.state,
                        android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterstate
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        stateSpin.setAdapter(adapterstate);

        Spinner citySpin = (Spinner) findViewById(R.id.spinner3);
        // Create an ArrayAdapter using the string array and a default spinner
        // layout
        ArrayAdapter<CharSequence> cityadapter = ArrayAdapter
                .createFromResource(this, R.array.City,
                        android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        cityadapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        citySpin.setAdapter(cityadapter);

        subButton = (Button) findViewById(R.id.button1);
        subButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                String van = ""+vNumber.getText().toString();
                List<NameValuePair> nameValue = new ArrayList<NameValuePair>(1);
                nameValue.add(new BasicNameValuePair("VAN", van));
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(
                            "http://10.0.2.2/tutorial.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValue));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity entity = httpResponse.getEntity();
                    is=entity.getContent();
                    String msg = "Data Entered Succesfully";
                    Toast.makeText(getApplicationContext(), msg,
                            Toast.LENGTH_LONG).show();
                } catch (ClientProtocolException e) {
                    Log.e("ClientProtocol", "Log_Tag");
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.e("Log_Tag", "IOException");
                    e.printStackTrace();
                }
                Intent intent = new Intent(UserOptions.this,
                        OnscreenActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);

            }

        });
    }

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

Useroptions.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testmap12.UserOptions" >

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner1"
        android:layout_centerHorizontal="true" />

    <Spinner
        android:id="@+id/spinner3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner2"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner3"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:text="@string/submitButton" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/spinner1"
        android:layout_marginTop="20dp"
        android:hint="@string/hintSchool" >

        <requestFocus />
    </EditText>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/spinner2"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="22dp" />

</RelativeLayout>

logcat的

07-21 13:54:52.665: E/AndroidRuntime(2965): FATAL EXCEPTION: main
07-21 13:54:52.665: E/AndroidRuntime(2965): Process: com.example.testmap12, PID: 2965
07-21 13:54:52.665: E/AndroidRuntime(2965): java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
07-21 13:54:52.665: E/AndroidRuntime(2965):     at com.example.testmap12.UserOptions$1.onClick(UserOptions.java:90)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at android.view.View.performClick(View.java:4756)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at android.view.View$PerformClick.run(View.java:19749)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at android.os.Handler.handleCallback(Handler.java:739)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at android.os.Handler.dispatchMessage(Handler.java:95)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at android.os.Looper.loop(Looper.java:135)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at android.app.ActivityThread.main(ActivityThread.java:5221)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at java.lang.reflect.Method.invoke(Native Method)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at java.lang.reflect.Method.invoke(Method.java:372)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
07-21 13:54:52.665: E/AndroidRuntime(2965):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

4 个答案:

答案 0 :(得分:0)

像这样更改您的代码

 @Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_options);
    ActionBar actionbar = getActionBar();
    actionbar.hide();
    vNumber = (EditText)findViewById(R.id.editText1);
    Spinner Schoolspin = (Spinner) findViewById(R.id.spinner1); 
    //Remaining code is as it is

}

答案 1 :(得分:0)

setContentView()需要在findviewbyid来电之前。多数编译器如何识别您的edittext的位置。

更改此顺序:

 vNumber = (EditText)findViewById(R.id.editText1);

 setContentView(R.layout.activity_user_options);

答案 2 :(得分:0)

你需要把:

    setContentView(R.layout.activity_user_options);
    vNumber = (EditText)findViewById(R.id.editText1);

答案 3 :(得分:0)

onCreate(Bundle)是您初始化活动的地方。最重要的是,在这里,您通常会使用定义UI的布局资源调用setContentView(view),并使用findViewById(int)检索该UI中需要以编程方式进行交互的小部件。

Why findViewById() is returning null if setcontentview() is not called?

但是&#34; id&#34;中的错误,如果来自java类的widget没有设置为contentview,是否可以获取id? &#39;

您必须创建动态视图,然后您无需调用setcontentview。

setContentView(R.layout.activity_user_options);
vNumber = (EditText)findViewById(R.id.editText1);