Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/199.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 自定义适配器不适用于片段中的RecyclerView_Android_Android Fragments_Android Recyclerview_Android Adapter - Fatal编程技术网

Android 自定义适配器不适用于片段中的RecyclerView

Android 自定义适配器不适用于片段中的RecyclerView,android,android-fragments,android-recyclerview,android-adapter,Android,Android Fragments,Android Recyclerview,Android Adapter,我正在做一个Android项目来显示Github回购的详细信息 我试图首先为一家特定的公司选择组织名称,比如亚马逊在Github上有AWS、AMZN、AWS等组织 为此,我首先通过RecyclerView创建了一个可点击按钮列表(它可以工作) 然后,当用户单击特定的组织名称时,应用程序向Github发出HTTP请求,以获取相关信息并显示在使用另一个RecycleView(不工作的RecycleWebRepoAdapter.java)的片段中 此部件不作为onCreateViewHolder或on

我正在做一个Android项目来显示Github回购的详细信息

我试图首先为一家特定的公司选择组织名称,比如亚马逊在Github上有AWS、AMZN、AWS等组织

为此,我首先通过RecyclerView创建了一个可点击按钮列表(它可以工作)

然后,当用户单击特定的组织名称时,应用程序向Github发出HTTP请求,以获取相关信息并显示在使用另一个RecycleView(不工作的RecycleWebRepoAdapter.java)的片段中

此部件不作为onCreateViewHolder或onBindViewHolder工作,也不调用onBindViewHolder(调用getItemCount并返回正确的长度)

尝试了一些像这样的建议!但它不起作用

感谢您的帮助

OrganizationInfo.java//驱动程序

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class OrganizationInfo extends AppCompatActivity {
    private String companyName;
    private String companyAddress;
    private List<String> orgNames;
    private TextView companyNameTV;
    private TextView companyAddressTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_organization_info);
        getCompanyData();
        companyNameTV = findViewById(R.id.companyNameTv);
        companyAddressTV = findViewById(R.id.companyAddressTv);
        companyNameTV.setText(companyName);
        companyAddressTV.setText(companyAddress);
        initRecyclerView();

    }

    private void getCompanyData() {
        companyName = "amazon";
        companyAddress = "207 Boren Ave N, Seattle, WA 98109";
        orgNames = new ArrayList<>();
        orgNames.add("amzn");
        orgNames.add("aws");
        orgNames.add("awslabs");
    }

    private void initRecyclerView(){
//        Log.d(TAG, "initRecyclerView: init recyclerview");

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        RecyclerView recyclerView = findViewById(R.id.orgListRecyclerView);
        recyclerView.setLayoutManager(layoutManager);
        RecyclerViewOrgAdapter adapter = new RecyclerViewOrgAdapter(this, orgNames);
        recyclerView.setAdapter(adapter);
    }
}

导入android.os.Bundle;
导入android.util.Log;
导入android.widget.TextView;
导入androidx.appcompat.app.appcompat活动;
导入androidx.recyclerview.widget.LinearLayoutManager;
导入androidx.recyclerview.widget.recyclerview;
导入java.util.ArrayList;
导入java.util.List;
公共类OrganizationInfo扩展AppCompativeActivity{
私有字符串companyName;
私有字符串公司地址;
私人名单或姓名;
私有文本视图公司名称电视;
私人文本视图公司地址TV;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u organization\u info);
getCompanyData();
companyNameTV=findviewbyd(R.id.companyNameTV);
companyAddressTV=findViewById(R.id.companyAddressTV);
companyNameTV.setText(companyName);
companyAddressTV.setText(companyAddress);
initRecyclerView();
}
私有void getCompanyData(){
companyName=“亚马逊”;
公司地址=“华盛顿州西雅图博伦大道207号,邮编98109”;
orgNames=新的ArrayList();
组织名称。添加(“amzn”);
组织名称。添加(“aws”);
组织名称。添加(“AWS”);
}
私有void initRecyclerView(){
//Log.d(标记“initRecyclerView:init recyclerview”);
LinearLayoutManager layoutManager=新的LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
RecyclerView RecyclerView=findViewById(R.id.orgListRecyclerView);
recyclerView.setLayoutManager(layoutManager);
RecycleServiceOrganAdapter=新的RecycleServiceOrganAdapter(这是orgNames);
recyclerView.setAdapter(适配器);
}
}
GithubFragment.java

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 */
public class GithubFragment extends Fragment {

