Почему данные Bundle выдают ошибку при получении?

Я написал очень маленький код для передачи данных через связку между двумя действиями. Теперь я думаю, что выполнил правильные шаги, но код выдает ошибку. Извините, если это очень глупая ошибка, но я застрял и ослеп на этот код, пожалуйста, помогите мне. Вот код..

package veniteck.solutions.mapmymetro;

    public class MainActivity extends Activity 
    {
    ImageView findnearestsource, findnearestdestination, getroute;
    String[] stops = {
            "Bangalore International Exhibition Center", "Jindal", "Manjunathnagar", "Nagasandra", "Dasarahalli", "Jalahalli", "Peenya Industry", "Peenya", "Yeswanthpur Industry", "Yeswanthpur", "Sandal Soap Factory", "Mahalaxmi", "Rajajinagar", "Kuvempu Road", "Srirampura", "Sampige Road", "Kempegowda Interchange", "Chikpet", "K R Market", "National College", "Lalbagh", "South End Circle", "Jayanagar", "R V Road Interchange", "Banashankari", "J P Nagar", "Puttenahalli", "Anjanapura Cross Road", "Krishna Leela Park", "Vajrahalli", "Thaighattapura", "Anjanapura/NICE Junction", "Kengeri", "R V College of Engineering", "Bangalore University Cross", "Rajarajeshwari Nagar", "Nayandahalli", "Mysore Road", "Deepanjali Nagar", "Attiguppe", "Vijayanagar", "Hosahall1i", "Magadi Road", "Sir M Vishweshwariah", "Vidhana Soudha", "M G Road Interchange", "Trinity", "Halasuru", "Indiranagar", "S V Road", "Baiyyappanahalli", "Jyotipura", "K R Puram", "Mahadevpura", "Garudacharpalya", "Doddanekkundi Induatrial State", "Vishweshwariah Industrial State", "Kundanahalli", "Vydhehi Hospital", "Satya Sai Medical Institute", "ITPB", "Kadugodi Industrial Area", "Ujjwal Vidhyalaya", "Whitefield", "Nagawara", "Arabic College", "Venkateshpura", "Tannery Town", "Pottery Town", "Cantonment Railway Station", "Shivajinagar", "Vellara Junction", "Langford Town", "Mico Bosch", "Dairy Circle", "Swagath Road Cross", "Jayadeva Hospital Interchange", "J P Nagar 4th Phase", "IIMB", "Hulimavu", "Gottigere", "Ragigudda Temple", "BTM Layout", "Silk Board", "HSR Layout", "Oxford College", "Muneshwara Nagar", "Chikkabegur", "Basapura Road", "Hosa Road", "Electronics City 1", "Electronics City 2", "Huskur Road", "Hebbagodi", "Bommasandra"
            };

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

        AutoCompleteTextView source = (AutoCompleteTextView)findViewById(R.id.autofillsource);
        source.setAdapter(new ArrayAdapter<String>(this, R.layout.list_details, stops));

        AutoCompleteTextView destination = (AutoCompleteTextView)findViewById(R.id.autofilldestination);
        destination.setAdapter(new ArrayAdapter<String>(this, R.layout.list_details, stops));

        findnearestsource = (ImageView)findViewById(R.id.findnearestsource);
        findnearestsource.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Please Wait..", Toast.LENGTH_LONG).show();

            }
        });

        findnearestdestination = (ImageView)findViewById(R.id.findnearestdestination);
        findnearestdestination.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Please Wait..", Toast.LENGTH_LONG).show();

            }
        });

        getroute = (ImageView)findViewById(R.id.getroute);
        getroute.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Please Wait..", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(MainActivity.this,Route.class);
                startActivity(intent);

            }   
        });



         // SECTION FOR BUNDLE CODE

        String src = source.getText().toString();
        String dest = destination.getText().toString();


         Bundle b = new Bundle();

         b.putString("srcstop", src);
         b.putString("deststop", dest);

         Intent in = new Intent(getApplicationContext(), Route.class);
         in.putExtras(b);
         startActivity(in);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    }

Другая деятельность

Route.java

    public class Route  extends Activity 
    {


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



         // SECTION FOR BUNDLE CODE



          TextView RouteText = (TextView)findViewById(R.id.RouteText);

          Intent in = getIntent();

          //Getting bundle
          Bundle b = in.getExtras();

          //Getting data from bundle
          String Source = b.getString("srcstop");
          String Destination = b.getString("deststop");

          //Binding values to TextViews
           RouteText.setText("Getting route directions from " +Source +"to " +Destination);


    }
    }

