简体   繁体   English

Android()上的Null指针异常

[英]Null pointer exception on create() Android

I have a method that I use to recieve some information. 我有一种方法可以用来接收一些信息。 I send to this method one string (the server direction), and two strings that contains the user and the password, and I recieve an String[] with all the information, but I have a NullPointerException at 我向该方法发送一个字符串(服务器方向),以及两个包含用户和密码的字符串,并且我收到了一个包含所有信息的String [],但是我有一个NullPointerException

values = request("http://myIp/XXX/post.php?request=1", user, password);

line. 线。 The complete code is the next: 完整的代码如下:

String[] values;

@SuppressLint("InlinedApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
    setContentView(R.layout.activity_select_environment);   

    myBundle = getIntent().getExtras();

    user = myBundle.getString("user");
    password = myBundle.getString("password");

    values = request("http://myIp/XXX/post.php?request=1", user, password);  

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, android.R.id.text1, values);
}

The method is the next: 该方法是下一个:

@SuppressWarnings("null")
public String[] request(String requesturl, String user, String password)
{
    String result[] = null; 

    try
    {
        HttpClient httpclient = new DefaultHttpClient(); 

        HttpPost httppost = new HttpPost(requesturl);

        String results = "";

        //Varibles POST
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("user", user));
        nameValuePairs.add(new BasicNameValuePair("password", password));                        

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        response.getAllHeaders();
        response.getEntity();
        result[0] = "";                                                                         
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
            results = EntityUtils.toString(response.getEntity());           
            if(!results.equals("-1"))
            {
                JSONObject jsonResponse = new JSONObject(results);

                JSONArray jsonMainNode = jsonResponse.optJSONArray("edificios");

                int lengthJsonArr =jsonMainNode.length();
                for(int i = 0; i < lengthJsonArr; i++)
                {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);   
                    result[i] = jsonChildNode.optString("nombre"); 
                }
            }                 
        }

        return result;
    }
    catch(Exception ex)
    {
        result[0] = "error";
        return result;
    }
}  

I recieved a NullPointerException on the "values=request("....");" 我在“ values = request(” ....“);”上收到NullPointerException line and I don't know why, because user and password have values and the other value is a string... What could be do? 行,我不知道为什么,因为用户名和密码都有值,而另一个值是字符串...该怎么办?

You have declared your result String array but did not initialize it. 您已经声明了result String数组,但尚未初始化它。

Try this: 尝试这个:

@SuppressWarnings("null")
public String[] request(String requesturl, String user, String password)
{
    String result[] = new String[ <Insert value> ];
    // Code...
}

Let me explain further to avoid downvotes. 让我进一步解释以避免投票不足。 This is why I think this: 这就是为什么我这样认为:

You first initialize the array to null, so it can't be used yet. 您首先将数组初始化为null,因此尚无法使用。 Further down the line you have this statement String results = "" but your array is still null . 在此行的最下方,您可以看到以下语句String results = ""但您的数组仍为null Then you do this result[0] = "" , oh dear. 然后,您要执行此result[0] = "" ,亲爱的。 That is where the nullPointerException comes from, I think. 我认为那是nullPointerException来源。

You have to initialize your array and you are right if you say that you need to know the size of your array up front. 您必须初始化数组,如果您说需要先了解数组的大小,那是对的。 Use the maximum value you expect for the size or, better yet, use a list and not an array . 使用您期望的最大值作为大小,或者最好使用list而不是array

Here is a nice source for the list datastructure: List in Android Development . 这是list结构的一个很好的来源: Android Development中的List

There is also a nice discussion about list versus arrays here , it is for C# but the principles remain more or less the same. 还有约一个很好的讨论listarrays 在这里 ,它是C#,但原则仍然或多或少相同。

You got the exception because you are trying to access the first element of the result , which is not even initialized. You got the exception because you are trying to access the first element of the , which is not even initialized.

So you need to initialize the array first and then use it 因此,您需要先初始化数组,然后再使用它

result = new String[<some size>];

If size of the array is not know in advance, then ArrayList can be a option for you. 如果事先不知道数组的大小,则可以使用ArrayList

ArrayList<String> result = new ArrayList<>();

usage 用法

result.add(<some string value>);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM