Вопрос по android, android-activity, runtime, android-intent, nullpointerexception – Ошибка доставки результата ResultInfo {who_null, request = 1, result = -1, data = Intent {(extras)}} в действие; NullPointerException

5

У меня есть два класса, которые называются Courses и MainActivity. В MainActivity есть активность LAUNCHER и Gridlayout. Курсы имеют действие DEFAULT. Когда GridLayout нажимает Курсы, открывается интерфейс, и пользователь заполняет представления в соответствии со своей программой курса, поэтому создается объект Курсы. Я хочу отправить этот объект в класс MainActivity.Я получаю NullPointerException. Я пытался решить эту проблему, но не могу. Мне нужна профессиональная помощь.

вот это Courses.java}

package com.example.classprogram;
public class Courses extends Activity implements Parcelable {

private String course_name;
private String classroom;
private String teacname;
private String day;
private String start_hour;
private String end_hour;
List days;
List StartingHours;



public static String COURSENAME;
public static String CLASSROOM;
public static String TCHRNAME;
public static String DAY;
public static String SHOUR;
public static String EHOUR;






public String getCourse_name() {
    return course_name;
}



public void setCourse_name(String course_name) {
    this.course_name = course_name;
}



public String getClassroom() {
    return classroom;
}



public void setClassroom(String classroom) {
    this.classroom = classroom;
}



public String getTeacname() {
    return teacname;
}



public void setTeacname(String teacname) {
    this.teacname = teacname;
}



public String getDay() {
    return day;
}



public void setDay(String day) {
    this.day = day;
}



public String getStart_hour() {
    return start_hour;
}



public void setStart_hour(String start_hour) {
    this.start_hour = start_hour;
}



public String getEnd_hour() {
    return end_hour;
}



public void setEnd_hour(String end_hour) {
    this.end_hour = end_hour;
}

Button add_class;
EditText cName;
EditText cRoom;
EditText tName;
Spinner gun;
Spinner sHour;
Spinner eHour;


public Courses() {}


public Courses(String course_name, String classroom, String teacname,
        String day, String start_hour, String end_hour) {
    super();
    this.course_name = course_name;
    this.classroom = classroom;
    this.teacname = teacname;
    this.day = day;
    this.start_hour = start_hour;
    this.end_hour = end_hour;
}


public Courses(Parcel in) {

    /*String[] data = new String[5];

    in.readStringArray(data);
    this.course_name = data[0];
    this.classroom = data[1];
    this.teacname = data[2];
    this.day = data[3];
    this.end_hour = data[4];
    this.start_hour = data[5];*/

    course_name = in.readString();
    classroom = in.readString();
    teacname = in.readString();
    day = in.readString();
    start_hour = in.readString();
    end_hour = in.readString();
}



@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}



@Override
public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub

    //dest.writeStringArray(new String[]{this.course_name,this.classroom,this.teacname,this.day,this.start_hour,this.end_hour});
    dest.writeString(course_name);
    dest.writeString(classroom);
    dest.writeString(teacname);
    dest.writeString(day);
    dest.writeString(start_hour);
    dest.writeString(end_hour);
}

public static final Parcelable.Creator CREATOR =new
        Parcelable.Creator() {
             public Courses createFromParcel(Parcel in){
                 return new Courses(in);
             }
             public Courses[] newArray(int size){
                 return new Courses[size];
             }
        };






