0

I have posted two classes below and the XML code for the spinner. I also posted the logcat errors. When i click on the spinner item, it unfortunately has stopped. The spinner items is loaded with json based data which are retrieved from MYSQL database

MyMainScreen.java

public class MyMainScreen extends Activity implements OnClickListener{

// Widget GUI
Button btnCalendar, btnCalendar1, btnTime, btnTime1;
private Spinner spinner1, spinner2;
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;

// API urls
// Url to get all categories
private String URL_CATEGORIES = "http://10.0.2.2:8888/jobs/get_categories.php";


 // Variable for storing current date and time

private int mYear, mMonth, mDay, mHour, mMinute;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    addListenerOnSpinnerItemSelection();

    btnCalendar = (Button) findViewById(R.id.btnCalendar);
    btnTime = (Button) findViewById(R.id.btnTime);
    btnCalendar1 = (Button) findViewById(R.id.btnCalendar1);
    btnTime1 = (Button) findViewById(R.id.btnTime1);

    btnCalendar.setOnClickListener(this);
    btnTime.setOnClickListener(this);
    btnCalendar1.setOnClickListener(this);
    btnTime1.setOnClickListener(this);
    categoriesList = new ArrayList<Category>();

    new GetCategories().execute(); 
}

/**
 * Async task to get all food categories
 * */
private class GetCategories extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MyMainScreen.this);
        pDialog.setMessage("Fetching data..");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        ServiceHandler jsonParser = new ServiceHandler();
        String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);

        Log.e("Response: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                if (jsonObj != null) {
                    JSONArray categories = jsonObj
                            .getJSONArray("pickup");                        

                    for (int i = 0; i < categories.length(); i++) {
                        JSONObject catObj = (JSONObject) categories.get(i);
                        Category cat = new Category(catObj.getInt("id"),
                                catObj.getString("name"));
                        categoriesList.add(cat);
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            Log.e("JSON Data", "Didn't receive any data from server!");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        populateSpinner();
    }

}

/**
 * Adding spinner data
 * */
private void populateSpinner() {
    List<String> lables = new ArrayList<String>();

    for (int i = 0; i < categoriesList.size(); i++) {
        lables.add(categoriesList.get(i).getName());
    }

    // Creating adapter for spinner
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, lables);

    // Drop down layout style - list view with radio button
    spinnerAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner1.setAdapter(spinnerAdapter);
    spinner2.setAdapter(spinnerAdapter);
}

public void addListenerOnSpinnerItemSelection() {
    spinner1 = (Spinner) findViewById(R.id.spinnerpick);
    spinner1.setOnItemSelectedListener(new ItemSelectedListener());
    spinner2 = (Spinner) findViewById(R.id.spinnerdrop);
    spinner2.setOnItemSelectedListener(new ItemSelectedListener());
  }



@Override
public void onClick(View v) {

     if (v == btnCalendar) {
    // Process to get Current Date
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    // Launch Date Picker Dialog
    DatePickerDialog dpd = new DatePickerDialog(this,
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth) {
                    // Display Selected date in text box
                    btnCalendar.setText(dayOfMonth + "-"
                            + (monthOfYear + 1) + "-" + year);

                }
            }, mYear, mMonth, mDay);
    dpd.show();
}

     if (v == btnTime) {

         // Process to get Current Time
         final Calendar c = Calendar.getInstance();
         mHour = c.get(Calendar.HOUR_OF_DAY);
         mMinute = c.get(Calendar.MINUTE);

         // Launch Time Picker Dialog
         TimePickerDialog tpd = new TimePickerDialog(this,
                 new TimePickerDialog.OnTimeSetListener() {

                     @Override
                     public void onTimeSet(TimePicker view, int hourOfDay,
                             int minute) {
                         // Display Selected time in text box
                         btnTime.setText(hourOfDay + ":" + minute);
                     }
                 }, mHour, mMinute, false);
         tpd.show();



}

     if (v == btnCalendar1) {
            // Process to get Current Date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            // Launch Date Picker Dialog
            DatePickerDialog dpd1 = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {
                            // Display Selected date in text box
                            btnCalendar1.setText(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
            dpd1.show();
        }

             if (v == btnTime1) {

                 // Process to get Current Time
                 final Calendar c = Calendar.getInstance();
                 mHour = c.get(Calendar.HOUR_OF_DAY);
                 mMinute = c.get(Calendar.MINUTE);

                 // Launch Time Picker Dialog
                 TimePickerDialog tpd1 = new TimePickerDialog(this,
                         new TimePickerDialog.OnTimeSetListener() {

                             @Override
                             public void onTimeSet(TimePicker view, int hourOfDay,
                                     int minute) {
                                 // Display Selected time in text box
                                 btnTime1.setText(hourOfDay + ":" + minute);
                             }
                         }, mHour, mMinute, false);
                 tpd1.show();



    }

   }

ItemSelectedListener.java

public class ItemSelectedListener extends Activity implements OnItemSelectedListener {

int check=0;

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

 }


  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
      check=check+1;
               if(check>1)
              {
    Toast.makeText(parent.getContext(), 
        "You have selected : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
  }


 switch(pos){
    case 1:
           Intent intent = new Intent(ItemSelectedListener.this, Play.class);
                      startActivity(intent);
                        break;
        case 2:
           Intent intenti = new Intent(ItemSelectedListener.this, Play.class);
                       startActivity(intenti);
                        break;
        // and so on 
        // .....

                }


  }
@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}


}

