Произошла ошибка при поиске имени с помощью приложения, что не дает результатов при поиске имени в приложении.
Попытка переключения между JSONArray и JSONObject, но возникает аналогичная ошибка. URL-адрес правильный и показывает данные в формате JSON.
package com.rjassi.service;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class CharacterSearchService extends AbstractService {
private String query;
private JSONObject results;
private JSONObject jsonObject;
public CharacterSearchService(String query) {
try {
this.query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
}
public JSONObject getResults() {
return results;
}
//This method will run on a separate thread to the UI
@Override
public void run() {
URL url;
boolean error = false;
HttpsURLConnection httpsURLConnection = null;
StringBuilder result = new StringBuilder();
try {
url = new URL("https://www.moogleapi.com/api/v1/characters/search?name=" + query);
httpsURLConnection = (HttpsURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
//put the result string into a JSONObject
JSONArray jsonArray = jsonObject.getJSONArray("name");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) {
error = true;
} else {
results = jsonObject;
}
}
/*
If the JSONObject has a "Response" attribute and it equals false then
no results were found
if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) {
error = true;
} else {
results = jsonObject.getJSONArray("Search");
}
*/
} catch (Exception ex) {
ex.printStackTrace();
results = null;
error = true;
} finally {
if (httpsURLConnection != null) {
httpsURLConnection.disconnect();
}
}
/*
Call the serviceCallComplete() method in the super class; AbstractService which
will then inform the listeners that the search is complete
*/
super.serviceCallComplete(error);
}
}
public void serviceComplete(AbstractService abstractService) {
if (!abstractService.hasError()) {
//Cast the AbstractService object passed into the method to a CharacterSearchService object
CharacterSearchService characterSearchService = (CharacterSearchService) abstractService;
//Create a string array that is the same as the results JSONArray
String[] result = new String[characterSearchService.getResults().length()];
//searchResults.clear();
/*
Loops through the JSONArray and get the name of each JSONObject it contains.
Store each name in string array.
*/
for (int i = 0; i < characterSearchService.getResults().length(); i++) {
try {
//Store each character result as a JSONObject in the ArrayList
//searchResults.add(characterSearchService.getResults().getJSONObject(i));
android.util.Log.i("sdfsf", characterSearchService.getResults().getJSONObject(String.valueOf(i)).getString("name"));
result[i] = characterSearchService.getResults().getJSONObject(String.valueOf(i)).getString("name");
} catch (JSONException ex) {
result[i] = "error";
}
}
//Display the string array on screen in the ListView.
setListAdapter(new ArrayAdapter<String>(this, R.layout.final_fantasy_list_cell, R.id.text, result));
}
else{
String[] result = new String[]{"No Results"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.final_fantasy_list_cell, R.id.text, result));
}
}
Это ошибка, которая возникает после поиска имени:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.rjassi.service.CharacterSearchService.run(CharacterSearchService.java:53)
at java.lang.Thread.run(Thread.java:764)
В ожидаемом выводе должно отображаться имя, которое ищется путем возврата этого имени или аналогичных им. из результатов поиска API.