@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_lecture);

     final Courses course = new Courses();

    add_class = (Button)findViewById(R.id.add);
    cName = (EditText)findViewById(R.id.class_Name);
    cRoom = (EditText)findViewById(R.id.classroom);
    tName = (EditText)findViewById(R.id.teacher_name);
    gun = (Spinner)findViewById(R.id.day);
    sHour = (Spinner)findViewById(R.id.start_hour);
    eHour = (Spinner)findViewById(R.id.end_hour);





    days = new ArrayList();
    days.add("Monday");
    days.add("Thuesday");
    days.add("Wednesday");
    days.add("Thursday");
    days.add("Friday");
    days.add("Saturday");


    ArrayAdapter adp = new ArrayAdapter
    (this, android.R.layout.simple_dropdown_item_1line, days);

    adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    gun.setAdapter(adp);

    gun.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView arg0, View arg1,
                int arg2, long arg3) {


            //Courses a = new Courses(); 

            switch(arg2) {

            case 0 :
                course.setDay("Monday");
                break;
            case 1 :
                course.setDay("Tuesday");
                break;
            case 2 :
                course.setDay("Wednesday");
                break;
            case 3 :
                course.setDay("Thursday");
                break;
            case 4 :
                course.setDay("Friday");
                break;
            case 5:
                course.setDay("Saturday");
            }               
        }
        @Override
        public void onNothingSelected(AdapterView arg0) {


        }
    });

    String[] Hours = getResources().getStringArray(R.array.Starting_Hours);
    ArrayAdapter adp1=new ArrayAdapter
             (this, android.R.layout.simple_spinner_item,Hours);
    adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sHour.setAdapter(adp1);

    sHour.setOnItemSelectedListener(new OnItemSelectedListener(){

        @Override
        public void onItemSelected(AdapterView arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub

            //Courses a = new Courses(); 

            switch(arg2) {

            case 0 :
                course.setStart_hour("8:00");
                break;
            case 1 :
                course.setStart_hour("8:30");
                break;
            case 2 :
                course.setStart_hour("9:00");
                break;
            case 3 :
                course.setStart_hour("9:30");
                break;
            case 4 :
                course.setStart_hour("10:00");
                break;
            case 5:
                course.setStart_hour("10:30");
                break;
            case 6:
                course.setStart_hour("11:00");
                break;
            case 7:
                course.setStart_hour("11:30");
                break;
            case 8:
                course.setStart_hour("12:00");
                break;
            case 9:
                course.setStart_hour("12:30");
                break;
            case 10:
                course.setStart_hour("13:00");
                break;
            case 11:
                course.setStart_hour("13:30");
                break;
            case 12:
                course.setStart_hour("14:00");
                break;
            case 13:
                course.setStart_hour("14:30");
                break;
            case 14:
                course.setStart_hour("15:00");
                break;
            case 15:
                course.setStart_hour("15:30");
                break;
            case 16:
                course.setStart_hour("16:00");
                break;
            case 17:
                course.setStart_hour("16:30");
                break;
            case 18:
                course.setStart_hour("17:00");
                break;
            case 19:
                course.setStart_hour("17:30");
                break;
            case 20:
                course.setStart_hour("18:00");
                break;
            case 21:
                course.setStart_hour("18:30");
                break;
            case 22:
                course.setStart_hour("19:00");
                break;
            }               
        }
        @Override
        public void onNothingSelected(AdapterView arg0) {
            // TODO Auto-generated method stub

        }
    });
    String [] _eHours = getResources().getStringArray(R.array.Ending_Hours);
    ArrayAdapter adp2=new ArrayAdapter
             (this, android.R.layout.simple_spinner_item,_eHours);
    adp2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    eHour.setAdapter(adp2);

    eHour.setOnItemSelectedListener(new OnItemSelectedListener(){

        @Override
        public void onItemSelected(AdapterView arg0, View arg1,
                int arg2, long arg3) {


            //Courses a = new Courses(); 

            switch(arg2) {

            case 0 :
                course.setEnd_hour("9:00");
                break;
            case 1 :
                course.setEnd_hour("9:30");
                break;
            case 2 :
                course.setEnd_hour("10:00");
                break;
            case 3:
                course.setEnd_hour("10:30");
                break;
            case 4:
                course.setEnd_hour("11:00");
                break;
            case 5:
                course.setEnd_hour("11:30");
                break;
            case 6:
                course.setEnd_hour("12:00");
                break;
            case 7:
                course.setEnd_hour("12:30");
                break;
            case 8:
                course.setEnd_hour("13:00");
                break;
            case 9:
                course.setEnd_hour("13:30");
                break;
            case 10:
                course.setEnd_hour("14:00");
                break;
            case 11:
                course.setEnd_hour("14:30");
                break;
            case 12:
                course.setEnd_hour("15:00");
                break;
            case 13:
                course.setEnd_hour("15:30");
                break;
            case 14:
                course.setEnd_hour("16:00");
                break;
            case 15:
                course.setEnd_hour("16:30");
                break;
            case 16:
                course.setEnd_hour("17:00");
                break;
            case 17:
                course.setEnd_hour("17:30");
                break;
            case 18:
                course.setEnd_hour("18:00");
                break;
            case 19:
                course.setEnd_hour("18:30");
                break; 
            case 20:
                course.setEnd_hour("19:00");
                break;
            }               
        }
        @Override
        public void onNothingSelected(AdapterView arg0) {
            // TODO Auto-generated method stub

        }
    });




     add_class.setOnClickListener(new OnClickListener(){

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

            course.setCourse_name(cName.getText().toString());
            course.setClassroom(cRoom.getText().toString());
            course.setTeacname(tName.getText().toString());


       /* Toast.makeText(getApplicationContext(),course.getCourse_name(),Toast.LENGTH_LONG ).show(); 
        Toast.makeText(getApplicationContext(), course.getClassroom().toString(), Toast.LENGTH_LONG).show();
        Toast.makeText(getApplicationContext(), course.getTeacname().toString(), Toast.LENGTH_LONG).show();
        Toast.makeText(getApplication(), course.getDay(), Toast.LENGTH_LONG).show();
        Toast.makeText(getApplication(), course.getStart_hour(), Toast.LENGTH_LONG).show();
        Toast.makeText(getApplication(), course.getEnd_hour(), Toast.LENGTH_LONG).show();*/

            /*data.putExtra("crs",new Courses(cName.getText().toString(),cRoom.getText().toString(),tName.getText().toString(),
                    gun.getSelectedItem().toString(),sHour.getSelectedItem().toString(),eHour.getSelectedItem().toString()));*/

            Intent data = new Intent(Courses.this,MainActivity.class);
            data.putExtra("ders",course);



        setResult(RESULT_OK,data);
        finish();

        }
    });


}

