0

Why is the return value is null

I'm trying to create something like a news feed using packages JSON but to no avail.

My code:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainFragment extends Fragment {

    private ListView songList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.main_layout, container, false);

        songList = (ListView)v.findViewById(R.id.listView_news);

        AsynDataClass jsonAsync = new AsynDataClass();

        jsonAsync.execute("");

        return v;
    }
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//
//// Inflate the menu; this adds items to the action bar if it is present.
//
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//
//        return true;
//
//    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

//noinspection SimplifiableIfStatement

        if (id == R.id.action_settings) {

            return true;

        }
        return super.onOptionsItemSelected(item);

    }

    private class AsynDataClass extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

// TODO Auto-generated method stub

            HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

            HttpPost httpPost = new HttpPost("http://192.168.1.3/song.json");

            String jsonResult = "";

            try {

                HttpResponse response = httpClient.execute(httpPost);

                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

                System.out.println("Returned Json object " + jsonResult.toString());

            } catch (ClientProtocolException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            } catch (IOException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            }

            return jsonResult;

        }

        @Override

        protected void onPreExecute() {

// TODO Auto-generated method stub

            super.onPreExecute();

        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            System.out.println("Resulted Value: " + result);

            List<ItemObject> parsedObject = returnParsedJsonObject(result);

            CustomAdapter jsonCustomAdapter = new CustomAdapter(getActivity(), parsedObject);

            songList.setAdapter(jsonCustomAdapter);

        }

        private StringBuilder inputStreamToString(InputStream is) {

            String rLine = "";

            StringBuilder answer = new StringBuilder();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            try {

                while ((rLine = br.readLine()) != null) {

                    answer.append(rLine);

                }

            } catch (IOException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            }

            return answer;

        }

    }

    private List<ItemObject> returnParsedJsonObject(String result){

        List<ItemObject> jsonObject = new ArrayList<ItemObject>();

        JSONObject resultObject = null;

        JSONArray jsonArray = null;

        ItemObject newItemObject = null;

        try {

            resultObject = new JSONObject(result);

            System.out.println("Testing the water " + resultObject.toString());

            jsonArray = resultObject.optJSONArray("African_Music");

        } catch (JSONException e) {

            e.printStackTrace();

        }
        if (jsonArray != null){
            for(int i = 0; i < jsonArray.length(); i++){

                JSONObject jsonChildNode = null;

                try {

                    jsonChildNode = jsonArray.getJSONObject(i);

                    String songName = jsonChildNode.getString("title");

                    String songYear = jsonChildNode.getString("title");

                    String songAuthor = jsonChildNode.getString("title");

                    String newLine = jsonChildNode.getString("_id");

                    newItemObject = new ItemObject(songName, songYear, songAuthor, newLine);

                    jsonObject.add(newItemObject);

                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }
        }

        return jsonObject;

    }

}

JSON packet: click


Gradle output:

06-27 14:59:09.260 22223-22223/ru.yktdevelopers.childrensofasia E/AndroidRuntime: FATAL EXCEPTION: main
Process: ru.yktdevelopers.childrensofasia, PID: 22223
java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at ru.yktdevelopers.childrensofasia.MainFragment.returnParsedJsonObject(MainFragment.java:198)
at ru.yktdevelopers.childrensofasia.MainFragment.access$100(MainFragment.java:30)
at ru.yktdevelopers.childrensofasia.MainFragment$AsynDataClass.onPostExecute(MainFragment.java:137)
at ru.yktdevelopers.childrensofasia.MainFragment$AsynDataClass.onPostExecute(MainFragment.java:81)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-27 14:59:38.079 22223-22230/ru.yktdevelopers.childrensofasia W/art: Suspending all threads took: 28.442ms
06-27 15:05:14.971 22223-22230/ru.yktdevelopers.childrensofasia E/art: Failed to send JDWP packet HPIF to debugger (-1 of 52): Broken pipe
06-27 15:05:14.971 22223-22230/ru.yktdevelopers.childrensofasia E/art: Failed sending reply to debugger: Broken pipe
06-27 15:05:15.020 22223-22230/ru.yktdevelopers.childrensofasia I/art: Debugger is no longer active
06-27 15:06:24.739 22223-22223/ru.yktdevelopers.childrensofasia I/Process: Sending signal. PID: 22223 SIG: 9

why the return value is converted to null

where did I go wrong? can not understand

Arjun saini
  • 4,223
  • 3
  • 23
  • 51

0 Answers0