- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试从电影数据库中获取有关电影的数据。然后在我的布局中使用 gridview 我想在我的设备上显示它。我通过使用 ArrayAdapter 来做到这一点。我只想在网格中显示电影的名称。但我不断收到“java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String java.lang.Object.toString()'”错误。我的代码如下:
public class MainActivityFragment extends Fragment {
ArrayAdapter<String> mMovieAdapter;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mMovieAdapter = new ArrayAdapter<String>(getActivity(), R.layout.item_movies, R.id.image_view_movie, new ArrayList<String>());
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView listView = (GridView) rootView.findViewById(R.id.gridview_movies);
listView.setAdapter(mMovieAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), DetailActivity.class);
String forecast = mMovieAdapter.getItem(i);
intent.putExtra(Intent.EXTRA_TEXT, forecast);
startActivity(intent);
/*
* Context context = getActivity(); String forecast =
* mForecastAdapter.getItem(i); int duration =
* Toast.LENGTH_SHORT; Toast.makeText(context, forecast,
* duration).show();
*/
}
});
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.moviefragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
// TO update weather when activity starts
@Override
public void onStart() {
super.onStart();
updateMovie();
}
private void updateMovie() {
FetchMovieTask movieTask = new FetchMovieTask();
movieTask.execute();
}
class FetchMovieTask extends AsyncTask<Void, Void, String[]> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
@Override
protected String[] doInBackground(Void... params) {
/* if(params.length == 0) { return null; } */
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page,
// at
// http://openweathermap.org/API#forecast
final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String QUERY_PARAM = "sort_by";
final String KEY_PARAM = "&api_key";
// Using UriBuilder
Uri builtUri = Uri.parse(BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, "popularity.desc").appendQueryParameter(KEY_PARAM, "c20129fdf73b5df3ab44548ad7f73586").build();
URL url = new URL(builtUri.toString());
// Printing the url in the log
// Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it
// won't affect parsing)
// But it does make debugging a *lot* easier if you print
// out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's
// no point in attemping
// to parse it.
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 {
return getMovieDataFromJson(movieJsonStr);
} catch (JSONException j) {
Log.e(LOG_TAG, "JSON Error", j);
}
return null;
}
private String[] getMovieDataFromJson(String forecastJsonStr) throws JSONException {
String title;
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
String[] resultStrs = new String[100];
for (int i = 0; i < movieArray.length(); i++) {
// Get the JSON object representing the day
JSONObject movie = movieArray.getJSONObject(i);
title = movie.getString("original_title");
resultStrs[i] = title;
Log.v(LOG_TAG, resultStrs[i]);
}
/*
* for (String s : resultStrs) { Log.v(LOG_TAG, "Forecast entry: " +
* s); }
*/
return resultStrs;
}
@Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
mMovieAdapter.clear();
mMovieAdapter.addAll(strings);
}
}
}
我的错误日志是:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.GridView.makeAndAddView(GridView.java:1433)
at android.widget.GridView.makeRow(GridView.java:361)
at android.widget.GridView.fillDown(GridView.java:302)
at android.widget.GridView.fillGap(GridView.java:262)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4968)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4512)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:549)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
最佳答案
我怀疑这是 Blackbelt 在评论中也提到的错误
String[] resultStrs = new String[100];
应该是
String[] resultStrs = new String[movieArray.length()];
因为您现在对 GridView 说您有 总是 100 部电影,但是当电影少于 100 部时,您将向 GridView 提供空元素
关于java.lang.NullPointerException : Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference in GridView 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31109836/
在 Tomcat 6/Ubuntu 12.04 上启动 Grails 2.1.0 应用程序时出现以下错误。 Error 500 - Internal Server Error. groovy.lang
在运行 Storm 拓扑时,我收到此错误。拓扑完美运行 5 分钟,没有任何错误,然后失败。我正在使用 Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS as 300 sec i
我有一个 jsp 代码在其中一台机器上运行良好。但是当我复制到另一台机器时,我得到了这个 no such method found 异常。我是 Spring 的新手。有人可以解释我错过了什么吗? 以下
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我的代码在下面给出了一个错误; Exception in thread "main" java.lang.NoSuchMethodError: com/myApp/Client.cypherCBC(L
我正在尝试一个 Restful web 服务示例,所以当我要访问 url 时,我遇到了异常 java.lang.NoSuchMethodError: jersey.repackaged.com.goo
我正在将一个 Spring web 项目转换为一个 Maven 项目,但我收到了这个错误: java.lang.NoSuchMethodError: org.jboss.logging.Logger.
在我的项目中,我有一个像这样的枚举: public enum MyEnum { FIRST(1), SECOND(2); private int value; private MyEnum(int v
我创建了这个简单的示例,用于读取 Linux 正常运行时间: public String getMachineUptime() throws IOException { String[] di
我正在使用 Eclipse,并且正在使用 Java。我的目标是使用 bogoSort 方法对 vector 进行排序在一个 vector (vectorExample)中适应我的 vector 类型,
我正在运行以下查询。它显示一条错误消息。如何解决这个错误? ListrouteList=null; List companyList = session.createS
我有以下模型类: @Entity @Table(name="user_content") @org.hibernate.annotations.NamedQueries({ @org.
我有那个错误。这是我的代码: GmailSettingsService service = new GmailSettingsService(APPLICATION_NAME, DOMAIN_NAME
实际上我在执行我的java程序时遇到了下面提到的错误 Exception in thread "pool-1-thread-1" java.lang.ClassCastException: jav
java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.String 我在以下代码中遇到此异常: Strin
我正在尝试从 linkedhashset 中检索随机元素。下面是我的代码,但它每次都给我异常。 private static void generateRandomUserId(Set userIds
我已经完成了 Android 中的代码: List spinnerArray = new ArrayList(); for (int i = 0; i item = (LinkedTreeMap)
这个问题已经有答案了: Explanation of ClassCastException in Java (12 个回答) 已关闭 6 年前。 我已经编写了 java 到 Json 的代码,同时从页
这个问题在这里已经有了答案: ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn (4 个答案) 关闭 6 年前
我在运行时遇到问题来编译这段代码,这给我一个错误,java.lang.Integer 无法转换为 Java.lang.Double。如果有人帮助我更正此代码,我将非常高兴 double x; pu
我是一名优秀的程序员,十分优秀!