вот MainActivity.java

package com.example.classprogram;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;

  public class MainActivity extends Activity {

public GridLayout glayout;
protected String _COURSENAME ;
protected String _CLASSROOM ;
protected String _TCHRNAME ;
protected String _DAY ;
protected String _SHOUR ;
protected String _EHOUR ;
//private Bundle extras[] ;
int THIS = 1;
TextView[][] indexes = new TextView[7][24];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    glayout = (GridLayout)findViewById(R.id.grid);

    glayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent in = new Intent (getApplicationContext(),Courses.class);
            startActivityForResult(in,THIS);


        }
    });

}




@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if(requestCode==THIS){
        if(resultCode==RESULT_OK){

              // Bundle d = getIntent().getExtras();
         //Courses _course = d.getParcelable("crs");

          Intent x = getIntent();
          Courses _course = (Courses) x.getParcelableExtra("course");

          Toast.makeText(getApplicationContext(), _course.getCourse_name(), Toast.LENGTH_LONG).show();

            /*for(int i=0;i

Ваш Ответ

5   ответов
5

onActivityResult Метод, есть параметр для.Intent

Сделать это onActivityResult: -

        Bundle bundle = data.getExtras();

они ы можете получить лишнийс помощью этого объекта пакета

@ Dane411 Потому что getIntent () вернет намерение, под которым была создана текущая активность, а не то, что было возвращено из действия, начатого сstartActivityForResult Riptyde4
Почему он должен использовать "Намерение данных "вместо создания нового или использованияgetIntent () "? Dane411
3

Вызовите супер первым делом в onActivityResult ():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //first call super
    super.onActivityResult(requestCode, resultCode, data);

    //rest of your code
    if(requestCode==THIS) {

И действительно вместо

Intent x = getIntent();

делать:

Intent x = data;
0

как у меня сработало следующее

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_CANCELED && data != null) {
            if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
           -----
            }
        }
    }
0

заменить линию

Intent x = getIntent();

вIntent x = data;

Я получил ту же ошибку (NullPointerException). softwareengineer
проверьте, проходите ли вы курс объекта с ключомкурс" от этой деятельности в этом комплекте San
1

Intent data = new Intent(Courses.this,MainActivity.class);
data.putExtra("ders",course);
startActivity(data);

В MainActivity.java я заменилкурс" с "Ders» Значение ключа bcoz равно "Ders»

Intent x = getIntent();
Courses _course = (Courses) x.getParcelableExtra("ders");

Похожие вопросы