MainActivity无法识别我的xml文件中的gridview
这是mainActivity onCreate():
protected void onCreate(Bundle savedInstanceState) {
mContext = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMovieFragment = new MovieFragment();
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, mMovieFragment)
.commit();
}
if(this == null){
Log.v(null, "THIS is empty");
}
GridView gridView = (GridView) findViewById(R.id.gridview);
if(gridView == null){
Log.v(null, "GridView is empty");
}
/*gridView.setAdapter(new ImageAdapter(this, mMovieFragment.getArrayImages()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});*/
}
然后我有2个xml文件,activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" />
和fragment_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
tools:context=".MainActivity$MovieFragment">
</GridView>
gridView = findViewById(R.id.gridview)为空
MovieFragment.java:
public class MovieFragment extends Fragment{
public ArrayAdapter<String> mMovieAdapter;
public String[] mArrayImages;
public MovieFragment(){
mArrayImages = new String[20];
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
new FetchMoviesTask().execute("http://api.themoviedb.org/3/movie/popular?api_key=37068e0a72b2cc1751b4246899923ba7");
}
public String[] getArrayImages() {
return mArrayImages;
}
public class FetchMoviesTask extends AsyncTask<String, Void, Void> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private Void getMovieImagesFromJson(String movieJSONstr) throws JSONException {
final String OWM_RESULTS = "results";
final String OWM_POSTERPATH = "poster_path";
JSONObject movieJson = new JSONObject(movieJSONstr);
JSONArray movieArray = movieJson.getJSONArray(OWM_RESULTS);
Log.v("SIZE MOVIE ARRAY: ", Integer.toString(movieArray.length()));
for(int i = 0; i < movieArray.length(); i++) {
JSONObject movieObj = movieArray.getJSONObject(i);
mArrayImages[i] = movieObj.getString(OWM_POSTERPATH);
Log.v("String "+i+":", mArrayImages[i]);
}
return null;
}
@Override
protected Void doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJSONstr = null;
try{
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream == null){
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if(buffer.length() == 0){
movieJSONstr = null;
}
movieJSONstr = buffer.toString();
Log.v("URLoutput: ", movieJSONstr);
} 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("MovieFragment", "Error closing stream", e);
}
}
}
try{
return getMovieImagesFromJson(movieJSONstr);
}catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
}
}
答案 0 :(得分:0)
你应该在MovieFragment的onCreateView方法中获得gridview引用
答案 1 :(得分:0)
问题在于片段添加。
来自https://developer.android.com/reference/android/app/FragmentTransaction.html#commit()
提交不会立即执行,稍后会完成
在您查找网格时,片段尚未附加,因此此时网格不存在
在检索视图之前,您必须等待该片段真正附加
答案 2 :(得分:0)
对于findViewById
来电,您需要对片段xml进行充气,然后使用返回的视图“查找”您的观点。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView grid = rootView.findViewById(R.id.gridview);
new FetchMoviesTask().execute("http://api.themoviedb.org/3/movie/popular?api_key=37068e0a72b2cc1751b4246899923ba7");
}
您还可以通过让onPostExecute
返回字符串数组
doInBackground
中设置网格适配器
public class FetchMoviesTask extends AsyncTask<String, Void, String[]> {
@Override
protected String[] doInBackground(String... params) {
//get your string array.
//mArrayImages = assign the value
return mArrayImages;
}
@Override
protected onPostExecute(String[] strings) {
gridView.setAdapter(new ImageAdapter(getActivity(), strings);
}