Error searching blogger information via json

Asked

Viewed 40 times

2

I’m trying to get information from the blogger via json and put to appear in a recyclerview. But I’m not getting it. I’m a beginner in programming, so I’m unharmed if you have to sign any key so you can release the content by json.

Edit: Data is not being displayed.

Edit 2: It seems to find out what the problem is, but I still can’t solve it. Turns out what I want to get is not a Jsonarray:

JSONObject response = new JSONObject(result);
JSONArray version = response.optJSONArray("title");

It is a Jsonobject:

JSONObject response = new JSONObject(result);
JSONObject getTitle = response.getJSONObject("title");

Until then the app persisted in failed Toast, after this change no longer appears the message. However, nothing on the screen is still displayed.

This appears when I’m monitoring the progress of the app: W/System.err: org.json.Jsonexception: No value for title

Since "title" is really an object.

Code after the change:

private void parseResult(String result) {
        Log.d("Debug", result);
        try {
            JSONObject response = new JSONObject(result);
            JSONObject getTitle = response.getJSONObject("title");
            rowItems = new ArrayList<>();
            for (int i = 0; i < getTitle.length(); i++) {
                RowItem item = new RowItem();
                String put = getTitle.getString("$t");
                item.setTitle(put);
                rowItems.add(item);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }
    }
}

Here is the java code of my application.

Rowitem:

public class RowItem {

    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Adapter:

public class IAdapter extends RecyclerView.Adapter<IAdapter.CustomViewHolder> {

    private List<RowItem> listItems;
    private Context mContext;
    private OnItemClickListener onItemClickListener;

    public IAdapter(Context context, List<RowItem> listItems) {
        this.listItems = listItems;
        this.mContext = context;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.listar_apps, null);
        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
        final RowItem listItem = listItems.get(i);

        customViewHolder.applyTitle.setText(Html.fromHtml(listItem.getTitle()));

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemClickListener.onItemClick(listItem);
            }
        };
        customViewHolder.applyTitle.setOnClickListener(listener);
    }

    @Override
    public int getItemCount() {
        return (null != listItems ?
        listItems.size() : 0);
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {
        protected TextView applyTitle;

        public CustomViewHolder(View view) {
            super(view);
            this.applyTitle = (TextView) view.findViewById(R.id.titulo_app);
        }
    }

    public OnItemClickListener getOnItemClickListener() {
        return onItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}

Personal activity:

public class Creator extends AppCompatActivity {

    private RecyclerView recyclerView;
    private static final String TAG = "Creator";

    private List<RowItem> rowItems;
    private IAdapter adapter;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creator);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        String url = "http://techpositivo.blogspot.com/feeds/posts/default?alt=json";
        new GetData().execute(url);
    }

    public class GetData extends AsyncTask<String, Void, Integer> {
        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();

                //200 representa HTTP OK
                if (statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }

                    parseResult(response.toString());
                    result = 1; //Sucesso
                } else {
                    result = 0; //Falhou
                }
            } catch (Exception e){
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //Falhou
        }
        @Override
        protected void onPostExecute(Integer result) {
            if (result == 1) {
                adapter = new IAdapter(Creator.this, rowItems);
                recyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(RowItem item) {
                        Toast.makeText(Creator.this, item.getTitle(), Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Toast.makeText(Creator.this, "Falhou...", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray version = response.optJSONArray("title");
            rowItems = new ArrayList<>();
            for (int i = 0; i < version.length(); i++) {
                JSONObject title = version.optJSONObject(i);
                RowItem item = new RowItem();
                item.setTitle(title.optString("$t"));
                rowItems.add(item);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }
    }
}

Note: Do not notice my site in the desktop version, because my purpose is only for smartphones.

  • Isn’t it displaying? Is there an error? Which part is difficult?

  • @Thiagoluizdomacoski Yes. The data is not being shown.

  • what comes in your variable sponse?

  • @Thiagoluizdomacoski Repairing my code. Response loads all json text. It is then passed to the parseResult method to make the distribution.

  • I think the error is time to get the value in the method parseResult try to put in the first line of this method the following: Lod. d ("Debug", result); and see if it shows in the console the same q vc sees accessing the url

  • @Thiagoluizdomacoski Yes, Debug contained the same content when accessed by the link. But I seem to have an error below: D/Creator: Attempt to invoke virtual method 'int org.json.Jsonarray.lenght()' on a null Object Reference

  • Sponse.optJSONArray("title") does not exist! This is what the code means

  • @Thiagoluizdomacoski Accessing the link can you help me identify what values should I call to receive the name of each post, for example? I’m trying everything anyway, but I’m not getting it.

  • Sure! I can’t now, but as soon as possible put the answer

  • @Thiagoluizdomacoski Friend. Thank you very much for the layout. My question has been edited, I think with improvements (news). Look there, please.

Show 5 more comments

1 answer

2


The error occurs when browsing the properties of JSON

In this case, to have the title of the post’s you need to navigate in the following Objects:

feed > entry > title

In the title object we will have the property $t

Follow an example:

public class GetData extends AsyncTask<String, Void, Integer> {

    private List<String> titles = new ArrayList<>();
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            //200 representa HTTP OK
            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }

                parseResult(response.toString());
                result = 1; //Sucesso
            } else {
                result = 0; //Falhou
            }
        } catch (Exception e) {
            Log.d("TAG", e.getLocalizedMessage());
        }
        return result; //Falhou
    }

    @Override
    protected void onPostExecute(Integer result) {

        for(final String title : titles){

            RowItem item = new RowItem();
            item.setTitle(title.optString("$t"));
            rowItems.add(item);
        }

        adapter = new IAdapter(Creator.this, rowItems);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RowItem item) {
                Toast.makeText(Creator.this, item.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);

            // Pegamos o feed
            JSONObject feed = new  JSONObject(response.get("feed").toString());
            // Pegamos o  entry
            JSONArray entry =  feed.getJSONArray("entry");
            for (int i = 0; i < entry.length(); i++) {
                // Pegamos um item
                JSONObject post = entry.optJSONObject(i);
                // Pegamos o objeto title
                final JSONObject titleJson = new JSONObject(post.get("title").toString());
                //Pegamos o valor
                titles.add(titleJson.getString("$t"));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Observing: I created a list and added the titles, and only on onPostExecute, change the elements of the screen!

Suggestion: Instead of a list of String create an object with all the properties you see in the list of entry !

A tip to find out what these properties are is Log.i()

  • Absolutely. He worked quietly. Thank you very much. But now that I went to see, my site has more than 100 posts, and this link (json) lists few titles?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.