    private List<Repository> repositories = new ArrayList<>();
    RecyclerView recyclerView;
    RecyclerViewRepoAdapter listAdapter;
    public GithubFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        assert getArguments() != null;
        View v =  inflater.inflate(R.layout.fragment_github, container, false);
        recyclerView = v.findViewById(R.id.repo_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(listAdapter);  // Called from here after response from cloud funtion
        return v;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            String orgName = getArguments().getString("org_name");
            GraphQLAsyncTask graphQLAsyncTask = new GraphQLAsyncTask();
            graphQLAsyncTask.execute(orgName, "");
        }

    }

    private class GraphQLAsyncTask extends AsyncTask<String, String, String> {

        private String response;
        private Reader in;

        @Override
        protected String doInBackground(String... body) {
            Map<String, String> params = new HashMap<>();
            params.put("company", body[0]);
            params.put("language", body[1]);

            StringBuilder postData = new StringBuilder();


            try{
                for (Map.Entry param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey().toString(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");

                String url = "https://****************/getOrgReposGraphQL";
                URL urlObj = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Accept-Charset", "UTF-8");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.getOutputStream().write(postDataBytes);

                conn.connect();
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                StringBuilder sb = new StringBuilder();
                for (int c; (c = in.read()) >= 0; )
                    sb.append((char) c);
                response = sb.toString();

            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }


        @Override
        protected void onPostExecute(String response) {
            ParseResponse parseResponse = new ParseResponse(response);
            repositories.addAll(parseResponse.getRepositories());
            listAdapter.notifyDataSetChanged();

        }
    }
}

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class RecyclerViewOrgAdapter extends RecyclerView.Adapter<RecyclerViewOrgAdapter.ViewHolder> {
    private static final String TAG = "RecyclerViewOrgAdapter";
    private List<String> orgs;
    private Context context;

    public RecyclerViewOrgAdapter(Context context, List<String> orgs) {
        this.orgs = orgs;
        this.context = context;

    }
    @NonNull
    @Override
    public RecyclerViewOrgAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.organization_id_relative_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerViewOrgAdapter.ViewHolder holder, final int position) {
        holder.orgIdBtn.setText(orgs.get(position));
        holder.orgIdBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppCompatActivity activity = (AppCompatActivity) v.getContext();
                Fragment githubFragment = new GithubFragment();
                Bundle bundle = new Bundle();
                bundle.putString("org_name", orgs.get(position));
                githubFragment.setArguments(bundle);
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.github_fragment, githubFragment).addToBackStack(null).commit();
            }
        });
    }

    @Override
    public int getItemCount() {

        return orgs.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        Button orgIdBtn;
        public ViewHolder(View itemView) {
            super(itemView);
            orgIdBtn = itemView.findViewById(R.id.orgIdBtn);
        }
    }



}

