有没有什么办法让我的应用程序加载所有那些对自己和没有我不必旋转设备或轻扫屏幕上看到的图片?我注意到它适用于某些尺寸而不适用于其他尺寸(但我需要现在的尺寸较大)。另外,如果我没有两套占位符图像(不知道为什么),则应用程序不起作用。提前致谢!的GridView不会显示图像
这里是我的形象适配器:
package tk.talcharnes.popularmovies;
import android.content.Context; import android.view.View; import
android.view.ViewGroup; import android.widget.BaseAdapter; import
android.widget.GridView; import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/** * Created by Tal on 2/24/2016. */ public class ImageAdapter
extends BaseAdapter { // private static String[] desc = new
String[9];
private static String[] desc = {
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg"
};
private static String[] imageArray = getDesc();
private Context mContext;
//private String[] asc = new String[PostersFragment.getMovieModelListLength()];
private static String[] asc = {};
public ImageAdapter(){
}
public int getCount() {
try{
return imageArray.length;}
catch(NullPointerException e){
e.printStackTrace();
return 0;
}
}
public ImageAdapter(Context c) {
mContext = c;
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return imageArray[position];
}
// create a new ImageView for each item referenced by the Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
int pixels = (int) (mContext.getResources().getDisplayMetrics().density + 0.5f);
imageView.setLayoutParams(new GridView.LayoutParams(185*pixels, 277*pixels));
convertView = imageView;
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(imageArray[position])
.placeholder(R.drawable.sample_0)
// .resize(185,277)
.into(imageView);
//imageView.setImageResource(Integer.parseInt(imageArray[position]));
return imageView;
}
public static String[] getAsc() {
return asc;
}
public static void setAsc(String[] asc) {
ImageAdapter.asc = asc;
}
public static String[] getDesc() {
return desc;
}
public static void setImageArray(String[] arrayName){
imageArray = arrayName;
} }
这里是我的片段:
package tk.talcharnes.popularmovies;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class PostersFragment extends Fragment {
private static List<MovieModel> movieModelList;
private static int movieModelListLength;
GridView gridView;
private String done = null;
ImageAdapter adapter;
public PostersFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
FetchPostersTask fetchPostersTask = (FetchPostersTask) new FetchPostersTask().execute();
// should find gridview on the view which you are creating
gridView = (GridView) view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getContext()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getContext(), "You clicked " + movieModelList.get(position).getTitle() ,
Toast.LENGTH_SHORT).show();
}
});
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private final String BASE_URL = "https://api.themoviedb.org/3/";
private String middle_section = "discover/movie?sort_by=popularity.desc&api_key=";
private String jSonUrl = BASE_URL + middle_section + BuildConfig.MOVIE_DB_API_KEY;
//Get movie posters and data
public class FetchPostersTask extends AsyncTask<Void,Void,Void> {
private final String LOG_TAG = FetchPostersTask.class.getSimpleName();
//will contain raw Json data
String posterJsonString = null;
public Void parseMovieJson()
throws JSONException{
JSONObject jsonParentObject = new JSONObject(posterJsonString);
JSONArray movieJSonArray = jsonParentObject.getJSONArray("results");
movieModelList = new ArrayList<>();
for(int i = 0; i < movieJSonArray.length(); i++){
JSONObject movieJsonObject = movieJSonArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setTitle(movieJsonObject.getString("title"));
movieModel.setOverview(movieJsonObject.getString("overview"));
movieModel.setPoster_path(movieJsonObject.getString("poster_path"));
movieModel.setRelease_date(movieJsonObject.getString("release_date"));
movieModel.setVote_average(movieJsonObject.getString("vote_average"));
movieModelListLength++;
movieModelList.add(movieModel);
}
return null;
}
@Override
protected Void doInBackground(Void ...params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//
//will contain raw Json data
// String posterJsonString = null;
try{
//open connection to api
URL url = new URL(jSonUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//read input into string
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream == null){
//nothing else to do in this case
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine())!= null){
buffer.append(line + "\n");
}
if(buffer.length()==0){
//nothing here, don't parse
return null;
}
posterJsonString = buffer.toString();
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
Log.e(LOG_TAG, "Error", e);
return null;
}
finally {
if(urlConnection != null){
urlConnection.disconnect();
}
if(reader != null){
try{
reader.close();
}
catch (final IOException e){
Log.e(LOG_TAG,"Error closing stream", e);
}
}
}
try{
parseMovieJson();;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//ImageAdapter.setAsc(movieModelList.);
String[] asc = new String[movieModelList.size()];
for(int i = 0; i < asc.length; i++){
asc[i]=(getMovieModelList().get(i).getPoster_path());
//ImageAdapter.setAsc(asc);
}
adapter.setImageArray(asc);
}
}
public static List<MovieModel> getMovieModelList(){
return movieModelList;
}
public static int getMovieModelListLength(){
return movieModelListLength;
}
}
我相信这最后一块应该是所需的代码最后一位,如果在所有这就是布局:
<FrameLayout 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"
tools:context=".PostersFragment">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:gravity="center"
android:horizontalSpacing="0dp"
android:verticalSpacing="0dp"
android:layout_margin="0dp"
/>
</FrameLayout>
对不起,如果代码有点笨重我是新的程序员,并已注释掉了几件事只是为了确保我以后可以使用它们。在此先感谢再次:d
更新:当我试图把代码:adapter.notifyDataSetChange();在adapter.setImageArray(asc)之后;我得到这个错误代码:
FATAL EXCEPTION: main
Process: tk.talcharnes.popularmovies, PID: 6558
java.lang.NullPointerException: Attempt to invoke virtual method 'void tk.talcharnes.popularmovies.ImageAdapter.notifyDataSetChanged()' on a null object reference
at tk.talcharnes.popularmovies.PostersFragment$FetchPostersTask.onPostExecute(PostersFragment.java:171)
at tk.talcharnes.popularmovies.PostersFragment$FetchPostersTask.onPostExecute(PostersFragment.java:70)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5290)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
我确实得到了类似的错误代码以前这是一个数组我有,当我设置阵列我点名降序排列不知何故固定空指针错误,和然后我把postersfragment改成immagearray,当asynctask完成后,就成为asc数组。不知道为什么这样做会阻止这个错误并且修复它。
应用程序崩溃,当我做到这一点:/又为什么会更新在某些图像大小而不是其他人?太奇怪了! –
什么是错误? –
感谢您的帮助,我只是在帖子的更新部分添加了错误和简要说明。 :D –