activity_main.xml

<LinearLayout 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:orientation="vertical"
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=".MainActivity" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_up" />

<LinearLayout
    android:id="@+id/linearlayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <Spinner
        android:id="@+id/spinnerpick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"
      />

    <Button
        android:id="@+id/btnCalendar"
        style="?android:attr/spinnerStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/Calendar" />

    <Button
        android:id="@+id/btnTime"
        style="?android:attr/spinnerStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/time_picker" />
</LinearLayout>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:text="@string/drop_off" />

 <LinearLayout
    android:id="@+id/linearlayout2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

      <Spinner
        android:id="@+id/spinnerdrop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown" />

    <Button
        android:id="@+id/btnCalendar1"
        style="?android:attr/spinnerStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/Calendar" />

    <Button
        android:id="@+id/btnTime1"
        style="?android:attr/spinnerStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/time_picker" />

    </LinearLayout>

 <RelativeLayout
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

 <Button
        android:id="@+id/btnSubmit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/button_send" />

   </RelativeLayout>

Logcat

  04-24 03:08:10.585: D/AndroidRuntime(1115): Shutting down VM
  04-24 03:08:10.585: W/dalvikvm(1115): threadid=1: thread exiting with uncaught exception      (group=0x41465700)
  04-24 03:08:10.635: E/AndroidRuntime(1115): FATAL EXCEPTION: main
  04-24 03:08:10.635: E/AndroidRuntime(1115): java.lang.NullPointerException
  04-24 03:08:10.635: E/AndroidRuntime(1115): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.content.ComponentName.<init>(ComponentName.java:75)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.content.Intent.<init>(Intent.java:3662)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at com.example.carrental.ItemSelectedListener.onItemSelected(ItemSelectedListener.java:32)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.widget.AdapterView.access$200(AdapterView.java:49)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.os.Handler.handleCallback(Handler.java:730)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.os.Handler.dispatchMessage(Handler.java:92)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.os.Looper.loop(Looper.java:137)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.app.ActivityThread.main(ActivityThread.java:5103)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at java.lang.reflect.Method.invokeNative(Native Method)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at java.lang.reflect.Method.invoke(Method.java:525)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
  04-24 03:08:10.635: E/AndroidRuntime(1115):   at dalvik.system.NativeStart.main(Native Method)

4 Answers4

1

seems you call getPackageName() out of context. please invoke getPackageName() in Activity.onCreate()

Jiang YD
  • 3,205
  • 1
  • 14
  • 20
  • what did you mean?add getPackage name for what use? – user3402438 Apr 24 '14 at 07:29
  • you can not new instance of Activity or any subclass. Activity should be created by Android Framework. Because the onCreate method of new ItemSelectedListener instance you created will not invoked, means you are out of context. – Jiang YD Apr 24 '14 at 07:35
0

You should get rid of the extends Activity in the public class ItemSelectedListener
and for the start activity you can use parent.getContext().startActivity();

Niko Adrianus Yuwono
  • 11,012
  • 8
  • 42
  • 64
0
 04-24 03:08:10.635: E/AndroidRuntime(1115): java.lang.NullPointerException
 04-24 03:08:10.635: E/AndroidRuntime(1115): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
 04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.content.ComponentName.<init>(ComponentName.java:75)
 04-24 03:08:10.635: E/AndroidRuntime(1115):   at android.content.Intent.<init>(Intent.java:3662)

The Context is null when you initialize Intent. To know why read

Can i Create the object of a activity in other class?

What you have

public class ItemSelectedListener extends Activity implements OnItemSelectedListener {

and

spinner1.setOnItemSelectedListener(new ItemSelectedListener());

You cannot instantiate a Activity class.

You can use a anonumous inner class. So change to

spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{

    @Override
    public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
            long arg3) {
         Toast.makeText(MainScreen.this, 
                    "You have selected : " + parent.getItemAtPosition(pos).toString(),
                    Toast.LENGTH_SHORT).show();



             switch(pos){
                case 1:
                       Intent intent = new Intent(MyMainScreen.this, Play.class);
                                  startActivity(intent);
                break;
                case 2:
                       Intent intenti = new Intent(MyMainScreen.this, Play.class);
                                   startActivity(intenti);
                break;

              }

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

});

Similarly for spinner2.

