未注释的参数覆盖 @NonNull 参数

Posted

技术标签:

【中文标题】未注释的参数覆盖 @NonNull 参数【英文标题】:Not annotated parameter overrides @NonNull parameter 【发布时间】:2019-09-24 19:52:04 【问题描述】:

inflater 出现@nonnull 错误,任何人都可以解决此错误吗? 我是android新手我不知道如何解决这个错误任何解决方案? 是主题的错误还是其他什么,我的代码有什么大问题吗?你能解决这个错误吗?由于此错误,我的代码无法正常工作。非常感谢您的帮助

下面列出了我在代码中的导入

       import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.app.DownloadManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.support.v7.widget.DividerItemDecoration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import static android.content.Context.DOWNLOAD_SERVICE;
import java.lang.reflect.Type;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;



 public class FilesListingFragment extends android.support.v4.app.Fragment 


    private static final String TAG = "FilesListingFragment";

    public static final String PATH_FILES = "http://%s:%s/files";
    public static final String PATH_STATUS = "http://%s:%s/status";
    public static final String PATH_FILE_DOWNLOAD = "http://%s:%s/file/%s";

    private String mSenderIp = null, mSenderSSID;
    private ContactSenderAPITask mUrlsTask;
    private ContactSenderAPITask mStatusCheckTask;

    private String mPort, mSenderName;

    static final int CHECK_SENDER_STATUS = 100;
    static final int SENDER_DATA_FETCH = 101;

    RecyclerView file;
    ProgressBar progressBar;
    TextView mTextView;

    private SenderFilesListingAdapter mFilesAdapter;

    private UiUpdateHandler uiUpdateHandler;

    private static final int SENDER_DATA_FETCH_RETRY_LIMIT = 3;
    private int senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT, senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;

    @Nullable

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) 
        View v = inflater.inflate(R.layout.fragment_files_listing, null);
        file = (RecyclerView) v.findViewById(R.id.files_list);
        progressBar = (ProgressBar) v.findViewById(R.id.loading);
        mTextView = (TextView) v.findViewById(R.id.empty_listing_text);
        mTextView.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                mTextView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                fetchSenderFiles();
            
        );
        file.setLayoutManager(new LinearLayoutManager(getActivity()));
        file.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.lidivider)));/**here is the error */
        mFilesAdapter = new SenderFilesListingAdapter(new ArrayList<String>());
        file.setAdapter(mFilesAdapter);
        uiUpdateHandler = new UiUpdateHandler(this);
        return v;
    

    public static FilesListingFragment getInstance(String senderIp, String ssid, String senderName, String port) 
        FilesListingFragment fragment = new FilesListingFragment();
        Bundle data = new Bundle();
        data.putString("senderIp", senderIp);
        data.putString("ssid", ssid);
        data.putString("name", senderName);
        data.putString("port", port);
        fragment.setArguments(data);
        return fragment;
    

    @Override
    public void onAttach(Context activity) 
        super.onAttach(activity);
        if (null != getArguments()) 
            mSenderIp = getArguments().getString("senderIp");
            mSenderSSID = getArguments().getString("ssid");
            mPort = getArguments().getString("port");
            mSenderName = getArguments().getString("name");
            Log.d(TAG, "sender ip: " + mSenderIp);
        
    

    @Override
    public void onResume() 
        super.onResume();
        fetchSenderFiles();
        checkSenderAPIAvailablity();
    

    private void fetchSenderFiles() 
        progressBar.setVisibility(View.VISIBLE);
        if (null != mUrlsTask)
            mUrlsTask.cancel(true);
        mUrlsTask = new ContactSenderAPITask(SENDER_DATA_FETCH);
        mUrlsTask.execute(String.format(PATH_FILES, mSenderIp, mPort));
    

    private void checkSenderAPIAvailablity() 
        if (null != mStatusCheckTask)
            mStatusCheckTask.cancel(true);
        mStatusCheckTask = new ContactSenderAPITask(CHECK_SENDER_STATUS);
        mStatusCheckTask.execute(String.format(PATH_STATUS, mSenderIp, mPort));
    

    @Override
    public void onPause() 
        super.onPause();
        if (null != mUrlsTask)
            mUrlsTask.cancel(true);
    

    @Override
    public void onDestroy() 
        super.onDestroy();
        if (null != uiUpdateHandler)
            uiUpdateHandler.removeCallbacksAndMessages(null);
        if (null != mStatusCheckTask)
            mStatusCheckTask.cancel(true);
    

    public String getSenderSSID() 
        return mSenderSSID;
    

    public String getSenderIp() 
        return mSenderIp;
    

    private void loadListing(String contentAsString) 
        Type collectionType = new TypeToken<List<String>>() 
        .getType();
        ArrayList<String> files = new Gson().fromJson(contentAsString, collectionType);
        progressBar.setVisibility(View.GONE);
        if (null == files || files.size() == 0) 
            mTextView.setText("No Downloads found.\n Tap to Retry");
            mTextView.setVisibility(View.VISIBLE);
         else 
            mTextView.setVisibility(View.GONE);
            mFilesAdapter.updateData(files);
        
    

    private void onDataFetchError() 
        progressBar.setVisibility(View.GONE);
        mTextView.setVisibility(View.VISIBLE);
        mTextView.setText("Error occurred while fetching data.\n Tap to Retry");
    

    private long postDownloadRequestToDM(Uri uri, String fileName) 

        // Create request for android download manager
        DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(uri);


        request.setTitle(fileName);

        request.setDescription("ShareThem");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);


        request.setDestinationInExternalFilesDir(getActivity(),
                Environment.DIRECTORY_DOWNLOADS, fileName);

        return downloadManager.enqueue(request);
    

    private class SenderFilesListingAdapter extends RecyclerViewArrayAdapter<String, SenderFilesListItemHolder> 
        SenderFilesListingAdapter(List<String> objects) 
            super(objects);
        

        void updateData(List<String> objects) 
            clear();

            mObjects = objects;
            notifyDataSetChanged();
        

        @Override
        public SenderFilesListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) 
            View itemView = LayoutInflater.from(parent.getContext()).


                    inflate(R.layout.listitem_file, parent, false);
            return new SenderFilesListItemHolder(itemView);
        


        @Override
        public void onBindViewHolder(SenderFilesListItemHolder holder, int position) 
            final String senderFile = mObjects.get(position);
            holder.itemView.setTag(senderFile);
            final String fileName = senderFile.substring(senderFile.lastIndexOf('/') + 1, senderFile.length());
            holder.title.setText(fileName);
            holder.download.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View view) 
                    postDownloadRequestToDM(Uri.parse(String.format(PATH_FILE_DOWNLOAD, mSenderIp, mPort, mObjects.indexOf(senderFile))), fileName);
                    Toast.makeText(getActivity(), "Downloading " + fileName + "...", Toast.LENGTH_SHORT).show();
                
            );
        
    

    static class SenderFilesListItemHolder extends RecyclerView.ViewHolder 
        TextView title;
        ImageButton download;

        SenderFilesListItemHolder(View itemView) 
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.sender_list_item_name);
            download = (ImageButton) itemView.findViewById(R.id.sender_list_start_download);
        
    


    /**
     * Performs network calls to fetch data/status from Sender.
     * Retries on error for times bases on values of @link FilesListingFragment#senderDownloadsFetchRetry
     */
    private class ContactSenderAPITask extends AsyncTask<String, Void, String> 

        int mode;
        boolean error;

        ContactSenderAPITask(int mode) 
            this.mode = mode;
        

        @Override
        protected String doInBackground(String... urls) 
            error = false;
            try 
                return downloadDataFromSender(urls[0]);
             catch (IOException e) 
                e.printStackTrace();
                error = true;
                Log.e(TAG, "Exception: " + e.getMessage());
                return null;
            
        

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) 
            switch (mode) 
                case SENDER_DATA_FETCH:
                    if (error) 
                        if (senderDownloadsFetchRetry >= 0) 
                            --senderDownloadsFetchRetry;
                            if (getView() == null || getActivity() == null || null == uiUpdateHandler)
                                return;
                            uiUpdateHandler.removeMessages(SENDER_DATA_FETCH);
                            uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(mode), 800);
                            return;
                         else senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT;
                        if (null != getView())
                            onDataFetchError();
                     else if (null != getView())
                        loadListing(result);
                    else Log.e(TAG, "fragment may have been removed, File fetch");
                    break;
                case CHECK_SENDER_STATUS:
                    if (error) 
                        if (senderStatusCheckRetryLimit > 1) 
                            --senderStatusCheckRetryLimit;
                            uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
                            uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 800);
                         else if (getActivity() instanceof ReceiverActivity) 
                            senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
                            ((ReceiverActivity) getActivity()).resetSenderSearch();
                            Toast.makeText(getActivity(), getString(R.string.p2p_receiver_error_sender_disconnected), Toast.LENGTH_SHORT).show();
                         else
                            Log.e(TAG, "Activity is not instance of ReceiverActivity");
                     else if (null != getView()) 
                        senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
                        uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
                        uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 1000);
                     else
                        Log.e(TAG, "fragment may have been removed: Sender api check");
                    break;
            

        

        private String downloadDataFromSender(String apiUrl) throws IOException 
            InputStream is = null;
            try 
                URL url = new URL(apiUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
               int response =
                conn.getResponseCode();
               Log.d(TAG, "The response is: " + response);
                is = conn.getInputStream();
                // Convert the InputStream into a string
                return readIt(is);
             finally 
                if (is != null) 
                    is.close();
                
            
        

        private String readIt(InputStream stream) throws IOException 
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try 
                Reader reader = new BufferedReader(
                        new InputStreamReader(stream, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) 
                    writer.write(buffer, 0, n);
                
             finally 
                stream.close();
            
            return writer.toString();
        
    
    private static class UiUpdateHandler extends Handler 
        WeakReference<FilesListingFragment> mFragment;

        UiUpdateHandler(FilesListingFragment fragment) 
            mFragment = new WeakReference<>(fragment);
        

        @Override
        public void handleMessage(Message msg) 
            FilesListingFragment fragment = mFragment.get();
            if (null == mFragment)
                return;
            switch (msg.what) 
                case CHECK_SENDER_STATUS:
                    fragment.checkSenderAPIAvailablity();
                    break;
                case SENDER_DATA_FETCH:
                    fragment.fetchSenderFiles();
                    break;
            
        
    

fragment_files_listing

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    tools:context=".receiver.FilesListingFragment"

    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/files_list"
        android:layout_
        android:layout_
        android:scrollbars="vertical" />

    <ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
        style="@android:style/Widget.Holo.ProgressBar"
        android:layout_
        android:id="@+id/loading"
        android:layout_
        android:layout_centerInParent="true"
        android:layout_gravity="center" />

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/empty_listing_text"
        android:layout_
        android:layout_
        android:layout_centerInParent="true"
        android:clickable="true"
        android:gravity="center"
        android:text="No Downloads found.\n Tap to Retry"
        android:visibility="gone" />

</RelativeLayout>

【问题讨论】:

在哪一行显示错误? 请分享您的日志和R.layout.fragment_files_listing xml 文件 @ferran 看看 xml 在这一行错误显示 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) 我认为由于这个错误还有一个看一下link 【参考方案1】:

未注解的参数覆盖@NonNull 参数

这只是一个警告。你有

@Override
public View onCreateView(LayoutInflater inflater...

而您要扩展的基类在 inflater 参数上有无效注释。

public View onCreateView(@NonNull LayoutInflater inflater...

您只需在 Android Studio 中按 alt-enter 即可获得一个快速修复菜单,该菜单可以选择在此处添加缺少的注释。

由于这个错误,我的代码无法正常工作。

缺少这样的注释只会导致警告。 “不工作”的原因是另一回​​事。请首先更新您的问题并在此处指定“不工作”对您意味着什么。

【讨论】:

可能由于这个错误,我的代码无法正常工作看看link【参考方案2】:

尝试改变这一行

View v = inflater.inflate(R.layout.fragment_files_listing, null);

View v = inflater.inflate(R.layout.fragment_files_listing, container, false);

这将使用您的片段容器膨胀您的布局。

【讨论】:

可能是由于这个错误,我的代码不起作用看看link【参考方案3】:

你必须改变这一行

View v = inflater.inflate(R.layout.fragment_files_listing, null);

View v = inflater.inflate(R.layout.fragment_files_listing, container, false);

然后清理你的项目并使缓存无效重启你的android工作室希望它会工作。

谢谢。

【讨论】:

以上是关于未注释的参数覆盖 @NonNull 参数的主要内容,如果未能解决你的问题,请参考以下文章

Android @NonNull的用处

在Android Studio中将默认注释设置为@NonNull

XCTest:由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'参数'测试“不能为零”。

无法使用 double 类型的左值初始化“id _NonNull”类型的参数

异常“已传递主参数'webdriver'但未定义主参数创建注释时出错

未找到改造注释。 (参数#1)