线 - > JSONArray jArray = new JSONArray(result);给出nullpointer异常

时间:2014-04-05 21:53:55

标签: java android eclipse

package com.example.fyptrialapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class SearchByName extends Activity{

    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream=null;
    Intent i;

    //public static final String recipes[]=new String[]{"Almond-Sheera","Bhel","Bread-Pizzas","Carrot-Pickle","Carrot-Relish"};
     String recipes[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_recipe);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        Button b2=(Button)findViewById(R.id.bSearchByName);

        try{

            httpclient = new DefaultHttpClient();
            httppost = new HttpPost("http://10.0.2.2/fypTrial2/searchByName.php");
            response = httpclient.execute(httppost);    // Execute HTTP Post Request
            inputStream = response.getEntity().getContent();
            String result=null;

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line=null;
            while((line=reader.readLine())!= null){
                sb.append(line+"\n");
            }

            inputStream.close();
            result=sb.toString();

            JSONArray jArray=new JSONArray(result);// this statment gives error

            for(int i=0;i<jArray.length();i++){
                JSONObject json=jArray.getJSONObject(i);
                recipes[i]=json.getString("name");
            }
        }
        catch(Exception e){

            Log.e("log_tag3", "Error convering result"+e.toString());

        }

        ArrayAdapter<String> ac=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,recipes);
            AutoCompleteTextView tv=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
            tv.setAdapter(ac);
        b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            Intent i=new Intent("com.example.practice.Search_Result");
            startActivity(i);
            }
        });     


    }   
}

错误

  

java.nullpointerexception。转换结果变量时出错。并且   致命的主要错误

如果我想使用ASnk任务,我该怎么写呢。

2 个答案:

答案 0 :(得分:0)

您确实应该将AsyncTask用于网络部分。对于AsyncTask的usasge,您的应用可能已经因为NetworkOnMainThread错误而跟随this link崩溃。

但是,除此之外,您提供的代码很少,以指出NullPointerException的原因。如果对象可能出现,则应始终检查对象是否为空。

try{
   //your code
}catch(NullPointerException ex){
   ex.printStackTrace();
}

答案 1 :(得分:0)

JSON语法永远不会以数组的形式启动。可能是它以{后跟[,但从不直接[]开始。这就是为什么尝试将结果转换为JSONArray将无法正常工作。你应该首先尝试获取对象,然后是数组元素。

JSONObject jo = new JSONObject(result);
JSONArray jArray = jo.getJSONArray("keyIdentifyer");

如果你没有数组键标识符,你可以尝试迭代或获取第一个元素。没有密钥时,请参阅迭代时的this post answear