What you have is a annonymous inner class which implements the interface OnItemSelectedListener you override onItemSelected and do what is required there.

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • @Raghunandanwhat u mean is to put the onItemSelected method in the mainscreen.java right?why the onItemSelected method cannot be in the separate class? – user3402438 Apr 24 '14 at 07:35
  • @user3402438 `OnItemSelectedListener` is a interface. Either way a class needs to implement the interface. In the suggested solution you have a annonymous inner class that implements the interface. You can have a another class that implements the interface. But for intent you require a valid context. ALso startActivity is a method of Activity class – Raghunandan Apr 24 '14 at 07:37
  • @user3402438 either follow my suggestion or blackbelts suggestion both will work and if you don't know what an interface is you need to read java – Raghunandan Apr 24 '14 at 07:38
  • why the first item in the spinner produces no response? the other items in the spinner work well and is able to start a new activity. – user3402438 Apr 24 '14 at 08:34
  • @user3402438 Need more info. it should work are you sure you refernced the id properly. Are you sure spinner 1 is populated – Raghunandan Apr 24 '14 at 08:36
  • @user3402438 index starts 0. case 0 is missing – Raghunandan Apr 24 '14 at 08:39
  • @user3402438 did you put case 0 and try – Raghunandan Apr 24 '14 at 08:47
  • @user3402438 by default you have the first item selected. You can use a boolean flag to handle that situation. – Raghunandan Apr 24 '14 at 09:03
  • I'm not sure whether I'm correct.I put **boolean firstSelection;** right after the class ItemSelectedListener.Theni put boolean firstSelection=false inside case 0. But same thing occurs. – user3402438 Apr 24 '14 at 09:49
  • but if i change to case 1, the first item has no response. Any solution pls? – user3402438 Apr 24 '14 at 10:33
  • @user3402438 have your first item as `Select...`. Then remove case 0. `Select...` is not the required item. It is selected by default. Then you select any item you can start from index 1. So have your first item in spinner display `Select...`. Its simple coz you say its difficult with boolean flag... – Raghunandan Apr 24 '14 at 10:35
  • my first item is not Select....My first item is exactly the first item in my spinner that can be selected. Still cannot solve it...:( – user3402438 Apr 24 '14 at 10:54
  • @user3402438 i said make it `Select...` is it hard to add one item. This is simplest solution i can provide. If you cannot solve it i can't help further this is leading to a discussion. good luck – Raghunandan Apr 24 '14 at 10:55
0

You can have an Activity as parameter for your Listener, if you do not want the inner class

public class ItemSelectedListener implements OnItemSelectedListener {

int check=0;
Activity mActivity;
public ItemSelectedListener(Activity activity) {
    mActivity = activity;
}

public void onClick(View v) {
 }

 public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
      check=check+1;
      if(check>1) {
        Toast.makeText(mActivity, 
        "You have selected : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
       }

     switch(pos){
        case 1:
           Intent intent = new Intent(mActivity, Play.class);
           mActivity.startActivity(intent);
           break;
        case 2:
           Intent intenti = new Intent(mActivity, Play.class);
           mActivity.startActivity(intenti);
           break;
        // and so on 
        // .....

      }
  }
  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
  }    
}
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • but after i used your method...in the MainScreen class, there is an arror in this part. public void addListenerOnSpinnerItemSelection() { spinner1 = (Spinner) findViewById(R.id.spinnerpick); spinner1.setOnItemSelectedListener(new ItemSelectedListener()); spinner2 = (Spinner) findViewById(R.id.spinnerdrop); spinner2.setOnItemSelectedListener(new ItemSelectedListener()); } – user3402438 Apr 24 '14 at 07:47
  • it becomes `new ItemSelectedListener(this))` – Blackbelt Apr 24 '14 at 07:56
  • @blackbeltDo you know how to fix it because your coding consisted of two ItemSelectedListener which clashed with this part: spinner1.setOnItemSelectedListener(new ItemSelectedListener()); – user3402438 Apr 24 '14 at 08:00
  • @blackbeltbrilliant!!it really works!!thanks for your help..but one thing how comes the first item in the spinner no response? the remaining items is clickable and is able to start a new activity.Except the first item in the spinner – user3402438 Apr 24 '14 at 08:22
  • can you rephrase your last question? – Blackbelt Apr 24 '14 at 08:34
  • @blackbelt i guess op is referring to index 0 case 0 is missing – Raghunandan Apr 24 '14 at 08:39
  • but why he is `switch`ing starting from 1 ? @Raghunandan – Blackbelt Apr 24 '14 at 08:45
  • @blackbelt probably op thought index start from 1. I am not sure what he thought but i am guessing – Raghunandan Apr 24 '14 at 08:46
  • @Raghunandan but after i changed to case 0,another problem occurred.The first item in the spinner automatic being selected and start an activity without being clicked by me – user3402438 Apr 24 '14 at 08:51
  • @user3402438 post the updated code. did you miss a break statement?? – Raghunandan Apr 24 '14 at 08:54
  • @Raghunandan nope..break statement is existed. Can you show me the correct way to use boolean flag in my coding? – user3402438 Apr 24 '14 at 10:05