我无法上传将另一个API发送到Firebase的照片

时间:2018-11-18 23:43:26

标签: android firebase retrofit firebase-storage android-glide

我创建了基本的Android屏幕,其中列出了流行电影(THE MOVIE DB)enter code here。我正在使用recyclerview来执行此操作。当我单击电影时,会看到有关该电影的详细信息。我的主要目的是在firebase中上传电影海报。我的连接已经完成。我可以写电影名称,评分和概述,但不能在firebase中上传电影海报。有没有人可以帮助我?谢谢

public class MyMovieAdapter extends RecyclerView.Adapter<MyMovieAdapter.MyViewHolder> {

private Context context;
private List<Movie> mList;
public static String movieId;
public Glide x;


private DatabaseReference dRef= FirebaseDatabase.getInstance().getReference();
private DatabaseReference rootRef=dRef.child("user");
private StorageReference storageManager;


public MyMovieAdapter(Context context, List<Movie> mList) {
    this.context = context;
    this.mList = mList;
}


@NonNull
@Override
public MyMovieAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view= LayoutInflater.from(parent.getContext()).
            inflate(R.layout.movie_layout,parent,false);

    return new MyViewHolder(view);


}

@Override
public void onBindViewHolder(@NonNull MyMovieAdapter.MyViewHolder holder, int position) { //final
    holder.title.setText(mList.get(position).getTitle());
    String vote=Double.toString(mList.get(position).getVoteAverage());
    holder.uservote.setText(vote);

    Glide.with(context).load(mList.get(position).getImagePath()).into(holder.image);//placeholder?
}

@Override
public int getItemCount() {
    return mList.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder{
    public TextView title,uservote;
    public ImageView image;

    MyViewHolder(View view){
        super(view);
        title=view.findViewById(R.id.movie_title);
        uservote=view.findViewById(R.id.movie_rate);
        image=view.findViewById(R.id.movie_image_2);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int pos=getAdapterPosition();
                //if line
                Movie selectedMovie=mList.get(pos);
                Intent i=new Intent(context,DetailActivity.class);
                i.putExtra("original_title",mList.get(pos).getTitle());
                i.putExtra("poster_path",mList.get(pos).getImagePath());
                i.putExtra("overview",mList.get(pos).getOverView());
                i.putExtra("vote_average",Double.toString(mList.get(pos).getVoteAverage()));
                i.putExtra("release_date",mList.get(pos).getReleaseDate());
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                movieId=dRef.push().getKey();

                rootRef.child(movieId).child("movieName").setValue(mList.get(pos).getTitle());
                rootRef.child(movieId).child("movieImage").setValue(mList.get(pos).getImagePath());
                //storageManager.child(mList.get(pos).getImagePath());
                storageManager=FirebaseStorage.getInstance().getReference();


                 Uri u=Uri.parse(mList.get(pos).getImagePath());



                storageManager.putFile(u).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    }
                });

                context.startActivity(i);


            }
        });
    }

}

}

public class DetailActivity extends AppCompatActivity {

public TextView movieName,movieOverView,movieReleaseDate,movieUserAverage;
public ImageView imageView;
private Uri imageUri;

private DatabaseReference dRef= FirebaseDatabase.getInstance().getReference();
private DatabaseReference rootRef=dRef.child("user");
private StorageReference storageManager= FirebaseStorage.getInstance().getReference("upload").child("eee");

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

    imageView=findViewById(R.id.movie_image);
    movieName=findViewById(R.id.movie_name);
    movieOverView=findViewById(R.id.movie_overview);
    movieReleaseDate=findViewById(R.id.movie_release_date);
    movieUserAverage=findViewById(R.id.movie_vote_average);

    Intent comenIntent=getIntent();

    if(comenIntent.hasExtra("original_title")){

        String nameOfMovie=getIntent().getExtras().getString("original_title");
        String overView=getIntent().getExtras().getString("overview");
        String vote=getIntent().getExtras().getString("vote_average");
        String releaseDate=getIntent().getExtras().getString("release_date");
        String image=getIntent().getExtras().getString("poster_path");

        Glide.with(this).load(image).into(imageView);
        movieName.setText(nameOfMovie);
        movieOverView.setText(overView);
        movieUserAverage.setText(vote);
        movieReleaseDate.setText(releaseDate);

        //StorageReference st=storageManager.child("fff");

        //selectImage();

        imageUri=Uri.parse(image);
        //getFileExtension(imageUri);

        storageManager.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            }
        });


    }
}

private void selectImage(){
    Intent b=new Intent();
    b.setType("image/*");
    b.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(b,RESULT_OK);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode==RESULT_OK){
        imageUri=data.getData();
    }

}

private String getFileExtension(Uri uri){
    ContentResolver cR=getContentResolver();
    MimeTypeMap mime=MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(cR.getType(uri));
}

}

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private MyMovieAdapter myMovieAdapter;
private ArrayList<Movie> movieList;
private SwipeRefreshLayout swipeRefreshLayout;
public ProgressDialog progressDialog;

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

    editScreen();
    swipeRefreshLayout=findViewById(R.id.swipe_refresh);
    swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_dark);
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            editScreen();
            Toast.makeText(MainActivity.this,"Movies Refreshed",Toast.LENGTH_SHORT).show();
        }
    });
}

public Activity getActivity(){
   Context context=this;
    while (context instanceof ContextWrapper){
       if (context instanceof Activity){
            return (Activity) context;
        }
        context=((ContextWrapper)context).getBaseContext();
    }
    return null;
}

private void editScreen(){

    progressDialog=new ProgressDialog(this);
    progressDialog.setMessage("Movies are being refreshed !");
    progressDialog.setCancelable(false);
    progressDialog.show();

    recyclerView=findViewById(R.id.recycler_view);


    movieList=new ArrayList<>();
    myMovieAdapter=new MyMovieAdapter(this,movieList);

    //recyclerView.setHasFixedSize(true);
    //RecyclerView.LayoutManager lm=new LinearLayoutManager(getApplicationContext());
    //recyclerView.setLayoutManager(lm);
    //recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(),LinearLayoutManager.VERTICAL));
   if(getActivity().getResources().getConfiguration().orientation== Configuration.ORIENTATION_PORTRAIT){
       recyclerView.setLayoutManager(new GridLayoutManager(this,1));
    }else{
       recyclerView.setLayoutManager(new GridLayoutManager(this,4));
    }

    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(myMovieAdapter);
    myMovieAdapter.notifyDataSetChanged();

    loadJSON();

}

private void loadJSON(){



    try{

        if (BuildConfig.THE_MOVIE_DB_API_KEY.isEmpty()){
            Toast.makeText(getApplicationContext(),"Empty API KEY",Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
            return;
        }

        Client client=new Client();
        Service apiService=client.getClient().create(Service.class);

        Call <MovieGetting> call=apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_KEY);

        call.enqueue(new Callback<MovieGetting>() {
            @Override
            public void onResponse(Call<MovieGetting> call, Response<MovieGetting> response) {

               // Log.v("RESPONSE_CALLED", "ON_RESPONSE_CALLED");

                List<Movie> movies=response.body().getResults();

                //if(response.body().getResults()==null){
                  //  Log.v("RESPONSE_CALLED", "ON_RESPONSE_NULL");
               // }
                recyclerView.setAdapter(new MyMovieAdapter(getApplicationContext(),movies));
                recyclerView.smoothScrollToPosition(0);

                if (swipeRefreshLayout.isRefreshing()){
                    swipeRefreshLayout.setRefreshing(false);
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<MovieGetting> call, Throwable t) {
                Toast.makeText(getApplicationContext(),"Empty API KEY",Toast.LENGTH_SHORT).show();
            }
        });

    }catch (Exception e){

        Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
    }






}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.androidSettings:
            return true;
            default:
                return super.onOptionsItemSelected(item);
    }
}

private void selectImage(){
    Intent b=new Intent();
    b.setType("image/*");
    b.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(b,RESULT_OK);
}

}

