得到错误java.lang.NullPointerException ............ [英] getting error as java.lang.NullPointerException............

查看:139
本文介绍了得到错误java.lang.NullPointerException ............的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我更喜欢Android(java)我只是开发一个简单的应用程序,它将调用webservice(Json Webservice)并绑定数据到android:listview。



i创建和JSON webservice并测试它是完美无缺的。



在android中,当我给它的URL并执行程序意味着它显示错误为

在com.example.cargo.MainActivity $ JSONParse中获取java.lang.NullPointerException错误。 onPostExecute(MainActivity.java:113)


第113行的


 Cargo = json.getJSONArray(TAG_Track ); 





不知道出了什么问题。过去4天我遇到了这个问题。

这是我的MainActivity代码:



 package com.example.cargo; 


import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
// import learn2crack.listview.library.JSONParser;

公共类MainActivity扩展Activity {
ListView listView1;
TextView textView1;
// TextView名称;
// TextView api;
按钮按钮1;
ArrayList< HashMap< String,String>> Track = new ArrayList< HashMap< String,String>>();

//获取JSON数组的URL
private static String url =http://192.168.1.126/testing/CService.asmx;

// JSON节点名称
private static final String TAG_Track =Track;
private static final String TAG_Status =Status;

JSONArray Cargo = null;

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

setContentView(R.layout.activity_main);
Track = new ArrayList< HashMap< String,String>>();
button1 =(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view){
new JSONParse()。execute();
}
});
}

私有类JSONParse扩展AsyncTask< String,String,JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute(){
super.onPreExecute();
textView1 =(TextView)findViewById(R.id.textView1);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(获取数据......);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String ... args){

JSONParser jParser = new JSONParser();

//从URL获取JSON
JSONObject json = jParser.getJSONFromUrl(url);
返回json;
}
@Override
protected void onPostExecute(JSONObject json){
pDialog.dismiss();
try {
//从URL获取JSON数组

Cargo = json.getJSONArray(TAG_Track);
for(int i = 0; i< Cargo.length(); i ++){
JSONObject c = Cargo.getJSONObject(i);

//将JSON项存储在变量
String Status = c.getString(TAG_Status);
// String name = c.getString(TAG_NAME);

//添加值HashMap key => value

HashMap< String,String> map = new HashMap< String,String>();
map.put(TAG_Status,Status);
Track.add(地图);
listView1 =(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this,Track,
R.layout.listview,
new String [] {TAG_Status},new int [] {
R.id .textView1});

listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent,View view,
int position,long id){
Toast.makeText(MainActivity.this,You Clicked at+ Track.get(+ position).get(Status),Toast.LENGTH_SHORT)。show();
}
});
}
} catch(JSONException e){
e.printStackTrace();
}
}
}
}







这里是我的json解析器代码:



 package com.example.cargo; 




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json =;

//构造函数
public JSONParser(){

}

public String getJSONString(HttpResponse response){

try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()。newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(response.getEntity()。getContent());
NodeList nl = doc.getElementsByTagName(string);
节点n = nl.item(0);
String str = n.getFirstChild()。getNodeValue();
System.out.println(节点值:+ str);
return str;
} catch(ParserConfigurationException e){
e.printStackTrace();
} catch(SAXException e){
e.printStackTrace();
} catch(IllegalStateException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
返回null;
}
public JSONObject getJSONFromUrl(String url){

//发出HTTP请求
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
是= httpEntity.getContent();

} catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is,iso-8859-1),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine())!= null){
sb.append(line);
}
is.close();

json = sb.toString()。substring(0,sb.toString()。length() - 1);
} catch(例外e){
Log.e(缓冲区错误,转换结果错误+ e.toString());
}

//尝试将字符串解析为JSON对象
try {
// JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
jObj = new JSONObject(json);
} catch(JSONException e){
Log.e(JSON Parser,解析数据时出错+ e.toString());
}

//返回JSON字符串
返回jObj;

}
}





可以任何一次请帮助我。



提前致谢

解决方案

JSONParse.onPostExecute(MainActivity.java:113)


113行中的


 Cargo = json.getJSONArray(TAG_Track); 





不知道出了什么问题。过去4天我遇到了这个问题。

这是我的MainActivity代码:



 package com.example.cargo; 


import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
// import learn2crack.listview.library.JSONParser;

公共类MainActivity扩展Activity {
ListView listView1;
TextView textView1;
// TextView名称;
// TextView api;
按钮按钮1;
ArrayList< HashMap< String,String>> Track = new ArrayList< HashMap< String,String>>();

//获取JSON数组的URL
private static String url =http://192.168.1.126/testing/CService.asmx;

// JSON节点名称
private static final String TAG_Track =Track;
private static final String TAG_Status =Status;

JSONArray Cargo = null;

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

setContentView(R.layout.activity_main);
Track = new ArrayList< HashMap< String,String>>();
button1 =(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view){
new JSONParse()。execute();
}
});
}

私有类JSONParse扩展AsyncTask< String,String,JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute(){
super.onPreExecute();
textView1 =(TextView)findViewById(R.id.textView1);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(获取数据......);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String ... args){

JSONParser jParser = new JSONParser();

//从URL获取JSON
JSONObject json = jParser.getJSONFromUrl(url);
返回json;
}
@Override
protected void onPostExecute(JSONObject json){
pDialog.dismiss();
try {
//从URL获取JSON数组

Cargo = json.getJSONArray(TAG_Track);
for(int i = 0; i< Cargo.length(); i ++){
JSONObject c = Cargo.getJSONObject(i);

//将JSON项存储在变量
String Status = c.getString(TAG_Status);
// String name = c.getString(TAG_NAME);

//添加值HashMap key => value

HashMap< String,String> map = new HashMap< String,String>();
map.put(TAG_Status,Status);
Track.add(地图);
listView1 =(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this,Track,
R.layout.listview,
new String [] {TAG_Status},new int [] {
R.id .textView1});

listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent,View view,
int position,long id){
Toast.makeText(MainActivity.this,You Clicked at+ Track.get(+ position).get(Status),Toast.LENGTH_SHORT)。show();
}
});
}
} catch(JSONException e){
e.printStackTrace();
}
}
}
}







这里是我的json解析器代码:



 package com.example.cargo; 




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json =;

//构造函数
public JSONParser(){

}

public String getJSONString(HttpResponse response){

try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()。newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(response.getEntity()。getContent());
NodeList nl = doc.getElementsByTagName(string);
节点n = nl.item(0);
String str = n.getFirstChild()。getNodeValue();
System.out.println(节点值:+ str);
return str;
} catch(ParserConfigurationException e){
e.printStackTrace();
} catch(SAXException e){
e.printStackTrace();
} catch(IllegalStateException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
返回null;
}
public JSONObject getJSONFromUrl(String url){

//发出HTTP请求
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
是= httpEntity.getContent();

} catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is,iso-8859-1),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine())!= null){
sb.append(line);
}
is.close();

json = sb.toString()。substring(0,sb.toString()。length() - 1);
} catch(例外e){
Log.e(缓冲区错误,转换结果错误+ e.toString());
}

//尝试将字符串解析为JSON对象
try {
// JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
jObj = new JSONObject(json);
} catch(JSONException e){
Log.e(JSON Parser,解析数据时出错+ e.toString());
}

//返回JSON字符串
返回jObj;

}
}





可以任何一次请帮助我。



提前谢谢


假设您正在使用Eclipse(或其他开发工具),它允许您在模拟设备上运行代码时进行调试。



在:: doInBackground的最后一行粘贴一个断点,并确认此时有非空结果。



如果将null传递给postExecute,请查看:: getJSONFromUrl方法。

- 你在:: getContent调用的输入流中得到了什么吗?

- 如果没有检查服务器。它的事件日志中有什么东西吗?

- 如果你的是你的字符串制作者正在填充?



如果你正在使用Eclipse检查控制台输出看看是否有任何异常日志消息出现。



偏离主题,我对你在asynctask中使用UI元素(进度对话框)感到困扰。我的理解是asynctask旨在从UI任务卸载处理以防止它被阻止。因为看起来你正在使用listview来显示你的结果,所以我希望你不介意我建议一个基于下面项目的解决方案作为替代。



在Android ListView的列表空和忙指示之间切换

Hi,

I'm a frsher to Android(java) i'm just developing an simple apps that will call to webservice(Json Webservice) and bind the data to android:listview.

i created and JSON webservice and tested it was working flawlessly.

In android when i give its URL and execute the program means it showing the error as

getting error as java.lang.NullPointerException at com.example.cargo.MainActivity$JSONParse.onPostExecute(MainActivity.java:113)


in the line 113 which is

Cargo = json.getJSONArray(TAG_Track);



Dont know what was going wrong.I was stucking with this issues past 4 days.
here is my MainActivity code:

package com.example.cargo;


import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
//import learn2crack.listview.library.JSONParser;

		public class MainActivity extends Activity {
			ListView listView1;
			TextView textView1;
			//TextView name;
			//TextView api;
			Button button1;
			ArrayList<HashMap<String, String>> Track= new ArrayList<HashMap<String, String>>();
			
			//URL to get JSON Array
			private static String url = "http://192.168.1.126/testing/CService.asmx";
			
			//JSON Node Names 
			private static final String TAG_Track = "Track";
			private static final String TAG_Status = "Status";
			
			JSONArray Cargo = null;

			@Override
		    protected void onCreate(Bundle savedInstanceState) {
		        super.onCreate(savedInstanceState);
		      
		        setContentView(R.layout.activity_main);
		        Track = new ArrayList<HashMap<String, String>>();
		        button1 = (Button)findViewById(R.id.button1);
		        button1.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View view) {
				         new JSONParse().execute();
					}
				});
		    }

			private class JSONParse extends AsyncTask<String, String, JSONObject> {
		    	 private ProgressDialog pDialog;
		    	@Override
		        protected void onPreExecute() {
		            super.onPreExecute();
                  textView1 = (TextView)findViewById(R.id.textView1);
					pDialog = new ProgressDialog(MainActivity.this);
		            pDialog.setMessage("Getting Data ...");
		            pDialog.setIndeterminate(false);
		            pDialog.setCancelable(true);
		            pDialog.show();
		    	}
		    	@Override
		        protected JSONObject doInBackground(String... args) {
		    		
		    		JSONParser jParser = new JSONParser();

		    		// Getting JSON from URL
		    		JSONObject json = jParser.getJSONFromUrl(url);
		    		return json;
		    	}
		    	 @Override
		         protected void onPostExecute(JSONObject json) {
		    		 pDialog.dismiss();
		    		 try {
		    				// Getting JSON Array from URL
		    			 
		    				Cargo = json.getJSONArray(TAG_Track);
		    				for(int i = 0; i < Cargo.length(); i++){
		    				JSONObject c = Cargo.getJSONObject(i);
		    				
		    				// Storing  JSON item in a Variable
		    				String Status = c.getString(TAG_Status);
		    				//String name = c.getString(TAG_NAME);
		    			
		    			// Adding value HashMap key => value
		    				
		    				HashMap<String, String> map = new HashMap<String, String>();
		    				map.put(TAG_Status, Status);
		    				Track.add(map);
		    				listView1=(ListView)findViewById(R.id.listView1);
		    				ListAdapter adapter = new SimpleAdapter(MainActivity.this, Track,
		    						R.layout.listview,
		    						new String[] { TAG_Status }, new int[] {
		    								R.id.textView1});

		    				listView1.setAdapter(adapter);
		    				listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		    		            @Override
		    		            public void onItemClick(AdapterView<?> parent, View view,
		    		                                    int position, long id) {
		    		                Toast.makeText(MainActivity.this, "You Clicked at "+Track.get(+position).get("Status"), Toast.LENGTH_SHORT).show();
		    		            }
		    		        });
		    				}
		    		} catch (JSONException e) {
		    			e.printStackTrace();
		    		}
		    	 }
		    }
		}




and here is my json parser code:

package com.example.cargo;




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

	public String getJSONString(HttpResponse response) {

	    try {
	         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	       org.w3c.dom.Document doc = builder.parse(response.getEntity().getContent());
	         NodeList nl = doc.getElementsByTagName("string");
	         Node n = nl.item(0);
	         String str = n.getFirstChild().getNodeValue();
	         System.out.println("Node value : " + str);
	         return str;
	    } 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;
	}
	public JSONObject getJSONFromUrl(String url) {

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			 while ((line = reader.readLine()) != null) {
                 sb.append(line);
             }
             is.close();

             json = sb.toString().substring(0, sb.toString().length()-1);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			// JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
}



can any once please help me.

Thanks in advance

解决方案

JSONParse.onPostExecute(MainActivity.java:113)


in the line 113 which is

Cargo = json.getJSONArray(TAG_Track);



Dont know what was going wrong.I was stucking with this issues past 4 days.
here is my MainActivity code:

package com.example.cargo;


import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
//import learn2crack.listview.library.JSONParser;

		public class MainActivity extends Activity {
			ListView listView1;
			TextView textView1;
			//TextView name;
			//TextView api;
			Button button1;
			ArrayList<HashMap<String, String>> Track= new ArrayList<HashMap<String, String>>();
			
			//URL to get JSON Array
			private static String url = "http://192.168.1.126/testing/CService.asmx";
			
			//JSON Node Names 
			private static final String TAG_Track = "Track";
			private static final String TAG_Status = "Status";
			
			JSONArray Cargo = null;

			@Override
		    protected void onCreate(Bundle savedInstanceState) {
		        super.onCreate(savedInstanceState);
		      
		        setContentView(R.layout.activity_main);
		        Track = new ArrayList<HashMap<String, String>>();
		        button1 = (Button)findViewById(R.id.button1);
		        button1.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View view) {
				         new JSONParse().execute();
					}
				});
		    }

			private class JSONParse extends AsyncTask<String, String, JSONObject> {
		    	 private ProgressDialog pDialog;
		    	@Override
		        protected void onPreExecute() {
		            super.onPreExecute();
                  textView1 = (TextView)findViewById(R.id.textView1);
					pDialog = new ProgressDialog(MainActivity.this);
		            pDialog.setMessage("Getting Data ...");
		            pDialog.setIndeterminate(false);
		            pDialog.setCancelable(true);
		            pDialog.show();
		    	}
		    	@Override
		        protected JSONObject doInBackground(String... args) {
		    		
		    		JSONParser jParser = new JSONParser();

		    		// Getting JSON from URL
		    		JSONObject json = jParser.getJSONFromUrl(url);
		    		return json;
		    	}
		    	 @Override
		         protected void onPostExecute(JSONObject json) {
		    		 pDialog.dismiss();
		    		 try {
		    				// Getting JSON Array from URL
		    			 
		    				Cargo = json.getJSONArray(TAG_Track);
		    				for(int i = 0; i < Cargo.length(); i++){
		    				JSONObject c = Cargo.getJSONObject(i);
		    				
		    				// Storing  JSON item in a Variable
		    				String Status = c.getString(TAG_Status);
		    				//String name = c.getString(TAG_NAME);
		    			
		    			// Adding value HashMap key => value
		    				
		    				HashMap<String, String> map = new HashMap<String, String>();
		    				map.put(TAG_Status, Status);
		    				Track.add(map);
		    				listView1=(ListView)findViewById(R.id.listView1);
		    				ListAdapter adapter = new SimpleAdapter(MainActivity.this, Track,
		    						R.layout.listview,
		    						new String[] { TAG_Status }, new int[] {
		    								R.id.textView1});

		    				listView1.setAdapter(adapter);
		    				listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		    		            @Override
		    		            public void onItemClick(AdapterView<?> parent, View view,
		    		                                    int position, long id) {
		    		                Toast.makeText(MainActivity.this, "You Clicked at "+Track.get(+position).get("Status"), Toast.LENGTH_SHORT).show();
		    		            }
		    		        });
		    				}
		    		} catch (JSONException e) {
		    			e.printStackTrace();
		    		}
		    	 }
		    }
		}




and here is my json parser code:

package com.example.cargo;




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

	public String getJSONString(HttpResponse response) {

	    try {
	         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	       org.w3c.dom.Document doc = builder.parse(response.getEntity().getContent());
	         NodeList nl = doc.getElementsByTagName("string");
	         Node n = nl.item(0);
	         String str = n.getFirstChild().getNodeValue();
	         System.out.println("Node value : " + str);
	         return str;
	    } 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;
	}
	public JSONObject getJSONFromUrl(String url) {

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			 while ((line = reader.readLine()) != null) {
                 sb.append(line);
             }
             is.close();

             json = sb.toString().substring(0, sb.toString().length()-1);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			// JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
}



can any once please help me.

Thanks in advance


Assuming you're using Eclipse (or a.n.other dev. tool) which lets you debug whilst running the code on an emulated device.

Stick a break-point on the last line of ::doInBackground and confirm that you have a non-null result at that point.

If null is being handed to the postExecute look at your ::getJSONFromUrl method.
- Are you getting anything back in the inputstream for the ::getContent call?
- If not check the server. Anything in its event logs?
- If you are is your stringbuilder being populated?

If you're using Eclipse check the console output to see if any your exception log messages appear.

Going off-topic, I'm troubled by your use of UI elements (progress dialog) in an asynctask. My understanding is that asynctask is designed to offload processing from the UI task to prevent it from being blocked. As it looks as though you're using a listview to display your results I hope you don't mind me suggesting a solution based on the item below as an alternative.

Switching between List Empty and Busy Indicators for Android ListView


这篇关于得到错误java.lang.NullPointerException ............的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