没有在android中显示Spinner值

时间:2014-10-31 06:11:45

标签: android

您好我的应用程序中它在logcat中出现nullpointerexception错误。 在这个我创建的微调器中,name初始微调器值来自database,但是如果调试此代码,则在初始微调器中没有显示来自数据库和数据的响应,它在此代码中显示Null指针异常。

for(int i=0;i<JA.length();i++)
{
   intial_name = json.getString("initial_name");
   intial_id = json.getString("initial_id");

}

联系我们课程

public class ContactUs extends Activity implements OnClickListener
{
    EditText regno1,fname1,mname1,lname1,dob1,age1,f_hname1,adress1,tel_o1,pin_zip1,tel_r,email1,mobile1,id_prof1,b_group1,name_kin1,realition1;
    String data="";
    TextView tv1;

    Button back,home,choosefile;
    Spinner intial,pmaincat,pcatory,religion,caste;
    RadioGroup sex,payment;
    RadioButton rb;
    String initial_id;
    String[] initial_name;
    private EditText fromDateEtxt;
    private DatePickerDialog fromDatePickerDialog;
    private SimpleDateFormat dateFormatter;
    /** Called when the activity is first created. */
    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {

        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.contactus);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        tv1=(TextView) findViewById(R.id.tv);


        payment = (RadioGroup) findViewById(R.id.sex);
        int selectedId = payment.getCheckedRadioButtonId();
        rb = (RadioButton) findViewById(selectedId);

        back=(Button) findViewById(R.id.back);
        home=(Button) findViewById(R.id.home);
        fname1=(EditText) findViewById(R.id.fname);        
        lname1=(EditText) findViewById(R.id.lname);
        regno1=(EditText) findViewById(R.id.rgno);
        mname1=(EditText) findViewById(R.id.mname);

        age1=(EditText) findViewById(R.id.age);
        f_hname1=(EditText) findViewById(R.id.f_hname);
        adress1=(EditText) findViewById(R.id.adress);        
        tel_o1=(EditText) findViewById(R.id.telo);
        pin_zip1=(EditText) findViewById(R.id.pzipcode);
        tel_r=(EditText) findViewById(R.id.tel_r);
        email1=(EditText) findViewById(R.id.email);
        mobile1=(EditText) findViewById(R.id.mobile);        
        id_prof1=(EditText) findViewById(R.id.idprof);
        b_group1=(EditText) findViewById(R.id.bgroup);
        name_kin1=(EditText) findViewById(R.id.name_kin);
        realition1=(EditText) findViewById(R.id.relationship);


        intial=(Spinner)findViewById(R.id.intial);
        pmaincat=(Spinner)findViewById(R.id.pmaincat);
        pcatory=(Spinner)findViewById(R.id.pcatgory);
        religion=(Spinner)findViewById(R.id.religion);
        caste=(Spinner)findViewById(R.id.caste);

        sex=(RadioGroup)findViewById(R.id.sex);
        payment=(RadioGroup)findViewById(R.id.paymentmode);

        tv1.setText("PATIENT REGISTRATION");
        final Button photo1 = (Button) findViewById(R.id.photo);    
        Button Send = (Button) findViewById(R.id.Send); 

