2016-12-20 3 views
-1

Здравствуйте, я написал адаптер GridView, который должен правильно отображать одно изображение и один заголовок от FireBaseStorage.Адаптер GridView, не отображающий данные

Я проверил и проверил, что мои растровые изображения и заголовок правильно извлекаются. Я создаю экземпляр GridView и адаптера, когда «0» выбрано в PlaceActivity.

Я получаю данные в своем методе getData() на месте. Мой GridView также находится в макете Swipe Refresh в XML активности места. Есть идеи? благодаря

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> 

Сетка Item Layout 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> 

ответ

0

Вы должны добавить

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

внутри адаптера.

Ваш адаптер никогда не вызывает getView(), потому что вы не укажете, сколько просмотров у вас есть.

+0

Спасибо за ваш ответ. Я добавил эти строки в адаптер. Но пока ничего не отображается? @Override public int getCount() { return data.size(); } – androidcoder1234

+0

Я снова читаю ваш код, и с ним несколько проблем. Первая вещь в вашем методе getData(). Это работает async. Поэтому для вас он возвращает пустой массив, прежде чем добавлять к нему какие-либо элементы. Поэтому вместо этого вы должны сделать его функцией void, и когда вы получите новый элемент, добавьте его непосредственно в массив адаптеров и вызовите notifyDataSetChanged. Я напишу полный ответ сегодня вечером, когда вернусь домой, если не забуду – bogdanN

+0

Спасибо! Я был бы очень признателен. – androidcoder1234

 Смежные вопросы

  • Нет связанных вопросов^_^