导入android.os.AsyncTask;
导入android.os.Bundle;
导入androidx.annotation.NonNull;
导入androidx.annotation.Nullable;
导入androidx.fragment.app.fragment;
导入androidx.recyclerview.widget.LinearLayoutManager;
导入androidx.recyclerview.widget.ListAdapter;
导入androidx.recyclerview.widget.recyclerview;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.Reader;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.ProtocolException;
导入java.net.URL;
导入java.net.urlcoder;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
/**
*一个简单的{@link Fragment}子类。
*/
公共类GithubFragment扩展了片段{
私有列表存储库=新的ArrayList();
回收视图回收视图;
RecycleServiceWrepoAdapter列表适配器;
公共GithubFragment(){
//必需的空公共构造函数
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
断言getArguments()!=null;
视图v=充气机。充气(R.layout.fragment\u github,容器,假);
recyclerView=v.findViewById(R.id.repo\u recycler\u视图);
LinearLayoutManager布局管理器=新的LinearLayoutManager(getContext());
listAdapter=new RecycleServiceWrepoAdapter(getContext(),repositories);//要显示的Github repo列表
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter);//在云函数响应后从此处调用
返回v;
}
@凌驾
已创建视图上的公共void(视图,@Nullable Bundle savedInstanceState){
如果(getArguments()!=null){
字符串orgName=getArguments().getString(“组织名称”);
GraphQLAsyncTask GraphQLAsyncTask=新建GraphQLAsyncTask();
graphQLAsyncTask.execute(orgName,“”);
}
}
私有类GraphQLSyncTask扩展了AsyncTask{
私有字符串响应;
私人读者;
@凌驾
受保护的字符串背景(字符串…正文){
Map params=新的HashMap();
参数put(“公司”,正文[0]);
参数put(“语言”,正文[1]);
StringBuilder postData=新建StringBuilder();
试一试{
对于(Map.Entry参数:params.entrySet()){
如果(postData.length()!=0)postData.append('&');
append(URLEncoder.encode(param.getKey().toString(),“UTF-8”);
postData.append('=');
append(URLEncoder.encode(String.valueOf(param.getValue()),“UTF-8”);
}
字节[]postDataBytes=postData.toString().getBytes(“UTF-8”);
String url=“https://**************/getOrgReposGraphQL”;
URL urlObj=新URL(URL);
HttpURLConnection conn=(HttpURLConnection)urlObj.openConnection();
连接设置输出(真);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“接受字符集”、“UTF-8”);

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class RecyclerViewOrgAdapter extends RecyclerView.Adapter<RecyclerViewOrgAdapter.ViewHolder> {
    private static final String TAG = "RecyclerViewOrgAdapter";
    private List<String> orgs;
    private Context context;

    public RecyclerViewOrgAdapter(Context context, List<String> orgs) {
        this.orgs = orgs;
        this.context = context;

    }
    @NonNull
    @Override
    public RecyclerViewOrgAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.organization_id_relative_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerViewOrgAdapter.ViewHolder holder, final int position) {
        holder.orgIdBtn.setText(orgs.get(position));
        holder.orgIdBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppCompatActivity activity = (AppCompatActivity) v.getContext();
                Fragment githubFragment = new GithubFragment();
                Bundle bundle = new Bundle();
                bundle.putString("org_name", orgs.get(position));
                githubFragment.setArguments(bundle);
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.github_fragment, githubFragment).addToBackStack(null).commit();
            }
        });
    }

    @Override
    public int getItemCount() {

        return orgs.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        Button orgIdBtn;
        public ViewHolder(View itemView) {
            super(itemView);
            orgIdBtn = itemView.findViewById(R.id.orgIdBtn);
        }
    }



}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/repo_list_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="1."
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/repo_name_row"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="16dp"
        android:text="Repo Name"
        android:textSize="24sp"
        app:layout_constraintStart_toEndOf="@+id/repo_list_number"
        app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="42dp"
        android:layout_height="33dp"
        android:layout_marginTop="12dp"
        app:layout_constraintStart_toStartOf="@+id/repo_name_row"
        app:layout_constraintTop_toBottomOf="@+id/repo_name_row"
        app:srcCompat="@mipmap/star_dark_round" />

    <TextView
        android:id="@+id/repo_stars_tv"
        android:layout_width="42dp"
        android:layout_height="33dp"
        android:layout_marginStart="16dp"
        android:text="1441"
        app:layout_constraintBottom_toBottomOf="@+id/imageView2"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <TextView
        android:id="@+id/repo_language_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="8dp"
        android:text="Ruby"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="@+id/repo_stars_tv"
        app:layout_constraintStart_toEndOf="@+id/repo_stars_tv"
        app:layout_constraintTop_toTopOf="@+id/repo_stars_tv" />
</LinearLayout>
</LinearLayout>

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".GithubFragment">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/repo_recycler_view"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="match_parent" />
</LinearLayout>
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display

recyclerView.setLayoutManager(layoutManager);            
recyclerView.setAdapter(listAdapter);  // Called from here after response from cloud funtion
assert getArguments() != null;
View v =  inflater.inflate(R.layout.fragment_github, container, false);
recyclerView = v.findViewById(R.id.repo_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display

recyclerView.setLayoutManager(layoutManager);            
recyclerView.setAdapter(listAdapter);  // Called from here after response from cloud funtion
return v;
ParseResponse parseResponse = new ParseResponse(response);
repositories = parseResponse.getRepositories();
listAdapter.notifyDataSetChanged();