致命异常:主java.lang.RuntimeException

时间:2015-12-31 02:45:40

标签: java android nullpointerexception runtimeexception

这是我的RestAPI.java

     /* JSON API for android appliation */
    package com.ezchart.restfulapiclient;

     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.OutputStreamWriter;
     import java.io.UnsupportedEncodingException;
     import java.text.SimpleDateFormat;
     import java.util.Collection;
     import java.util.Date;
     import java.util.HashMap;
     import java.util.Locale;
     import java.util.Map;
     import java.lang.reflect.Method;
     import java.lang.reflect.Modifier;
     import java.net.HttpURLConnection;
     import java.net.URL;
     import org.json.JSONObject;
     import org.json.JSONArray;

    public class RestAPI {
    //url connection string to connect webservice
    private final String urlString = "http://localhost:4475/Handler1.ashx";

    private static String convertStreamToUTF8String(InputStream stream)
            throws IOException {
        String result = "";
          //build a new string
        StringBuilder sb = new StringBuilder();
        try {
            InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
            char[] buffer = new char[4096];
            int readedChars = 0;
            while (readedChars != -1) {
                readedChars = reader.read(buffer);
                if (readedChars > 0)
                    sb.append(buffer, 0, readedChars);
            }
            result = sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    private String load(String contents) throws IOException {
        //new urlString for connection
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(60000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
        w.write(contents);
        w.flush();
        InputStream istream = conn.getInputStream();
        String result = convertStreamToUTF8String(istream);
        return result;
    }

    private Object mapObject(Object o) {
        Object finalValue = null;
        if (o.getClass() == String.class) {
            finalValue = o;
        } else if (Number.class.isInstance(o)) {
            finalValue = String.valueOf(o);
        } else if (Date.class.isInstance(o)) {
            //create date format
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss",
                    new Locale("en", "USA"));
            finalValue = sdf.format((Date) o);
        } else if (Collection.class.isInstance(o)) {
            Collection<?> col = (Collection<?>) o;
            JSONArray jarray = new JSONArray();
            for (Object item : col) {
                jarray.put(mapObject(item));
            }
            finalValue = jarray;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            Method[] methods = o.getClass().getMethods();
            for (Method method : methods) {
                if (method.getDeclaringClass() == o.getClass()
                        && method.getModifiers() == Modifier.PUBLIC
                        && method.getName().startsWith("get")) {
                    String key = method.getName().substring(3);
                    try {
                        Object obj = method.invoke(o, null);
                        Object value = mapObject(obj);
                        map.put(key, value);
                        finalValue = new JSONObject(map);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return finalValue;
    }
    //Creating new account
    public JSONObject CreateNewAccount(String firstName, String lastName,
            String userName, String password) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface", "RestAPI");
        o.put("method", "CreateNewAccount");
        //add-in for new user details
        p.put("firstName", mapObject(firstName));
        p.put("lastName", mapObject(lastName));
        p.put("userName", mapObject(userName));
        p.put("password", mapObject(password));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }
     //getting the user details 
    public JSONObject GetUserDetails(String userName) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface", "RestAPI");
        o.put("method", "GetUserDetails");
        p.put("userName", mapObject(userName));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }
    //using username and pw for authentucation
    public JSONObject UserAuthentication(String userName, String passsword)
            throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface", "RestAPI");
        //UserAuthentication method using json object
        o.put("method", "UserAuthentication");
        p.put("userName", mapObject(userName));
        p.put("passsword", mapObject(passsword));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }
    //get the Dept. information
    public JSONObject GetDepartmentDetails() throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface", "RestAPI");
        o.put("method", "GetDepartmentDetails");
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }}

我的主要活动

      package com.ezchart.restfulapiclient;


      import android.app.Activity;
      import android.content.Intent;
      import android.os.Bundle;
      import android.view.Menu;
      import android.view.View;
      import android.view.MenuItem;
      import android.widget.AdapterView;
      import android.widget.ArrayAdapter;
      import android.widget.ListView;

    public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Display three main feature on the screen
        String listItem []={"Login","Create User Account","Department  Details"};
        ListView lvMain=(ListView)findViewById(R.id.lv_main);
        lvMain.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItem));

        lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                  @Override
                  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                              long arg3) {

                        if(arg2==0)
                        {
                              Intent i=new Intent(MainActivity.this,LoginActivity.class);
                              startActivity(i);
                        }
                        else if(arg2==1)
                        {
                              Intent i=new Intent(MainActivity.this,CreateUserActivity.class);
                              startActivity(i);
                        }
                        else if(arg2==2)
                        {
                              Intent i=new Intent(MainActivity.this,DeptActivity.class);
                              startActivity(i);
                        }
                  }
            });

    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Android Manifest.xml

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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".LoginActivity"
            android:label="@string/title_activity_login"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.ezchart.restfulapiclient.MainActivity" />
        </activity>
        <activity
            android:name=".UserDetailsActivity"
            android:label="@string/title_activity_user_details"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.ezchart.restfulapiclient.MainActivity" />
        </activity>
        <activity
            android:name=".CreateUserActivity"
            android:label="@string/title_activity_create_user"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.ezchart.restfulapiclient.MainActivity" />
        </activity>
        <activity
            android:name=".DeptActivity"
            android:label="@string/title_activity_dept"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.ezchart.restfulapiclient.MainActivity" />
        </activity>
    </application>

