我想創建一個應用程序來顯示在回收站查看數據。但是,當我運行它時,主視圖是空白的(工具欄和導航抽屜工作正常)。我仔細查看了我的代碼,發現了類似的問題,但是目前爲止還沒有任何工作。我已經測試了可以工作的asynctasks,但是信息不會顯示。RecyclerView片段不會出現
主要活動:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private static ListView mDrawerList;
private static ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private static String zipCode = "<zipcode>";
private static String street = "<address>";
public static String[] officeList = null;
public static Elements positionLinks = null;
public static int positionSelected;
public CardFragment currentFragment;
public static String[] namesOfCandidates;
public static String[] partiesOfCandidates;
public static String[] occupationsOfCandidates;
public static String[] candidateLinks;
public static boolean gotCandidates = false;
public static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
officeList = getResources().getStringArray(R.array.offices_array);
new AsyncPositions().execute();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, officeList));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_favorite).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}else if(item.getItemId()==R.id.action_settings){
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
// User chose the "Settings" item, show the app settings UI...
return true;
}else if(item.getItemId()==R.id.action_favorite){
Toast.makeText(this, "Favorited", Toast.LENGTH_SHORT).show();
// User chose the "Favorite" action, mark the current item
// as a favorite...
//remember to change this to something else - or maybe just a starred thing for elected officials
return true;
}else {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_buttons, menu);
return super.onCreateOptionsMenu(menu);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
/**
* Swaps fragments in the main content view
*/
private void selectItem(int position) {
positionSelected = position;
//try {
new AsyncCandidates().execute();
/* }
catch(InterruptedException ie){
ie.printStackTrace();
}
catch(ExecutionException ee){
ee.printStackTrace();
}*/
//change the cards to info about candidate
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(officeList[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
}
public String pollingPlaceInfo(){
//document.getElementsByClassName("PollingPlace_polling-place-content_ucq")[0].innerText;
return null;
}
//Gets the information about the specific candidate chosen by the card view
// requests position on drawer and candidate number (index) to pinpoint which candidate
// returns 2d array that contains each issue as well as info about it
public String[][] getIssues(int position, int candidate) {
return null;
}
//asynctask to pull the positions for the nav drawer
private static class AsyncPositions extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(MainActivity.context);
String[] positions;
private String zipCode;
private String street;
private String urlString = "";
private Elements positionLinks;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.show();
zipCode = MainActivity.zipCode;
street = MainActivity.street;
}
@Override
protected Void doInBackground(Void... params) {
Document doc = null;
urlString = "http://votersedge.org/en/ca/search?zip="+zipCode+"&address="+street;
try {
//get initial landing page to find most recent election
doc = Jsoup.connect(urlString)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
//get the link to the most recent election page
String newLink = "";
boolean nullpe = false;
try{
doc.body().getElementsByClass("MultipleElections_upcoming-elections_3C2 col-md-12").first().child(1).attr("action");
}
catch(NullPointerException npe) {
newLink = "http://votersedge.org"+doc.body().getElementsByClass("MultipleElections_recent-elections_rsw col-md-12").first().child(1).attr("action");
nullpe = true;
}
if(!nullpe) {
newLink = "http://votersedge.org" + doc.body().getElementsByClass("MultipleElections_upcoming-elections_3C2 col-md-12").first().child(1).attr("action");
}
doc = Jsoup.connect(newLink)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
}
catch(IOException ioe){
ioe.printStackTrace();
}
Elements positionHeaders = doc.getElementsByClass("ContestsList_jurisdiction-group-label_1Kt");
positionLinks = doc.getElementsByClass("ContestsList_contest-link_W44");
//get size of positions list for easy access
int sizeOfList = positionLinks.size()/2;
//create array that will be returned
positions = new String[sizeOfList];
int l = 0;
int k=0;
int j=2;
for(int i=0; i<sizeOfList; i++){
try{
doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j);
}
catch(IndexOutOfBoundsException ibe){
k++;
j=2;
l++;
}
try{
doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0);
}
catch(IndexOutOfBoundsException ibe){
j++;
l++;
}
while(!doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0).tagName().equals("h4")){
j++;
l++;
}
positions[i] = positionHeaders.eq(l).text() + " " +doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0).child(0).child(1).text();
j++;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.officeList = positions;
MainActivity.mDrawerList.setAdapter(new ArrayAdapter<>(MainActivity.context,
R.layout.drawer_list_item, MainActivity.officeList));
MainActivity.positionLinks = positionLinks;
pdLoading.dismiss();
}
}
private class AsyncCandidates extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(MainActivity.context);
private Elements positionElements;
private int position;
private String[] namesOfCandidates;
private String[] partiesOfCandidates;
private String[] occupationsOfCandidates;
private String[] candidateLinks;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.show();
positionElements = MainActivity.positionLinks;
position = MainActivity.positionSelected;
}
@Override
protected Void doInBackground(Void... params) {
Document doc = null;
String link = "http://votersedge.org"+ positionElements.eq(position).attr("href");
try {
doc = Jsoup.connect(link)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
}
catch(IOException ioe){
ioe.printStackTrace();
}
//getting links for reference for further information gathering
//need to create initial array to get all links (each has 1 duplicate in the array)
// and then create another array to get rid of duplicates
Elements links = doc.body().getElementsByClass("CandidateCard_candidate-link_2m1");
String[] cLinks = new String[links.size()];
for(int i=0; i<links.size(); i++) {
cLinks[i] = "http://votersedge.org" + links.eq(i).attr("href");
}
candidateLinks = new String[links.size()/2];
for(int i=0; i<links.size(); i+=2){
candidateLinks[i/2] = cLinks[i];
}
//getting names of candidates
Elements names = doc.body().getElementsByClass("CandidateCard_candidate-name_234 col-md-12 col-xs-12 col-sm-12 flush-cols");
namesOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
namesOfCandidates[i] = names.eq(i).text();
}
//getting political parties of candidates
Elements attributes = doc.body().getElementsByClass("CandidateCard_candidate-attributes_3qD col-md-12 col-xs-12 col-sm-12 flush-cols");
partiesOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
partiesOfCandidates[i] = attributes.eq(i).first().child(0).text()+" Candidate";
if(partiesOfCandidates[i].equals(" Candidate")) partiesOfCandidates[i] = "Candidate";
}
//getting occupations of candidates
occupationsOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
occupationsOfCandidates[i] = attributes.eq(i).first().child(1).text();
}
gotCandidates = true;
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.namesOfCandidates = namesOfCandidates;
MainActivity.candidateLinks = candidateLinks;
MainActivity.partiesOfCandidates = partiesOfCandidates;
MainActivity.occupationsOfCandidates = occupationsOfCandidates;
Bundle bundle = new Bundle();
bundle.putStringArray("names", namesOfCandidates);
bundle.putStringArray("parties", partiesOfCandidates);
bundle.putStringArray("links", candidateLinks);
bundle.putStringArray("occupations", occupationsOfCandidates);
FragmentManager fm = getSupportFragmentManager();
MainActivity.this.currentFragment = (CardFragment) fm.findFragmentById(R.id.fragmentContainer);
if (MainActivity.this.currentFragment == null) {
MainActivity.this.currentFragment = new CardFragment();
MainActivity.this.currentFragment.setArguments(bundle);
fm.beginTransaction()
.add(R.id.fragmentContainer, MainActivity.this.currentFragment)
.addToBackStack(null)
.commit();
}else{
MainActivity.this.currentFragment = new CardFragment();
MainActivity.this.currentFragment.setArguments(bundle);
fm.beginTransaction()
.replace(R.id.fragmentContainer, MainActivity.this.currentFragment)
.addToBackStack(null)
.commit();
}
pdLoading.dismiss();
}
}
}
CardFragment.java
public class CardFragment extends Fragment {
RecyclerView MyRecyclerView;
String[] namesOfCandidates;
String[] partiesOfCandidates;
String[] occupationsOfCandidates;
String[] candidateLinks;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("test", "fragment has been created");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.getArguments();
namesOfCandidates = this.getArguments().getStringArray("names");
partiesOfCandidates = this.getArguments().getStringArray("parties");
candidateLinks = this.getArguments().getStringArray("links");
occupationsOfCandidates = this.getArguments().getStringArray("occupations");
View view = inflater.inflate(R.layout.fragment_card, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (namesOfCandidates.length > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(namesOfCandidates));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private String[] list;
public MyAdapter(String[] Data) {
list = Data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list[position]);
holder.mainTextView.setText(CardFragment.this.partiesOfCandidates[position]+"Candidate\n"+CardFragment.this.occupationsOfCandidates[position]);
holder.arrowImageView.setTag(R.drawable.ic_arrow_forward_black_24dp);
}
@Override
public int getItemCount() {
return list.length;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
ImageView arrowImageView;
TextView mainTextView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
mainTextView = (TextView) v.findViewById(R.id.mainTextView);
arrowImageView = (ImageView) v.findViewById(R.id.arrowImageView);
arrowImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = (int)arrowImageView.getTag();
if(id == R.drawable.ic_arrow_forward_black_24dp) {
//MOVE TO NEXT SCREEN
}
}
});
}
}
activity_main.xml中
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</FrameLayout>
<!-- Action bar -->
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:theme="@style/ThemeOverlay.AppCompat.Light"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
fragment_card.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_left_margin"
android:paddingRight="@dimen/activity_right_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<android.support.v7.widget.RecyclerView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
recycle_items.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/card_height"
android:orientation="vertical"
android:weightSum="4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:background="@android:drawable/screen_background_dark_transparent"
android:orientation="vertical">
<TextView
android:id="@+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="@dimen/text_size"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="3.2"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<TextView
android:id="@+id/mainTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="@dimen/text_size2"
android:layout_gravity="center"
/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="0.8"
android:gravity="center|right"
android:orientation="horizontal">
<ImageView
android:id="@+id/arrowImageView"
android:layout_width="@dimen/icon_width"
android:layout_height="@dimen/icon_height"
android:padding="@dimen/icon_padding"
android:src="@drawable/ic_arrow_forward_black_24dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
任何幫助非常感謝!
不幸的是,這不起作用 - 它仍然不顯示它。另外,這並不能解釋沒有例外情況。 – personMMIV
您是否已經確保片段中的「namesOfCandidates」包含正確的元素? 順便說一句,使用'&'不會顯示一個異常,因爲它是一個有效的運算符,它是按位與。 –
namesOfCandidates包含正確的元素。它看起來像片段不會顯示,因爲通過擺脫導航抽屜和操作欄的recyclerview出現 – personMMIV