GridView适配器不显示数据

时间:2016-12-20 14:50:59

标签: android xml gridview mobile android-arrayadapter

您好我已经编写了一个GridView适配器,它应该正确显示FireBaseStorage中的一个图像和一个标题。

我已检查并验证我的位图和标题是否正确检索。当一个"地点"我实例化GridView和适配器。已在PlaceActivity中选择。

我在Place Activity中的getData()方法中获取数据。我的GridView也在Place Activity XML中的Swipe Refresh Layout中。有任何想法吗?感谢

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

 import java.util.ArrayList;

public class GridViewAdapter extends ArrayAdapter {
private Context context;
private int layoutResourceId;
private ArrayList data = new ArrayList();

public GridViewAdapter(Context context, int layoutResourceId, ArrayList data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)        {
    View row = convertView;
    ViewHolder holder = null;

    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.imageTitle = (TextView) row.findViewById(R.id.text);
        holder.image = (ImageView) row.findViewById(R.id.image);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    ImageItem item = (ImageItem) data.get(position);
    if(item.getTitle() != null)
    holder.imageTitle.setText(item.getTitle());
    else
    holder.imageTitle.setText("Test");

    holder.image.setImageBitmap(item.getImage());
    return row;
}

static class ViewHolder {
    TextView imageTitle;
    ImageView image;
}
}


import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class PlaceActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
    private GoogleApiClient mGoogleApiClient;
    private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
    private Place p;
    private AutocompleteFilter typeFilter;
    private GridView gridView;
    private GridViewAdapter gridAdapter;
    private SwipeRefreshLayout mySwipeRefreshLayout;
    private Bitmap b;
    private String t;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_place);

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        1);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }



        Intent i = getIntent();
        p = null;
        mGoogleApiClient = new GoogleApiClient
                .Builder(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .enableAutoManage(this, this)
                .build();
        typeFilter = new AutocompleteFilter.Builder()
                .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                .build();

        mySwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
        mySwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {

                        // This method performs the actual data-refresh operation.
                        // The method calls setRefreshing(false) when it's finished.
                        myUpdateOperation();
                    }
                }
        );
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (Build.VERSION.SDK_INT >= 23) {
                    if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                            == PackageManager.PERMISSION_GRANTED) {

                    } else {

                        ActivityCompat.requestPermissions(PlaceActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);


                    }
                }


                Intent i = new Intent(getApplicationContext(), Upload.class);
                if(p==null)
                {
                    Context context = getApplicationContext();
                    CharSequence text = "Select a location!";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }
                else {
                    i.putExtra("folder", p.getName());

                    startActivity(i);
                }

            }
        });




    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                // User chose the "Settings" item, show the app settings UI...
                return true;

            case R.id.search:
                // User chose the "Favorite" action, mark the current item
                // as a favorite...
                try {
                    Intent intent =
                            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                                    .setFilter(typeFilter)
                                    .build(this);
                    startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }


                return true;

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                p = place;
                gridView = (GridView) findViewById(R.id.grid_View);
                gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, getData());
                gridView.setAdapter(gridAdapter);


            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                // TODO: Handle the error.


            } else if (resultCode == RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

public void myUpdateOperation()
{
    if(p==null)
    {
        Context context = getApplicationContext();
        CharSequence text = "Select a location!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
    gridAdapter.notifyDataSetChanged();
    gridView.invalidateViews();
    GridViewAdapter gridAdapter2 = new GridViewAdapter(this, R.layout.grid_item_layout, getData());
    gridView.setAdapter(gridAdapter2);
    mySwipeRefreshLayout.setRefreshing(false);
}


    private ArrayList<ImageItem> getData() {
        final ArrayList<ImageItem> imageItems = new ArrayList<>();
        DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child((String) p.getName()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
                FirebaseStorage storage = FirebaseStorage.getInstance();
                StorageReference httpsReference = storage.getReferenceFromUrl(myUrl);
                while (iter.hasNext()) {
                    HashMap<String,String> m  = (HashMap<String, String>) iter.next().getValue();
                String v = m.get("url");
                    Log.d("url",v);

                    String bu = m.get("bucket");
                    Log.d("bucket",bu);
                    StorageReference iR = httpsReference.child(bu).child("thumb");

                    final long ONE_MEGABYTE = 1024 * 1024;
                    iR.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
                        @Override
                        public void onSuccess(byte[] bytes) {
                            // Data for "images/island.jpg" is returns, use this as needed
                            b=BitmapFactory.decodeByteArray(bytes,0, bytes.length);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            // Handle any errors
                        }
                    });


                    httpsReference.child(bu).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
                        @Override
                        public void onSuccess(StorageMetadata storageMetadata) {
                            // Metadata now contains the metadata for 'images/forest.jpg'
                            t = storageMetadata.getCustomMetadata("title");
                            Log.d("title", t);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            Log.d("error", "ERROr");
                            // Uh-oh, an error occurred!
                        }
                    });



                    imageItems.add(new ImageItem(b, t));




                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


        return imageItems;
    }





}

Place_Activity XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >
    <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"
        android:paddingBottom="2dp" />


    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swiperefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="?attr/actionBarSize"
            android:paddingTop="50dp">
        <GridView
            android:id="@+id/grid_View"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:columnWidth="100dp"
            android:drawSelectorOnTop="true"
            android:gravity="center"
            android:numColumns="auto_fit"
            android:stretchMode="columnWidth"
            android:verticalSpacing="5dp"
            android:focusable="true"
            android:clickable="true"/>
        </LinearLayout>
    </android.support.v4.widget.SwipeRefreshLayout>
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="+"
            android:elevation="16dp"
            android:textColor="@android:color/white"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:color/transparent"
            android:id ="@+id/fab"
            android:paddingRight="4dp"
            android:paddingBottom="4dp" />
    </FrameLayout>



</android.support.design.widget.CoordinatorLayout>

网格项布局XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:orientation="vertical"
    android:padding="5dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:textSize="12sp" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

你应该添加

getCount(){
  return data.size();
}

在适配器内。

您的适配器永远不会调用getView(),因为您没有指定您拥有的视图数量。