</manifest>

activity_main.xml中

<RelativeLayout 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: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" >

    <ListView
        android:id="@+id/lv_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

DeptActivity.java

package com.ezchart.restfulapiclient;


import java.util.ArrayList;

import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class DeptActivity extends Activity {

    ArrayAdapter<String> adapter;
    ListView listv;
    Context context;
    ArrayList<String> data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dept);
        // Show the Up button in the action bar.
        setupActionBar();

        data = new ArrayList<String>();
        listv = (ListView) findViewById(R.id.lv_dept);
        context = this;

        adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, data);
        listv.setAdapter(adapter);
        Toast.makeText(this,"Loading Please Wait..",Toast.LENGTH_SHORT).show();
        new AsyncLoadDeptDetails().execute();
    }

    protected class AsyncLoadDeptDetails extends
    AsyncTask<Void, JSONObject, ArrayList<DeptTable>> {
ArrayList<DeptTable> deptTable = null;

@Override
protected ArrayList<DeptTable> doInBackground(Void... params) {
    // TODO Auto-generated method stub

    RestAPI api = new RestAPI();
    try {

          JSONObject jsonObj = api.GetDepartmentDetails();

          JSONParser parser = new JSONParser();

          deptTable = parser.parseDepartment(jsonObj);

    } catch (Exception e) {
          // TODO Auto-generated catch block
          Log.d("AsyncLoadDeptDetails", e.getMessage());

    }

    return deptTable;
}

@Override
protected void onPostExecute(ArrayList<DeptTable> result) {
    // TODO Auto-generated method stub

    for (int i = 0; i < result.size(); i++) {
          data.add(result.get(i).getNo() + " " + result.get(i).getName());
    }

    adapter.notifyDataSetChanged();

    Toast.makeText(context,"Loading Completed",Toast.LENGTH_SHORT).show();
}

}

/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    getActionBar().setDisplayHomeAsUpEnabled(true);
}
}

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

我的logcat

12-31 01:36:14.463: E/AndroidRuntime(2465): FATAL EXCEPTION: main
12-31 01:36:14.463: E/AndroidRuntime(2465): Process: com.ezchart.restfulapiclient, PID: 2465
12-31 01:36:14.463: E/AndroidRuntime(2465): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ezchart.restfulapiclient/com.ezchart.restfulapiclient.DeptActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.ActivityThread.-wrap11(ActivityThread.java)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.os.Looper.loop(Looper.java:148)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.ActivityThread.main(ActivityThread.java:5417)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at java.lang.reflect.Method.invoke(Native Method)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
12-31 01:36:14.463: E/AndroidRuntime(2465): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
12-31 01:36:14.463: E/AndroidRuntime(2465):     at com.ezchart.restfulapiclient.DeptActivity.setupActionBar(DeptActivity.java:95)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at com.ezchart.restfulapiclient.DeptActivity.onCreate(DeptActivity.java:35)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.Activity.performCreate(Activity.java:6237)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
12-31 01:36:14.463: E/AndroidRuntime(2465):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
12-31 01:36:14.463: E/AndroidRuntime(2465):     ... 9 more

当我运行应用程序时,我发现上面的错误。 我认为这是因为urlString问题但不太确定。 请帮我看看并给出一些建议。 谢谢。

0 个答案:

没有答案