【问题标题】:Unable to start activity ComponentInfo: java.lang.NullPointerException error while try to create the numberpicker AndroidUnable to start activity ComponentInfo: java.lang.NullPointerException error while try to create the numberpicker Android
【发布时间】:2014-06-12 08:07:15
【问题描述】:

您好,在我的应用程序中,我正在尝试创建 NumberPicker,但它无法正常工作,出现类似错误。

    06-12 13:07:33.938: E/AndroidRuntime(7521): FATAL EXCEPTION: main
    06-12 13:07:33.938: E/AndroidRuntime(7521): Process: com.politicalmileage.elangovan, PID: 7521
    06-12 13:07:33.938: E/AndroidRuntime(7521): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.politicalmileage.elangovan/com.politicalmileage.elangovan.Schedule}: java.lang.NullPointerException
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.os.Handler.dispatchMessage(Handler.java:102)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.os.Looper.loop(Looper.java:136)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.ActivityThread.main(ActivityThread.java:5017)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at java.lang.reflect.Method.invokeNative(Native Method)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at java.lang.reflect.Method.invoke(Method.java:515)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at dalvik.system.NativeStart.main(Native Method)
    06-12 13:07:33.938: E/AndroidRuntime(7521): Caused by: java.lang.NullPointerException
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at com.politicalmileage.elangovan.Schedule.onCreate(Schedule.java:58)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.Activity.performCreate(Activity.java:5231)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
    06-12 13:07:33.938: E/AndroidRuntime(7521):     ... 11 more

我的 XML 代码。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:textColor="#43bd00"
    android:textSize="16sp"
    android:textStyle="bold"
    android:text="TextView" />


<TextView
    android:id="@+id/cost"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/title"
    android:text="TextView" />



<Button
    android:id="@+id/bAdd"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/title"
    android:layout_marginLeft="17dp"
    android:layout_toRightOf="@+id/title"
    android:text="+" />

<Button
    android:id="@+id/bSub"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/bAdd"
    android:layout_toRightOf="@+id/tvDisplay"
    android:text="-" />

<TextView
    android:id="@+id/tvDisplay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/bSub"
    android:layout_alignBottom="@+id/bSub"
    android:layout_toRightOf="@+id/bAdd"
    android:text="1" />

我的 java 代码。

   public class Schedule extends ListActivity {

     private ProgressDialog pDialog;
      int counter = 1;
      Button add,sub;
      TextView display;

// URL to get contacts JSON
private static String url = "myurl";

// JSON Node names
private static final String TAG_SCHEDULES = "schedule";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
/*private static final String TAG_CONTENT = "content";*/
private static final String TAG_COST = "cost";
/*private static final String TAG_DATETIME = "date_time";*/

// contacts JSONArray
JSONArray schedules = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> schedule_list;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.schedule_list_view);
    add = (Button) findViewById(R.id.bAdd);
    sub = (Button) findViewById(R.id.bSub);
    display = (TextView) findViewById(R.id.tvDisplay);
    add.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
        counter++;
        display.setText( "" + counter);
        }
    });

    sub.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
        counter--;
        display.setText( "" + counter);
        }
    });


    schedule_list = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();





    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
            /*String content = ((TextView) view.findViewById(R.id.content)).getText().toString();*/
            String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
            /*String datetime = ((TextView) view.findViewById(R.id.datetime)).getText().toString();*/



            // Starting single contact activity
            Intent in = new Intent(getApplicationContext(), ScheduleDetail.class);
            in.putExtra(TAG_TITLE, title);
            in.putExtra(TAG_COST, cost);
            /*in.putExtra(TAG_CONTENT, content);
            in.putExtra(TAG_DATETIME, datetime);*/
            startActivity(in);

        }
    });

    // Calling async task to get json
    new GetSchedule().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetSchedule extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Schedule.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                schedules = jsonObj.getJSONArray(TAG_SCHEDULES);

                // looping through All Schdules
                for (int i = 0; i < schedules.length(); i++) {
                    JSONObject c = schedules.getJSONObject(i);

                    String id = c.getString(TAG_ID);
                    String title = c.getString(TAG_TITLE);
                    /*String content = c.getString(TAG_CONTENT);*/
                    String cost = c.getString(TAG_COST);
                    /*String datetime = c.getString(TAG_DATETIME);*/

                    // Phone node is JSON Object

                    // tmp hashmap for Schedule
                    HashMap<String, String> schedule_file = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    schedule_file.put(TAG_ID, id);
                    schedule_file.put(TAG_TITLE, title);
                    /*schedule_file.put(TAG_CONTENT, content);*/
                    schedule_file.put(TAG_COST, cost);
                    /*schedule_file.put(TAG_DATETIME, datetime);*/

                    // adding schedule list
                    schedule_list.add(schedule_file);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */

        ListAdapter adapter = new SimpleAdapter(
                Schedule.this, schedule_list, 
                R.layout.schedule_list_item, 
                new String[] { TAG_TITLE, TAG_COST }, 
                new int[] { R.id.title,R.id.cost });

        setListAdapter(adapter);
      }
     }
   }

我正在尝试使用我的服务器的一些文本创建最小最大数,它无法正常工作,它显示空指针异常错误请在上面的代码中告诉我在哪里做错了如何解决这个问题。

谢谢。

【问题讨论】:

  • 第 58 行是什么Schedule.java
  • 可能是String title = ((TextView) view.findViewById(R.id.title)).getText().toString();@Raghunandan
  • 发布schedule_list_item.xml。 @blackbelt 所有视图都在一个布局中。所以是的,你可能是对的
  • @blackbelt 这不是此 NPE 的原因,因为该行位于匿名内部子类中,而不是直接位于 onCreate() 中。
  • @Raghunandan 我正在使用列表视图,它在列表视图内的另一个布局中我正在使用列表项 schedule_list_item.xml 高于 xml

标签: android nullpointerexception numberpicker


【解决方案1】:

您使用setContentView() 设置的schedule_list_view 布局不包含您尝试使用findViewById() 访问的视图,并且返回null。在 null 上调用方法会导致 NPE。

如果schedule_list_view 是内容视图,由于缺少android:id/list ListView,您会在getListView() 得到不同的异常。

【讨论】:

  • 你能告诉我我想改变哪里吗
  • setContentView()R.layout.something 一起使用,其中something.xml 包含具有您与findViewById() 一起使用的ID 的视图。
猜你喜欢
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多