JSONArray jsonArray = new JSONArray(json) on a null object reference
Все работало в хостинге 000webhost.com, а когда переехал на fornex.com стал ссылаться на нуль. Ошибка:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
apply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
data.clear();
smylocate = msgmy;
ssendlocate = msgsend;
downloadJSON("http://z67202.hostde25.fornex.host/stock_service.php");
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
}
private void downloadJSON(final String urlWebService) {
class DownloadJSON extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] stocks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
// stocks[i] = " From: " +obj.getString("mylocate") + " To: " + obj.getString("sendlocate") + " Name: " + obj.getString("starttime") ;
String entermylocate=obj.getString("mylocate");
String entersendlocate=obj.getString("sendlocate");
if( (entermylocate.contains(smylocate) && entersendlocate.contains(ssendlocate)))
{
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("mylocate", "From: " + entermylocate);
datum.put("sendlocate","To: " + entersendlocate);
datum.put("three fields", "From: " + obj.getString("starttime") + " " +
"Until: " + obj.getString("endtime")+ " $=" + obj.getString("money") );
// datum.put("Forth Line",obj.getString("endtime"));
datum.put("id",obj.getString("id"));
datum.put("name",obj.getString("name"));
datum.put("email",obj.getString("email"));
data.add(datum);
}
}
if (data!=null) {
adapter = new SimpleAdapter(this, data,
R.layout.list_layout,
new String[]{"mylocate", "sendlocate", "three fields", "id", "name", "email"},
new int[]{R.id.txt1, R.id.txt2, R.id.txt3, R.id.txt4, R.id.txt5, R.id.txt6});
listView.setAdapter(adapter);
dialog.dismiss();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedid = ((TextView) view.findViewById(R.id.txt4)).getText().toString();
String selectedmylocate = ((TextView) view.findViewById(R.id.txt1)).getText().toString();
String selectedsendlocate = ((TextView) view.findViewById(R.id.txt2)).getText().toString();
String selectedname = ((TextView) view.findViewById(R.id.txt5)).getText().toString();
String selectedthrii = ((TextView) view.findViewById(R.id.txt3)).getText().toString();
String selectedemail = ((TextView) view.findViewById(R.id.txt6)).getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), selectedid, Toast.LENGTH_SHORT);
toast.show();
Intent userinfo = new Intent(MainActivity1.this,UserInfo.class);
userinfo.putExtra("mylocate", selectedmylocate);
userinfo.putExtra("sendlocate", selectedsendlocate);
userinfo.putExtra("name", selectedname);
userinfo.putExtra("three", selectedthrii+"#");
userinfo.putExtra("email", selectedemail);
userinfo.putExtra("id", selectedid);
startActivity(userinfo);
}
});
}
Ответы (2 шт):
Автор решения: Вася Воронцов
→ Ссылка
Строка, используемая для создания JSONArray, объявлена в методе doInBackground() класса AsyncTask и не видна нигде более. Кроме этого, Вы бы могли использовать sb.toString().trim(); для получения ответа, но этого не произошло. Предлагаю "оглобалить" переменную json. Например, так:
public class MainActivity1 extends Activity {
String json = "";
class DownloadJSON extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
};
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String myVar;
while ((myVar = bufferedReader.readLine()) != null) {
sb.append(myVar + "\n");
};
json = sb.toString().trim();
return json;
} catch (Exception e) {
return null;
};
};
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
};
};
};
/*Ваш код здесь*/
private void downloadJSON(final String urlWebService) {
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
};
}
Теперь в AsyncTask общая для всего MainActivity1 переменная json будет получать значение, и именно эта переменная со своим значением будет использоваться для для создания JSONArray.