Textview上的空指针异常

时间:2016-01-03 11:28:10

标签: android nullpointerexception textview

我可能会问一个愚蠢的问题,但这是在花了很多时间来解决这个问题。希望有人可以建议。

我收到错误

TitleTxt.setText("Title: " + title); 

TitleTxt为空。

package com.androidatc.customviewindrawer;

/**
 */
/**
 * Copyright (c) 2015 Android ATC.
 *
 * Author: Android ATC Training Team.
 *
 * Source code in this project is provided for trainers of
 * course AND-401 titled "Android Application Development".
 *
 * The is the source code for Lab 5 of the text book.
 *
 */

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.androidatc.customviewindrawer.android.IntentIntegrator;
import com.androidatc.customviewindrawer.android.IntentResult;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.TextHttpResponseHandler;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import cz.msebera.android.httpclient.Header;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SearchCatFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SearchCatFragment#newInstance} factory method to
 * create an instance of this fragment.
 */

public class BarCodeFrag extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SearchCatFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BarCodeFrag newInstance(String param1, String param2) {
        BarCodeFrag fragment = new BarCodeFrag();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public BarCodeFrag() {
        // Required empty public constructor
    }



    //the custom view
    private SearchView myView;
    private Button scanBtn,detailsBtn;
    private TextView formatTxt, contentTxt, TitleTxt, PublisherTxt, CreatorTxt, AvailabiltyTxt;

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



        scanBtn = (Button) rootView.findViewById(R.id.scan_button);
        formatTxt = (TextView) rootView.findViewById(R.id.scan_format);
        contentTxt = (TextView) rootView.findViewById(R.id.scan_content);
        detailsBtn = (Button) rootView.findViewById(R.id.scan_button);
        TitleTxt = (TextView) rootView.findViewById(R.id.title);
        PublisherTxt = (TextView) rootView.findViewById(R.id.Publisher);
        CreatorTxt = (TextView) rootView.findViewById(R.id.Creator);
        AvailabiltyTxt = (TextView) rootView.findViewById(R.id.Availability);

//        myView.setSquareColor(Color.BLUE);
//        myView.setLabelColor(Color.YELLOW);
//        myView.setLabelText("Press Me");

        scanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                myView.setSquareColor(Color.GREEN);
//                myView.setLabelColor(Color.MAGENTA);
//                myView.setLabelText("Android ATC");

                if (v.getId() == R.id.scan_button) {
                    //instantiate ZXing integration class
                    //IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
                    IntentIntegrator scanIntegrator = new IntentIntegrator(BarCodeFrag.this);
                    //start scanning
                    scanIntegrator.initiateScan();
                    // startActivityForResult(scanIntegrator, 1888);
                    // scanIntegrator.parseActivityResult

                } else {
                    //invalid scan data or scan canceled
                    Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                            "No scan data received!", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });
        return rootView;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        //retrieve result of scanning - instantiate ZXing object
        super.onActivityResult(requestCode, resultCode, intent);
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        //check we have a valid result

//        Toast.makeText(getActivity().getApplicationContext(), "Inside onActivityResult" , Toast.LENGTH_LONG).show();

        if (scanningResult != null) {
            //get content from Intent Result
            String scanContent = scanningResult.getContents();
            //get format name of data scanned
            String scanFormat = scanningResult.getFormatName();
            //output to UI
            formatTxt.setText("FORMAT: " + scanFormat);
            contentTxt.setText("CONTENT: " + scanContent);


//            Toast.makeText(getActivity().getApplicationContext(), "Reply: " + scanFormat + ":" + scanContent, Toast.LENGTH_LONG).show();

            CheckDetails(scanContent);
        }
    }

    public void CheckDetails(String scanContent) {
        //
        final int DEFAULT_TIMEOUT = 200000 * 1000000000;

//        Toast.makeText(getActivity().getApplicationContext(), "Scan Content : " + scanContent, Toast.LENGTH_LONG).show();

        // Make RESTful webservice call using AsyncHttpClient object
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(DEFAULT_TIMEOUT);

        RequestHandle requestHandle = client.get("http://koha-startRecord=1&maximumRecords=10&recordSchema=dc", new TextHttpResponseHandler() {

                    @Override
                    public void onSuccess(int i, Header[] headers, String response) {
//                        Toast.makeText(getActivity().getApplicationContext(), "XML File: " + response, Toast.LENGTH_LONG).show();
                        readBarCode(response);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String response, Throwable error) {
                        Toast.makeText(getActivity().getApplicationContext(), "Status code :" + statusCode + "errmsg : " + error.getMessage(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();

                    }

                }
        );
    }


    public void readBarCode(String response) {
        DocumentBuilder builder = null;

    try {
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(response));

        Document doc = builder.parse(src);
        //String available = doc.getElementsByTagName("zs:numberOfRecords").item(0).getTextContent();
        String title = doc.getElementsByTagName("dc:title").item(0).getTextContent();
        String creator1 = doc.getElementsByTagName("dc:creator").item(0).getTextContent();
        String creator2 = doc.getElementsByTagName("dc:creator").item(1).getTextContent();
        String publisher = doc.getElementsByTagName("dc:publisher").item(0).getTextContent();
        String description = doc.getElementsByTagName("dc:description").item(0).getTextContent();
        String availability = doc.getElementsByTagName("dc:duedate").item(0).getTextContent();
        NodeList list = doc.getElementsByTagName("dc:duedate");
//        NodeList available = doc.getElementsByTagName("dc:duedate/");

//        Element element = doc.getDocumentElement();

        src.setCharacterStream(new StringReader(response));



        NodeList nodes = doc.getElementsByTagName("dc:duedate");
        // print the text content of each child

//        int cnt=0;
//        // print the text content of each child
//        for (int i = 0; i < nodes.getLength(); i++) {
//            if(nodes.item(0).getNodeName().equals("dc:duedate") &&    nodes.item(i).getTextContent().trim().isEmpty()){
////                nodes.item(i).getTextContent().trim().length();
//                cnt++;
//            }
//        }


        int cnt=0;
        for (int i = 0; i < nodes.getLength(); i++) {
            if(nodes.item(i).getTextContent().trim().isEmpty()){
                cnt++;
            }

        }
        Log.e("TAGLOG", "" + cnt);

        //  String expiry = doc.getElementsByTagName("dateexpiry").item(0).getTextContent();

        // Toast.makeText(getActivity().getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show();
        Toast.makeText(getActivity().getApplicationContext(), "Title : " + title +
                "\n" + "Publisher : " + publisher +
                "\n" + "Creator : " + creator1 + "," + creator2 +
                "\n" + "Description : " + description +
                "\n" + "Total : " + list.getLength() +
                "\n" + "Available : " + cnt
                ,Toast.LENGTH_LONG).show();

    TitleTxt.setText("Title: " + title);


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

fragment_barcode.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:context="com.androidatc.customviewindrawer.BarCodeFrag"
    android:weightSum="1">

    <Button
        android:id="@+id/scan_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/scan"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:id="@+id/scan_format"
        android:layout_width="94dp"
        android:layout_height="40dp"
        android:textIsSelectable="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/scan_button"
        android:layout_gravity="center_horizontal"
        android:text="Format" />

    <TextView
        android:id="@+id/scan_content"
        android:layout_width="83dp"
        android:layout_height="40dp"
        android:textIsSelectable="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/scan_format"
        android:layout_weight="0.03"
        android:layout_gravity="center_horizontal"
        android:text="Content" />



    <TextView
        android:id="@+id/Title"
        android:layout_width="94dp"
        android:layout_height="40dp"
        android:textIsSelectable="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/title"
        android:layout_gravity="center_horizontal"
        android:text="Title" />

    <TextView
        android:id="@+id/Publisher"
        android:layout_width="83dp"
        android:layout_height="40dp"
        android:textIsSelectable="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/Publisher"
        android:layout_weight="0.03"
        android:layout_gravity="center_horizontal"
        android:text="Publisher" />

    <TextView
        android:id="@+id/Creator"
        android:layout_width="94dp"
        android:layout_height="40dp"
        android:textIsSelectable="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/Creator"
        android:layout_gravity="center_horizontal"
        android:text="Creator" />

    <TextView
        android:id="@+id/Availability"
        android:layout_width="83dp"
        android:layout_height="40dp"
        android:textIsSelectable="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/Availability"
        android:layout_weight="0.03"
        android:layout_gravity="center_horizontal"
        android:text="Availablity" />

</LinearLayout>

2 个答案:

答案 0 :(得分:3)

更改

TitleTxt = (TextView) rootView.findViewById(R.id.title);

TitleTxt = (TextView) rootView.findViewById(R.id.Title);

<TextView
    android:id="@+id/Title"

<TextView
    android:id="@+id/title"

答案 1 :(得分:1)

将您的标题文字ID更改为android:id="@+id/title"小写,因为您在java代码中使用TitleTxt = (TextView) rootView.findViewById(R.id.title);