Вот выход Logcat..

Logcat

Logcat в текстовом формате

10-04 12:38:13.722: D/dalvikvm(972): GC_FOR_ALLOC freed 0K, 4% free 8173K/8455K, paused 26ms, total 26ms
10-04 12:38:13.732: I/dalvikvm-heap(972): Grow heap (frag case) to 8.881MB for 896016-byte allocation
10-04 12:38:13.852: D/dalvikvm(972): GC_CONCURRENT freed 0K, 4% free 9048K/9351K, paused 74ms+14ms, total 120ms
10-04 12:38:13.922: I/Choreographer(972): Skipped 144 frames!  The application may be doing too much work on its main thread.
10-04 12:38:14.032: D/gralloc_goldfish(972): Emulator without GPU emulation detected.
10-04 12:38:14.381: I/Choreographer(972): Skipped 56 frames!  The application may be doing too much work on its main thread.
10-04 12:38:26.531: I/Choreographer(972): Skipped 30 frames!  The application may be doing too much work on its main thread.
10-04 12:38:37.222: D/AndroidRuntime(972): Shutting down VM
10-04 12:38:37.222: W/dalvikvm(972): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-04 12:38:37.242: E/AndroidRuntime(972): FATAL EXCEPTION: main
10-04 12:38:37.242: E/AndroidRuntime(972): java.lang.RuntimeException: Unable to start activity ComponentInfo{veniteck.solutions.mapmymetro/veniteck.solutions.mapmymetro.Route}: java.lang.NullPointerException
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.os.Looper.loop(Looper.java:137)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.ActivityThread.main(ActivityThread.java:4745)
10-04 12:38:37.242: E/AndroidRuntime(972):  at java.lang.reflect.Method.invokeNative(Native Method)
10-04 12:38:37.242: E/AndroidRuntime(972):  at java.lang.reflect.Method.invoke(Method.java:511)
10-04 12:38:37.242: E/AndroidRuntime(972):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-04 12:38:37.242: E/AndroidRuntime(972):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-04 12:38:37.242: E/AndroidRuntime(972):  at dalvik.system.NativeStart.main(Native Method)
10-04 12:38:37.242: E/AndroidRuntime(972): Caused by: java.lang.NullPointerException
10-04 12:38:37.242: E/AndroidRuntime(972):  at veniteck.solutions.mapmymetro.Route.onCreate(Route.java:25)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.Activity.performCreate(Activity.java:5008)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-04 12:38:37.242: E/AndroidRuntime(972):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-04 12:38:37.242: E/AndroidRuntime(972):  ... 11 more

Когда я ничего не ввожу в текстовые просмотры на 1-м занятии

Я могу пойти в Route.java.

Но когда я что-то ввожу,

и нажмите получить маршрут, он падает.

Действительно очень жаль, если этот квест достаточно глуп, чтобы не быть на SO. Но я действительно не понимаю решение.

4 ответа

Решение

Вы должны переместить их внутрь onClick, Изменить на

getroute.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
          Toast.makeText(getApplicationContext(), "Please Wait..", Toast.LENGTH_LONG).show();
          String src = source.getText().toString();
          String dest = destination.getText().toString();
          Bundle b = new Bundle();
          b.putString("srcstop", src);
          b.putString("deststop", dest);
          Intent in = new Intent(MainActivity.this, Route.class);
          in.putExtras(b);
          startActivity(in);

        }   
    });

Ниже находится внешний прослушиватель кликов. Таким образом, строки являются нулевыми. Переместить его внутрь onClick

String src = source.getText().toString();
String dest = destination.getText().toString();

Также внесите эти изменения

final AutoCompleteTextView source = (AutoCompleteTextView)findViewById(R.id.autofillsource);
final AutoCompleteTextView destination = (AutoCompleteTextView)findViewById(R.id.autofilldestination);

Ваш код находится вне слушателя щелчка. Сделайте это внутри слушателя щелчка, и это должно работать..

String src = source.getText().toString();
String dest = destination.getText().toString();

Ваш пакет имеет значение null, пожалуйста, проверьте здесь принятый ответ, чтобы увидеть, как правильно его установить: Передача пакета в startActivity()?

Попробуйте написать следующий код в onclick() mainActivity:

        String src = source.getText().toString();
        String dest = destination.getText().toString();


         Bundle b = new Bundle();

         b.putString("srcstop", src);
         b.putString("deststop", dest);

         Intent in = new Intent(getApplicationContext(), Route.class);
         in.putExtras(b);
         startActivity(in);
Другие вопросы по тегам