简体   繁体   English

清单 <Class> 变量即使分配了值也返回null

[英]List<Class> variable returns null even when assigned a value

I have a java code file, 我有一个Java代码文件,

public class PropertyRequestService {

static String result;
PropertiesList localProperty = new PropertiesList();
List<PropertiesList> Properties;


public List<PropertiesList> getAllPropertiesStuff() {
    JSONArray json = null;
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "Given URL");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs
                .add(Passing parameter));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(httppost);

        // HttpEntity entity = response.getEntity();
        // if (entity != null) {

        /*
         * result = EntityUtils.toString(entity); Log.i("RESPONSE=",
         * result);
         */
        // List<PropertiesList> tst=(List<PropertiesList>)response;

        ArrayList<String> jsonstring = getJSONString(response);

        System.out.println("jsonString : " + jsonstring);
        json = new JSONArray(jsonstring);       

        localProperty.angle=30;
            localProperty.PropertyID =Integer.parseInt(json.getString(0));
            localProperty.Latitude =Double.parseDouble(json.getString(2));
            localProperty.Longitude = Double.parseDouble(json.getString(3));
            localProperty.PropertyPrice = Integer.parseInt(json.getString(4));
            localProperty.PropertyAddress = json.getString(1);
            localProperty.listfrom=0;

            Properties.add(localProperty);


    } catch (Exception e1) {
        e1.printStackTrace();
    }

    return Properties;
}

public ArrayList<String> getJSONString(HttpResponse response) {

    try {
        HttpEntity entity = response.getEntity();

        String result = EntityUtils.toString(entity);
        InputStream stream = new ByteArrayInputStream((result.replace("&",
                " ")).getBytes("UTF-8"));
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();

        Document doc = builder.parse(stream);

        NodeList n1 = doc.getElementsByTagName("PropertyID");
        NodeList n2 = doc.getElementsByTagName("Address");
        NodeList n3 = doc.getElementsByTagName("Lat");
        NodeList n4 = doc.getElementsByTagName("Lng");
        NodeList n5 = doc.getElementsByTagName("Price");
        Node nn1 = n1.item(0);
        Node nn2 = n2.item(0);
        Node nn3 = n3.item(0);
        Node nn4 = n4.item(0);
        Node nn5 = n5.item(0);
        String str1 = nn1.getFirstChild().getNodeValue();
        String str2 = nn2.getFirstChild().getNodeValue();
        String str3 = nn3.getFirstChild().getNodeValue();
        String str4 = nn4.getFirstChild().getNodeValue();
        String str5 = nn5.getFirstChild().getNodeValue();

        ArrayList<String> nodes = new ArrayList<String>();
        nodes.add(str1);
        nodes.add(str2);
        nodes.add(str3);
        nodes.add(str4);
        nodes.add(str5);

        System.out.println("Node value : " + nodes);
        return nodes;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

}

and PropertiesList class, 和PropertiesList类,

public class PropertiesList {

 public int angle;
 public int PropertyID;
 public int PropertyPrice;
 public String PropertyAddress;
 public Double Latitude;
 public Double Longitude;
 public static int listfrom;
}

and from the activity class I call like this, 从活动类中我这样称呼我

   PropertyRequestService properties=new PropertyRequestService();
    propertyRSList=  properties.getAllPropertiesStuff();

The problem is that, near the line "Properties.add(localProperty);", I did observe that Properties variable is null and Exception is caught. 问题是,在“ Properties.add(localProperty);”行附近,我确实观察到Properties变量为null并捕获了Exception。 There is no syntax error or logical error according to me. 据我说,没有语法错误或逻辑错误。 Did I miss anything or any wrong assignment? 我错过了什么吗?

This is my logcat, 这是我的logcat,

05-22 17:51:46.192: W/dalvikvm(3317): threadid=1: thread exiting with uncaught exception (group=0x40018578)
05-22 17:51:46.684: E/AndroidRuntime(3317): FATAL EXCEPTION: main
05-22 17:51:46.684: E/AndroidRuntime(3317): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.BuildersUpdate/com.BuildersUpdate.PropertySearchTypes.CameraSearch}: java.lang.NullPointerException
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.os.Looper.loop(Looper.java:130)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.app.ActivityThread.main(ActivityThread.java:3687)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at java.lang.reflect.Method.invokeNative(Native Method)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at java.lang.reflect.Method.invoke(Method.java:507)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at dalvik.system.NativeStart.main(Native Method)
05-22 17:51:46.684: E/AndroidRuntime(3317): Caused by: java.lang.NullPointerException
05-22 17:51:46.684: E/AndroidRuntime(3317):     at com.BuildersUpdate.PropertySearchTypes.PropertyRequestService.getAllPropertiesStuff(PropertyRequestService.java:90)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at com.BuildersUpdate.PropertySearchTypes.CameraSearch.onCreate(CameraSearch.java:200)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-22 17:51:46.684: E/AndroidRuntime(3317):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

Please suggest me and correct me!! 请建议我,并纠正我!! Thanks in advance!! 提前致谢!!

You need to instantiate Properties before you access it. 您需要实例化Properties然后才能访问它。 Use: 采用:

List<PropertiesList> Properties = new ArrayList<>();

instead of: 代替:

List<PropertiesList> Properties;

BTW, according to java naming conventions, variables should start with lower case letter, so it is better to use properties instead. 顺便说一句,根据Java命名约定,变量应以小写字母开头,因此最好使用properties

You have not initialized the List<Properties> Properties . 您尚未初始化List<Properties> Properties You have just created a reference to it. 您刚刚创建了对它的引用。

List<Properties> Properties = new ArrayList<Properties>();

You have just defined a reference Properties which will point to object of type ArrayList. 您刚刚定义了一个引用属性 ,该属性将指向ArrayList类型的对象。 You also need to create the actual object using the new() operator. 您还需要使用new()运算符创建实际的对象。

List<PropertiesList> Properties = new ArrayList<>();

Then you can add your data in it. 然后,您可以在其中添加数据。

Properties.add(localProperty);

Take care of your namings . 照顾好你的名字 Variable,functions must be in camel case ie starts with a small letter and subsequent words start with capital letter. 可变功能必须为驼峰式,即以小写字母开头,随后的单词以大写字母开头。 Words starting with caps are generally names of classes. 以大写字母开头的单词通常是类的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 数组中的自定义类变量返回null - custom class variable returns null when in array Hashmap get(key)即使存在该值也返回null - Hashmap get(key) returns null even when the value is present 变量始终为true,即使稍后分配? - Variable is always true even when assigned later? 在JAVA的子类中分配值时,主类中的主类属性为null - Main class property is null in main class when value is assigned in sub class in JAVA 是否可以为值分配或与值类型变量进行比较? - Can null be assigned to or be compared to a value type variable? 输入数据为空,即使已将值分配给元素 - input data is null even thought value is assigned to element 可以将WHat值分配给此类的变量 - WHat value can be assigned to this class's variable 在数据竞争期间,线程是否可以读取volatile变量的初始空值? 特别是在构造函数中为它赋给非null值时? - During a data race can a thread ever read initial null value of volatile variable? especially when a non null value is assigned to it in constructor? Spring @Value 返回 Null 在 Class 实现时 @Configuration - Spring @Value Returns Null On Class Implementation When @Configuration 即使模拟了列表中的对象,Junit测试列表也将返回null - Junit test list returns null even when objects inside the list have been mocked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM