This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am new to JSON. I need help. My android studio keeps on telling me that my jsonobject is NULL. I can parse and display my jsonarray into a listview. But when i click the page where i displayed it, my app crashes.
Parser
class BgTask extends AsyncTask<Void, Void, String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://10.0.2.2/result/hehe.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputstream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
}
}
public void publishGame(View view)
{
if(json_string == null)
{
Toast.makeText(getApplicationContext(), "Get Data First",Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(this, Games.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
}
code that posts
Bundle intent=getIntent().getExtras();
if(intent !=null) {
json_string = intent.getString("json_data");
json_string = getIntent().getExtras().getString("json_data");
}
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String team1, score1, team2, score2, Type;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
team1 = JO.getString("team1");
score1 = JO.getString("score1");
team2 = JO.getString("team2");
score2 = JO.getString("score2");
Type = JO.getString("Type");
Downloader downloader = new Downloader(team1, score1, team2, score2, Type);
gamesAdapter.add(downloader);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The error pointing is here try {
jsonObject = new JSONObject(json_string);
The error is because you are trying to parse "json_data" to JSONObject which is not a valid json. Perhaps you are having server response in a variable called json_data which is of String type if that is the case you need to pass that variable instead of passing String literal into JSONObject constructor.
Related
I have a problem with this Json file. I am trying to do a Parser that shows in a textview the results after a button is pressed. I wonna parse the "firstName" tag but to do this, I need to pass through the others tags like "league" and "standard". I don't know how to parse them in this Json file.
The Json file is structured like this:
{
"_internal":{
"pubDateTime":"2017-06-23 03:21:52.076",
"xslt":"xsl/league/roster/marty_active_players.xsl",
"eventName":"league_roster"
},
"league":{
"standard":[
{
"firstName":"Alex",
"lastName":"Abrines",
"personId":"203518",
"teamId":"1610612760 1610612760",
"jersey":"8",
"pos":"G-F",
"heightFeet":"6",
"heightInches":"6",
"heightMeters":"1.98",
"weightPounds":"190",
"weightKilograms":"86.2",
"dateOfBirthUTC":"1993-08-01",
"teams":[
{
"teamId":"1610612760",
"seasonStart":"2016",
"seasonEnd":"2016"
}
],
"draft":{
"teamId":"1610612760",
"pickNum":"32",
"roundNum":"2",
"seasonYear":"2013"
},
"nbaDebutYear":"2016",
"yearsPro":"0",
"collegeName":"",
"lastAffiliation":"Spain/Spain",
"country":"Spain"
},
This is my Java code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
String Players[] = new String[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btn);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("http://data.nba.net/10s/prod/v1/2016/players.json");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
JSONArray jsonArray = new JSONArray(DataPlayers);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
Wrong:
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
Correct:
JSONObject jsonObject = new JSONObject(result);
JsonObject objStandard = jsonObject.getJSONObject("league");
Now from objStandard object, you can retrieve the json array and iterate through the sub json objects.
JSONArray jsonArray = objStandard.getJSONArray("standard");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
2 cents suggestion :)
It seems you have just started exploring android development, saying based on you are using a legacy method of json parsing, I would suggest you to check out GSON library, which is a Java serialization/deserialization library to convert Java Objects into JSON and back. In short, you will not be needed to parse JSON response manually but rather you will be having normal java class objects and members/methods to deal with.
Your code should be like this
try {
String result = "your_json_string";
JSONObject jsonObject = new JSONObject(result);
JSONObject leagueObject = jsonObject.getJSONObject("league");
JSONArray standardArray = leagueObject.getJSONArray("standard");
for (int i = 0; i < standardArray.length(); i++) {
JSONObject standardObject = standardArray.getJSONObject(i);
String name = standardObject.getString("firstName");
}
} catch (Exception e) {
System.out.println(e);
}
I want to get images from server into my Android app.
My first steps are:
I have this JSON string array from server
{"results":"[{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara1.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara2.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara3.jpg\"}]"}
I got urls in my App from server with code below and working fine.
private void getURLs() {
class GetURLs extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(GalleryTargets.this, "Loading...", "Please Wait...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(GalleryTargets.this,s,Toast.LENGTH_LONG).show();
imageJSON = s;
Log.e(LOGTAG, "Succeed Read url" + imageJSON);
extractJSON(imageJSON);
}
#Override
protected String doInBackground(String... strings) {
String uri = strings[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json);
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetURLs gu = new GetURLs();
gu.execute(newurl);
}
But, i want to extract json into a new JSON Object with this method below but throws the exception, Json object not created.
Any ideas why this exception happens?
Thank you in advance!
private void extractJSON(String jsonString){
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jArray.length(); i++) {
JSONObject oneObject = jArray.getJSONObject(i);
oneObject.getString("url");//
}
Log.e(LOGTAG, "JsonArray Succeed" );
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOGTAG, "JsonArray exception");
}
}
Instead of JSONArray jArray = jsonObject.getJSONArray("results");
Try JSONArray jArray = new JSONArray (jsonObject.getString("results"));
You're asking for a json array but it is a string.
There is an error on the json.. after "results": there must not be
quotes
This is correct
{"results":[{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara1.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara2.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara3.jpg\"}]}
I keep on getting a null pointer exception error. I looked through my code and I am not sure why I am getting this error. I populates when i complile the program
The error reads like this
Null pointer Exception: Attempt to invoke virtual method int java.lang.String.length() on a null object reference. Thanks in advance.
EditText enterCity;
TextView weatherView;
public void onClick (View view) {
downloadAPIInfo task = new downloadAPIInfo();
String APIKEY = "b4fabae83c89c469d7a458a230b7a267";
String website = "http://api.openweathermap.org/data/2.5/weather?q=";
String url = website + enterCity.getText().toString() + APIKEY;
task.execute(url);
Log.i("User Entry", enterCity.getText().toString());
}
public class downloadAPIInfo extends AsyncTask<String, Void, String> {
URL url;
HttpURLConnection httpURLConnection = null;
String result = "";
#Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int data = reader.read();
while(data != -1) {
char one = (char) data;
result += one;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Onpostexecute interacts with the UI
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject object = new JSONObject(result);
String weatherInfo = object.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i = 0; i < array.length(); i++ ) {
JSONObject jsonPart = array.getJSONObject(i);
Log.i("main", jsonPart.getString("main"));
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != "") {
message+= main + ":" + description + "\r\n";
}
}
if(message != "") {
weatherView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Log.i("WebsiteContent", result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterCity = (EditText) findViewById(R.id.cityeditText);
weatherView = (TextView) findViewById(R.id.weathertextView);
}
}
The JSONArray named 'array' is null in your onPostExecute mehtod.
Most probably your weatherInfo string is null.
I suggest you post the full stacktrace for a better explanation.
i have create an android application on where the user can select the start and end point of the location.
This application will use the Google-Direction web service and make the HTTPRequest.
I will make this as short, I want to call the asynctask method in the JSONParser class from the main_activity.
The issue is, I don't know how to display the result in the main_activtiy method
here is the asynctask method
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
public JSONParser() {
}
public void getJSONFromUrl(final String url, final responseListener target) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection = null;
StringBuilder stringBuilder = new StringBuilder();
try {
httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = inputStreamReader.read(buff)) != -1) {
stringBuilder.append(buff, 0, read);
}
return stringBuilder.toString();
} catch (MalformedURLException localMalformedURLException) {
return "";
} catch (IOException localIOException) {
return "";
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
target.onResponseComplete(result);
}
}.execute();
}
here is how the main method is calling the method
new JSONParser().getJSONFromUrl(url, new responseListener() {
#Override
public void onResponseComplete(String response) {
try {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
JSONArray step = new JSONObject(response).getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
.getJSONObject(0).getJSONArray("steps");
for (int i = 0; i < step.length(); i++) {
HashMap<String,Object> row = new HashMap<String,Object>();
row.put("Distance", step.getJSONObject(i).getJSONObject("distance").getString("text"));
list.add(row);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
the issue right know is how i want to display the Arraylist List value and put it into the TextView call jarak
You can change your List to be
ArrayList<HashMap<String, String>>
as you are getting a string from
step.getJSONObject(i).getJSONObject("distance").getString("text")
To get it out you can use (assuming your textview is called jarak)
for(HashMap<String,String> map : list) {
for(Entry<String, String> entry : map.entrySet()) {
jarak.setText(entry.getKey() + ", " + entry.getValue());
}
}
Hope that helps
I am a beginner in Android, and I am writing a short program to download a JSON feed from URL and parse it. I use AsyncTask to do the downloading.
The doInBackground() part seems to work well. Then I set my breakpoint to onPostExecute(), it can even stop at parseJSON(result), and 'result' is showing the correct json string downloaded. But when I try to step into parseJSON(result), it will NOT step into the function correctly(either throw JSONException directly or go to some random lines within parseJSON(result)).
From DDMS log it's not showing any valuable information as well.
How might I find what the problem is? Is it because I used onPostExecute() incorrectly, or parseJSON() has some problem?
public class MainActivity extends Activity {
private listItem[] items;
public class listItem {
String title;
String description;
String imageHref;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new listItem[50];
new DownloadJsonFeed().execute("http://dl.dropbox.com/u/10168342/facts.json");
}
private class DownloadJsonFeed extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
return downloadUrl(params[0]);
} catch (IOException e) {
return "Unable to retrieve json feed. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
try {
parseJSON(result); // Here !!!!!!
} catch (JSONException e) {
}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
} finally {
if (is != null) {
is.close();
}
}
}
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = new JSONArray(rows);
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}
JSONObject.getString() will try to get String type value, but what you want is array type.
I think you didn't get the JSON array right. The json_obj.getString will give you an String instead an array.
Try to change as follows:
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = json_obj.getJSONArray("rows"); //<---- change this line
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}