N
N
newdancer2015-12-14 22:23:59
Java
newdancer, 2015-12-14 22:23:59

Need help with json? Falls out with an error why?

Need help with json? Falls out with an error!
Fragment where I'm trying to get data:

public class FilmFragment extends ListFragment
{
    public static final String ARG_FILM_NUMBER = "film_number";

    // Для загрузки контента
    private ProgressDialog pDialog;

    // Создаем JSON парсер объект
    JSONParser jParser = new JSONParser();

    // url to get all products list
    private static String url_all_films = "http://kinoobzor.org/android/get_all_cinema.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_FILM = "dle_post";
    private static final String TAG_PID = "pid";
    private static final String TAG_TITLE = "name";
    private static final String TAG_CATEGORY = "category";

    // products JSONArray
    JSONArray films = null;

    ArrayList<Cinema> cinemas = new ArrayList<Cinema>();
    CinemaAdapter cinemaAdapter;

    View rootView;
    Context ctx;
    Activity act;

    public FilmFragment() {
        // Для фрагмента требуется пустой конструктор
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_film, container, false);
        int id_cat = getArguments().getInt(ARG_FILM_NUMBER);

        // получаем названия категорий фильмов и выводим в левом меню
        String[] cat_film=getResources().getStringArray(R.array.category_film_array);
        getActivity().setTitle(cat_film[id_cat]);

        // генерируем данные для адаптера
        new LoadAllCinema().execute();
        return rootView;
    }

    // встроенный класс для загрузки данных в потоке
    class LoadAllCinema extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_films, "GET", params);

            // Check your log cat for JSON reponse
           // Log.d("All Cinemas: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    films = json.getJSONArray(TAG_FILM);

                    for (int i = 0; i <= films.length(); i++) {
                        JSONObject c = films.getJSONObject(i);

                        // получаем данные
                        String id = c.getString(TAG_PID);
                        String title = c.getString(TAG_TITLE);
                        String category = c.getString(TAG_CATEGORY);

                        cinemas.add(new Cinema(Integer.valueOf(id), title,category));
                    }
                } else {
                    // no products found
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            act.runOnUiThread(new Runnable() {
                public void run() {

                    // создаем адаптер
                    cinemaAdapter = new CinemaAdapter(getContext(), cinemas);

                    // настраиваем список
                    ListView lvMain = getListView();
                    lvMain.setAdapter(cinemaAdapter);
                }
            });

        }

    }
}

the application falls out with an error in the line
int success = json.getInt(TAG_SUCCESS);
itself error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
                                                                                  at net.kinomovies.movietrailers.FilmFragment$LoadAllCinema.doInBackground(FilmFragment.java:98)
                                                                                  at net.kinomovies.movietrailers.FilmFragment$LoadAllCinema.doInBackground(FilmFragment.java:75)
                                                                                  at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                                                  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                                  at java.lang.Thread.run(Thread.java:818

what's wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Burov, 2015-12-14
@BuriK666

https://jsonformatter.curiousconcept.com/
Unicode characters must be escaped with \u...

C
Curly Brace, 2015-12-14
@stasuss

well, obviously. json is not parsed)

N
newdancer, 2015-12-14
@newdancer

Andrey Burov : I didn't quite understand what exactly to delete. This is what the php file looks like:

<?php
 
$response = array();

require 'db_connect.php';
 
$db = new DB_CONNECT();

$result = mysql_query("SELECT *FROM dle_post ORDER BY id DESC") or die(mysql_error());
 
if (mysql_num_rows($result) > 0) {
    $response["dle_post"] = array();
 
    while ($row = mysql_fetch_array($result)) {
        $cinema = array();
        $cinema["pid"] = $row["id"];
        $cinema["title"] = $row["title"];
        $cinema["category"] = $row["category"];
        $cinema["short_story"] = $row["short_story"];
        /*$cinema["xfields"] = $row["xfields"];*/
    
    $masxfields = array();
    $masxfields2 = array();
    $masxfields3 = array();
    $namescr = "screens";
    $masxfields=split("\\|\\|", $row["xfields"], -1);
    for ($i = 1; $i < count($masxfields); $i++) 
    { 
      $masxfields2=split("\\|", $masxfields[$i], 2);
      if ($masxfields2[0] == $namescr)
      {
        preg_match_all("#src=[\"']([^\"']+)#", $masxfields2[1], $masxfields3);
        $cinema[$masxfields2[0]] = $masxfields3[1][0].", ".$masxfields3[1][1].", ".$masxfields3[1][2];
      }
      else
      {
        $cinema[$masxfields2[0]] = $masxfields2[1];
      }
    } 
        array_push($response["dle_post"], $cinema);
    }
    $response["success"] = 1;

  $datastr=json_encode($response, JSON_UNESCAPED_UNICODE);/*кодируем в utf-8*/
  /*$datastr=stripslashes($datastr);*//*убираем экранирование*/
  $datastr=strip_tags($datastr, '<img>');/*убираем теги кроме img*/

    echo $datastr;
} else {
    $response["success"] = 0;
    $response["message"] = "No cinema found";

    echo json_encode($response);
}
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question