public class Client {

public  static final String BASE_URL="https://api.themoviedb.org/3/";
public static Retrofit retrofit=null;

public static Retrofit getClient(){
    if (retrofit==null){
        retrofit=new Retrofit.Builder().
                baseUrl(BASE_URL).
                addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

公共接口服务{

@GET("movie/popular")
Call<MovieGetting> getPopularMovies(@Query("api_key") String apiKey);

}

public class Movie {

    @SerializedName("id")
    private Integer id;
    @SerializedName("title")
    private String title;
    @SerializedName("overview")
    private String overView;
    @SerializedName("release_date")
    private String releaseDate;
    @SerializedName("vote_count")
    private Integer voteCount;
    @SerializedName("poster_path")
    private String imagePath;
    @SerializedName("adult")
    private Boolean adult;
    @SerializedName("video")
    private Boolean video;
    @SerializedName("genre_ids")
    private List<Integer>genreIds=new ArrayList<Integer>();
    @SerializedName("vote_average")
    private Double voteAverage;
    @SerializedName("popularity")
    private Double popularity;
    @SerializedName("original_language")
    private String originalLanguage;
    @SerializedName("original_title")
    private String originalTitle;
    @SerializedName("backdrop_path")
    private String backdropPath;

    public String staticUrl="https://image.tmdb.org/t/p/w500";

public Movie(Integer id, String title, String overView, String releaseDate, Integer voteCount,
             String imagePath, Boolean adult, Boolean video, List<Integer> genreIds, Double voteAverage,
             Double popularity, String originalLanguage, String originalTitle, String backdropPath) {
    this.id = id;
    this.title = title;
    this.overView = overView;
    this.releaseDate = releaseDate;
    this.voteCount = voteCount;
    this.imagePath = imagePath;
    this.adult = adult;
    this.video = video;
    this.genreIds = genreIds;
    this.voteAverage = voteAverage;
    this.popularity = popularity;
    this.originalLanguage = originalLanguage;
    this.originalTitle = originalTitle;
    this.backdropPath = backdropPath;
}




public Boolean getAdult() {
    return adult;
}

public void setAdult(Boolean adult) {
    this.adult = adult;
}

public Boolean getVideo() {
    return video;
}

public void setVideo(Boolean video) {
    this.video = video;
}

public List<Integer> getGenreIds() {
    return genreIds;
}

public void setGenreIds(List<Integer> genreIds) {
    this.genreIds = genreIds;
}

public Double getVoteAverage() {
    return voteAverage;
}

public void setVoteAverage(Double voteAverage) {
    this.voteAverage = voteAverage;
}

public Double getPopularity() {
    return popularity;
}

public void setPopularity(Double popularity) {
    this.popularity = popularity;
}

public String getOriginalLanguage() {
    return originalLanguage;
}

public void setOriginalLanguage(String originalLanguage) {
    this.originalLanguage = originalLanguage;
}

public String getOriginalTitle() {
    return originalTitle;
}

public void setOriginalTitle(String originalTitle) {
    this.originalTitle = originalTitle;
}

public String getBackdropPath() {
    return backdropPath;
}

public void setBackdropPath(String backdropPath) {
    this.backdropPath = backdropPath;
}





public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getOverView() {
    return overView;
}

public void setOverView(String overView) {
    this.overView = overView;
}

public String getReleaseDate() {
    return releaseDate;
}

public void setReleaseDate(String releaseDate) {
    this.releaseDate = releaseDate;
}

public int getVoteCount() {
    return voteCount;
}

public void setVoteCount(int voteCount) {
    this.voteCount = voteCount;
}

public String getImagePath() {
    return "https://image.tmdb.org/t/p/w185"+imagePath;
}

public void setImagePath(String imagePath) {
    this.imagePath = imagePath;
}

}

public class MovieGetting {

@SerializedName("page")
@Expose
private int page;
@SerializedName("results")
@Expose
private List<Movie> results;
@SerializedName("total_results")
@Expose
private int totalResults;
@SerializedName("total_pages")
@Expose
private int totalPages;



public int getPage() {
    return page;
}

public void setPage(int page) {
    this.page = page;
}

public List<Movie> getResults() {
    return results;
}

public void setResults(List<Movie> results) {
    this.results = results;
}

public int getTotalResults() {
    return totalResults;
}

public void setTotalResults(int totalResults) {
    this.totalResults = totalResults;
}

public int getTotalPages() {
    return totalPages;
}

public void setTotalPages(int totalPages) {
    this.totalPages = totalPages;
}

} 这是我的错误

E/UploadTask: could not locate file for uploading:https://image.tmdb.org/t/p/w185/AkJQpZp9WoNdj7pLYSj1L0RcMMN.jpg

E / StorageException:发生StorageException。                     发生未知错误,请检查HTTP结果代码和服务器响应的内部异常。                      代码:-13000 Http结果:0 E / StorageException:没有内容提供者:https://image.tmdb.org/t/p/w185/AkJQpZp9WoNdj7pLYSj1L0RcMMN.jpg                     java.io.FileNotFoundException:无内容提供者:https://image.tmdb.org/t/p/w185/AkJQpZp9WoNdj7pLYSj1L0RcMMN.jpg                         在android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1435)                         在android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1286)                         在android.content.ContentResolver.openInputStream(ContentResolver.java:1006)                         com.google.firebase.storage.UploadTask。(未知来源:156)                         位于com.google.firebase.storage.StorageReference.putFile(未知来源:13)                         在com.example.enes.cinemaapp.MyMovieAdapter $ MyViewHolder $ 1.onClick(MyMovieAdapter.java:110)                         在android.view.View.performClick(View.java:6597)                         在android.view.View.performClickInternal(View.java:6574)                         在android.view.View.access $ 3100(View.java:778)                         在android.view.View $ PerformClick.run(View.java:25883)                         在android.os.Handler.handleCallback(Handler.java:873)                         在android.os.Handler.dispatchMessage(Handler.java:99)                         在android.os.Looper.loop(Looper.java:193)                         在android.app.ActivityThread.main(ActivityThread.java:6642)                         在java.lang.reflect.Method.invoke(本机方法)                         在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) E / StorageException:发生StorageException。                     发生未知错误,请检查HTTP结果代码和服务器响应的内部异常。                      代码:-13000 Http结果:0

0 个答案:

没有答案