【问题标题】:logcat error android studio programming fragmentslogcat报错android studio编程片段
【发布时间】:2016-07-26 06:20:54
【问题描述】:

我的片段类正在解析 json 文件中的信息。但因为这首先是一个活动,这是我第一次尝试把它变成一个片段。

我的片段类:

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);
    }

}

当我单击应用程序上的选项时应用程序崩溃时会发生这种情况。 有什么建议可以解决这个问题吗?

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)

【问题讨论】:

    标签: java android android-fragments android-studio android-activity


    【解决方案1】:

    这是一个 NPE,因为您在 onCreateView() 中的 rootView 是本地对象:

        @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;
    }
    

    【讨论】:

    • 因为看不懂所以详细说明
    • onCreateView() 方法中的 rootView 对象是本地 java 对象。在 onPreExecute() 方法中,您尝试访问从未初始化过的全局对象 rootView...
    • 我们可以在聊天中讨论这个吗?
    • 你能打开一个吗
    • 仅在此处继续.. 一旦达到限制自动它会要求聊天光盘..
    【解决方案2】:

    使用

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

    在 GetMethodEx() 的 onPostExecute() 中。

    【讨论】:

      【解决方案3】:

      您可以在 onCreateView 中找到viewById,而不是在 onPreExecute 中使用,因为您的 View 对象不是全局声明的。

      试试这段代码:

      @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;}
      

      【讨论】:

        【解决方案4】:

        findViewById 不适用于片段。您需要执行以下操作

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

        【讨论】:

        • @johnab 您想讨论什么?发表您的问题
        猜你喜欢
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多