我在下面发布了两个类和spinner的XML代码。我还发布了logcat错误。当我点击微调项目时,它很遗憾地停止了。微调器项目加载了基于json的数据,这些数据是从MYSQL数据库
中检索的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)
答案 0 :(得分:1)
似乎你将getPackageName()称为脱离上下文。请在Activity.onCreate()
中调用getPackageName()答案 1 :(得分:0)
你应该摆脱公共类ItemSelectedListener中的extends Activity 对于启动活动,您可以使用parent.getContext()。startActivity();
答案 2 :(得分: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)
初始化Context
时,Intent
为空。要知道为什么阅读
Can i Create the object of a activity in other class?
你有什么
public class ItemSelectedListener extends Activity implements OnItemSelectedListener {
和
spinner1.setOnItemSelectedListener(new ItemSelectedListener());
您无法实例化Activity类。
你可以使用一个不规则的内部类。所以改为
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
}
});
同样适用于spinner2
。
你所拥有的是一个匿名的内部类,它实现了你重写OnItemSelectedListener
的接口onItemSelected
并执行那里所需要的。
答案 3 :(得分:0)
如果您不想要内部类
,可以将一个Activity作为监听器的参数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) {
}
}