        Send.setOnClickListener(new OnClickListener() {             
            public void onClick(View v)
            {
                 String first_name = fname1.getText().toString();
                 String middle_name = mname1.getText().toString(); 
                 String last_name = lname1.getText().toString(); 
                 String reg_no = regno1.getText().toString();
                 String dob = fromDateEtxt.getText().toString();
                 String age = age1.getText().toString();
                 String address = adress1.getText().toString(); 
                 String phone_office = tel_o1.getText().toString(); 
                 String fh = f_hname1.getText().toString(); 
                 String pin = pin_zip1.getText().toString();
                 String phone_resi = tel_r.getText().toString();
                 String email = email1.getText().toString(); 
                 String mobile_no = mobile1.getText().toString(); 
                 String id_proof = id_prof1.getText().toString();
                 String b_group = b_group1.getText().toString();
                 String name_of_kin = name_kin1.getText().toString(); 
                 String relation = realition1.getText().toString(); 

                 String pmode = rb.getText().toString().trim();
                 String photo = photo1.getText().toString(); 

                 String pmc=pmaincat.getSelectedItem().toString();
                 String pc=pcatory.getSelectedItem().toString();

                 String religion_id=religion.getSelectedItem().toString();
                 String caste_id=caste.getSelectedItem().toString();
                 String initial_id=intial.getSelectedItem().toString();


                 Toast.makeText(
                        ContactUs.this,
                        "Result : " + "\nclassId : " + initial_id
                        ,

                        Toast.LENGTH_SHORT).show();


                if(first_name.equals(""))
                {           
                    fname1.setError( "Please Enter First Name" );
                }
                else if(last_name.equals(""))
                {           
                    lname1.setError( "Please Enter Last Name" );
                }   
                if(reg_no.equals(""))
                {           
                    fname1.setError( "Please Select Religon" );
                }
                else if(last_name.equals(""))
                {           
                    lname1.setError( "Please Enter Last Name" );
                }   
                /*else if(mobile.equals(""))
                {           
                    mobile1.setError( "Please Enter Mobile No." );

                }
                else if(!isValidMobile(mobile)){


                }

                else if(email.equals(""))
                {           
                    email1.setError( "Please Enter EmailId" );
                }
                else if(!isValidMail(email)){


                }*/


                else
                {

                    try{

                        String queryString ="reg_no="+ reg_no
                                 +"&pmc="+pmc+"&pc="+pc+ "&initial_id="+initial_id+"&first_name="+first_name+"&middle_name="+middle_name+"&last_name="+last_name
                                 +"&fh="+fh+"&religion_id="+religion_id+"&dob="+dob+"&caste_id="+caste_id+"&address="+address+"&pin="+pin
                                 +"&email="+email+"&id_proof="+id_proof+"&phone_office="+phone_office+"&phone_resi="+phone_resi+"&mobile_no="+mobile_no+"&name_of_kin="+name_of_kin
                                 +"&relation="+relation+"&photo="+photo+"&pmode="+pmode;
                    data = DatabaseUtility.executeQueryPhp("pat_registration",queryString);
                    /*fname1.setText("");
                    lname1.setText("");
                     mobile1.setText("");
                     altmob1.setText("");
                     email1.setText("");
                     comment1.setText("");*/
                    Toast.makeText(
                            ContactUs.this,
                            "Message:Records Saved Sucessfully",

                            Toast.LENGTH_SHORT).show();
                    }
                     catch (Exception e) {
                            e.printStackTrace();
                        }

                }   
            }   

        });
        dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);

        findViewsById();

        setDateTimeField();
        String result = DatabaseUtility.executeQueryPhp("getpatient","");
        System.out.print(result);
        try
        {
            JSONArray JA = new JSONArray(result);
            JSONObject json = null;


            String intial_name = "";
            String intial_id = "";

            for(int i=0;i<JA.length();i++)
            {
                intial_name = json.getString("initial_name");
                intial_id = json.getString("initial_id");

            }







            spinner_fn();
        }
        catch(Exception e)
        {
            Log.e("Fail 3", e.toString());
        }
back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                onBackPressed();

            }
        });
 home.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent in=new Intent(getApplicationContext(),MainActivity.class);
                startActivity(in);

            }
        });
    }
    private void spinner_fn() {

        ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_spinner_item,
                initial_name);
        dataAdapter1
        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        intial.setAdapter(dataAdapter1);

        intial.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long id) {

                Log.e("Position new", initial_name[position]);



            }

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

            }

        });
    }
    private void findViewsById() {
        fromDateEtxt = (EditText) findViewById(R.id.dob);
        fromDateEtxt.setInputType(InputType.TYPE_NULL);
        fromDateEtxt.requestFocus();

    }

    private void setDateTimeField() {
        fromDateEtxt.setOnClickListener(this);

        Calendar newCalendar = Calendar.getInstance();
        fromDatePickerDialog = new DatePickerDialog(this,
                new OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                    int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                fromDateEtxt.setText(dateFormatter.format(newDate
                        .getTime()));
            }

        }, newCalendar.get(Calendar.YEAR),
        newCalendar.get(Calendar.MONTH),
        newCalendar.get(Calendar.DAY_OF_MONTH));

    }

    @Override
    public void onBackPressed(){


        super.onBackPressed();      
    }

    private boolean isValidMail(String email) 
    {
        boolean check;
        Pattern p;
        Matcher m;

        String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        p = Pattern.compile(EMAIL_STRING);

        m = p.matcher(email);
        check = m.matches();

        if(!check)
        {
            email1.setError("Not Valid Email");
        }
        return check;
    }
    private boolean isValidMobile(String mobile) 
    {
        boolean check;
        if(mobile.length() < 6 || mobile.length() > 13)
        {
            check = false;
            mobile1.setError("Not Valid Number");
        }
        else
        {
            check = true;
        }
        return check;
    }
    public void onNothingSelected(AdapterView<?> arg0) {

    }

    public void onClick(View view) {
        if (view == fromDateEtxt) {
            fromDatePickerDialog.show();
        }

    }

logcat的

10-31 06:00:29.004: E/Fail 3(1351): java.lang.NullPointerException

2 个答案:

答案 0 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

您为JA Json Array定义了json对象,但从未从数组中分配json对象,因此请尝试直接从JA获取json对象而不是json对象。

initial_name = new String[JA.length()];
initial_id = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
   intial_name[i] = JA.getJSONObject(i).getString("initial_name");
   initial_id[i] = JA.getJSONObject(i).getString("initial_id")
}

更新:尝试将initial_id定义为String []并初始化initial_name,将initial_id作为JA的长度,然后尝试在循环中的相应数组中添加相应的值。

答案 1 :(得分:0)

您正在将json对象初始化为null并尝试访问它。

使用以下代码替换您的try块:

try
{
   // JSONArray JA = new JSONArray(result);
   JSONObject json = new JSONObject(result);

   String intial_name = "";
   String intial_id = "";

   for(int i=0;i<json.length();i++)
   {
      intial_name = json.getString("initial_name");
      intial_id = json.getString("initial_id");
   }
   spinner_fn();
}