简体   繁体   中英

logcat error android studio programming fragments

My fragment class is parsing information from a json file. but because this was an activity first and this is my first attempt to make this a fragment.

my Fragment class:

public class salahtimesparser extends Fragment {
    View rootView;
    TextView fajrTV;
    TextView zuhrTV;
    TextView asrTV;
    TextView maghribTV;
    TextView ishaTV;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_salahtimesparser, container, false);
        new GetMethodEx().execute("http://muslimsalat.com/11717/daily/4.json?key=ea4417ebf152c478082e1ff6a1a759d9");
        return rootView;}

    public class GetMethodEx  extends AsyncTask<String, Void, InputStream> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            fajrTV = (TextView) rootView.findViewById(R.id.fajr);
            zuhrTV = (TextView) rootView.findViewById(R.id.zuhr);
            asrTV = (TextView) rootView.findViewById(R.id.asr);
            maghribTV = (TextView) rootView.findViewById(R.id.maghrib);
            ishaTV = (TextView) rootView.findViewById(R.id.isha);
        }

        @Override
        protected InputStream doInBackground(String... params) {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(params[0]);
                HttpResponse response = client.execute(post);
                int status = response.getStatusLine().getStatusCode();
                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream in = entity.getContent();
                    return in;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(InputStream in) {
            super.onPostExecute(in);
            try {
                JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));

                String fajr = null;
                String zuhr = null;
                String asr = null;
                String maghrib = null;
                String isha = null;

                reader.beginObject();
                while (reader.hasNext()) {
                    String name = reader.nextName();
                    if (name.equals("items")) {
                        reader.beginArray();
                        while (reader.hasNext()) {
                            reader.beginObject();
                            while (reader.hasNext()) {
                                String innerName = reader.nextName();
                                final boolean isInnerNull = reader.peek() == JsonToken.NULL;
                                if (innerName.equals("fajr") && !isInnerNull) {
                                    fajr = reader.nextString();
                                } else if (innerName.equals("dhuhr") && !isInnerNull) {
                                    zuhr = reader.nextString();
                                } else if (innerName.equals("asr") && !isInnerNull) {
                                    asr = reader.nextString();
                                } else if (innerName.equals("maghrib") && !isInnerNull) {
                                    maghrib = reader.nextString();
                                } else if (innerName.equals("isha") && !isInnerNull) {
                                    isha = reader.nextString();
                                } else {
                                    reader.skipValue();
                                }
                            }
                            reader.endObject();
                        }
                        reader.endArray();
                    } else {
                        reader.skipValue();
                    }
                }
                reader.endObject();
                reader.close();

                fajrTV.setText(fajr);
                zuhrTV.setText(zuhr);
                asrTV.setText(asr);
                maghribTV.setText(maghrib);
                ishaTV.setText(isha);

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


    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getActivity().getMenuInflater().inflate(R.menu.main2, 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);
    }

}

This happens when the app crashes when i click the option on the application. any suggestions how to fix this?

Logcat:

    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View 
android.view.View.findViewById(int)' on a null object reference

  at com.kazam.salahtimes.salahtimesparser$GetMethodEx.onPreExecute(salahtimesparser.java:45)
  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
  at android.os.AsyncTask.execute(AsyncTask.java:535)
  at com.kazam.salahtimes.salahtimesparser.onCreateView(salahtimesparser.java:37)
  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:145)
  at android.app.ActivityThread.main(ActivityThread.java:5832)
  at java.lang.reflect.Method.invoke(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

This is an NPE because your rootView in onCreateView() is local object:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //don't declare again use the global object rootView  
        rootView = inflater.inflate(R.layout.fragment_salahtimesparser, container, false);
        new GetMethodEx().execute("http://muslimsalat.com/11717/daily/4.json?key=ea4417ebf152c478082e1ff6a1a759d9");
        return rootView;
}

findViewById does not work with fragments. you need to do something like below

ImageView imageView = (ImageView) getView().findViewById(R.id.foo);

You can findviewById in onCreateView instead using inside onPreExecute because your View object is not globally declared.

Try this piece of code:

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_salahtimesparser, container, false); fajrTV = (TextView) rootView.findViewById(R.id.fajr); zuhrTV = (TextView) rootView.findViewById(R.id.zuhr); asrTV = (TextView) rootView.findViewById(R.id.asr); maghribTV = (TextView) rootView.findViewById(R.id.maghrib); ishaTV = (TextView) rootView.findViewById(R.id.isha); new GetMethodEx().execute("http://muslimsalat.com/11717/daily/4.json?key=ea4417ebf152c478082e1ff6a1a759d9"); return rootView;}

Use

if(getView()!=null){
fajrTV.setText(fajr);
zuhrTV.setText(zuhr);
asrTV.setText(asr);
maghribTV.setText(maghrib);
ishaTV.setText(isha);
}

in onPostExecute() of GetMethodEx().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM