无法启动包含主活动的json解析器http的活动

时间:2017-04-10 16:20:49

标签: android json

我遇到了一个问题。我有2个活动,第一个是主要活动,另一个是第二个活动。第二个活动包含使用http的json解析器的数据。我在主要活动中添加了按钮。当我点击按钮跳转到第二个活动,但应用程序停止。我该如何解决这个问题?

这里的主要活动。

public class MainActivity extends Activity{

    Button b;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        b = (Button) findViewById(R.id.button1);

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });
    }
}

这里的SecondActivity(当我只运行第二次活动时,它工作正常。)

public class SecondActivity extends ListActivity {

    ListView mylist;
    ProgressDialog PD;

    // JSON Node names
    public static final String TAG_ID = "id";
    public static final String TAG_NAME = "name";
    //public static final String TAG_TYPE = "төрөл";

    public static final String TAG_MATH = "Mathematics";
    public static final String TAG_SCIE = "Science";
    public static final String TAG_COMP = "Computer";

    List<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();

    /* Called when the activity is first created. */
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListView listview = getListView();
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                String stud_id = studentList.get(position).get(TAG_ID);
                String stud_name = studentList.get(position).get(TAG_NAME);

                Intent stud_intent = new Intent(SecondActivity.this,
                        Student_Detail.class);

                stud_intent.putExtra("stud", studentList.get(position));

                startActivity(stud_intent);

            }
        });

        new MyTask().execute();

    }

    class MyTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            PD = new ProgressDialog(SecondActivity.this);
            PD.setMessage("Loading...");
            PD.setCancelable(false);
            PD.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            String webdata = new MakeRequest().MakeGetRequest();
            String name = null;

            try {
                JSONObject json = new JSONObject(webdata);

                JSONArray employee = json.getJSONArray("students");

                for (int i = 0; i < employee.length(); i++) {

                    JSONObject students = employee.getJSONObject(i);

                    HashMap student = new HashMap<String, String>();
                    student.put(TAG_ID, students.get(TAG_ID));
                    student.put(TAG_NAME, students.get(TAG_NAME));
                    //student.put(TAG_TYPE, students.get(TAG_TYPE));

                    JSONObject score = students.getJSONObject("score");
                    student.put(TAG_MATH, score.get(TAG_MATH));
                    student.put(TAG_SCIE, score.get(TAG_SCIE));
                    student.put(TAG_COMP, score.get(TAG_COMP));

                    studentList.add(student);

                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;

        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);

            String[] from = { TAG_ID, TAG_NAME };
            int[] to = { R.id.stud_id, R.id.stud_name };

            ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
                    studentList, R.layout.list_items, from, to);

            setListAdapter(adapter);

            PD.dismiss();

        }

    }

}

此处显示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pavan.androidjsondemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pavan.androidjsondemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity" ></activity>
        <activity android:name=".Student_Detail" >
        </activity>
    </application>

</manifest>

这里的堆栈跟踪

04-11 00:42:29.751 2280-2280/? I/art: Not late-enabling -Xcheck:jni (already on)
04-11 00:42:29.751 2280-2280/? W/art: Unexpected CPU variant for X86 using defaults: x86
04-11 00:42:29.782 2280-2280/? W/System: ClassLoader referenced unknown path: /data/app/com.pavan.androidjsondemo-1/lib/x86
04-11 00:42:29.972 2280-2280/com.pavan.androidjsondemo D/AndroidRuntime: Shutting down VM


                                                                         --------- beginning of crash
04-11 00:42:29.972 2280-2280/com.pavan.androidjsondemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.pavan.androidjsondemo, PID: 2280
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pavan.androidjsondemo/com.pavan.androidjsondemo.MainAc}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                                          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                             at com.pavan.androidjsondemo.MainAc.onCreate(MainAc.java:23)
                                                                             at android.app.Activity.performCreate(Activity.java:6662)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                             at android.os.Looper.loop(Looper.java:154) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                                             at java.lang.reflect.Method.invoke(Native Method) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

1 个答案:

答案 0 :(得分:0)

您需要在setContentView(R.layout.activity_layout_xml_file)方法之后在您的MainActivity中加入super.onCreate(savedInstanceState);。阅读更多here

当您没有设置布局时,Activity中没有视图(除非您以编程方式构造布局;但是更容易坚持布局)。然后,findViewBy(R.id.button1)将返回null,因为无法找到具有此ID的视图。这会导致b.setOnClickListener(...)上的NullPointerException。