Java Android上使用Gson解析Json时的NullPointerException
我对StackOverflow有点陌生。我做了大量的搜索,但似乎找不到一个能帮助我解决具体问题的答案 我正在尝试解析这个特定的Json: 我是Json新手,我正在使用Google Gson解析它。它编译得很好。然而,我的Java类似乎并没有被Json中的正确信息填充(我一直得到NullPointerExceptions),这可能是因为我对Json缺乏了解。在这段代码中,NullPointerException特别来自我的主要活动中的Java Android上使用Gson解析Json时的NullPointerException,java,android,json,nullpointerexception,gson,Java,Android,Json,Nullpointerexception,Gson,我对StackOverflow有点陌生。我做了大量的搜索,但似乎找不到一个能帮助我解决具体问题的答案 我正在尝试解析这个特定的Json: 我是Json新手,我正在使用Google Gson解析它。它编译得很好。然而,我的Java类似乎并没有被Json中的正确信息填充(我一直得到NullPointerExceptions),这可能是因为我对Json缺乏了解。在这段代码中,NullPointerException特别来自我的主要活动中的final int N=response.results.siz
final int N=response.results.size()
行
我的主要活动:
public class MainActivity extends ActionBarActivity {
public static InputStream json;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
ResponseData response = new ResponseData();
new JsonAsync(this, response).execute();
final int N = response.results.size();
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView textView = new TextView(this);
textView.setText("Image Name:" + response.results.get(i).titleNoFormatting);
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.container);
// add the textview to the linearlayout
myLayout.addView(textView);
// save a reference to the textview for later
myTextViews[i] = textView;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
/**
* Async Task for Grabbing Json Data
*
*/
private static class JsonAsync extends AsyncTask<Void, Void, ResponseData> {
private String text;
public InputStream stream;
private Activity activity;
private ResponseData response;
public JsonAsync(Activity activity, ResponseData response) {
this.activity = activity;
this.response = response;
}
@Override
protected ResponseData doInBackground(Void...params) {
try {
URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=fuzzy%20monkey%27");
InputStream stream = url.openStream();
Gson gson = new Gson();
String json = convertStreamToString(stream);
ResponseData response = gson.fromJson(json, ResponseData.class);
return response;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(ResponseData result) {
super.onPostExecute(result);
}
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
}
我的回答是:
public class ResponseData {
public List<Result> results;
}
公共类响应数据{
公开名单结果;
}
我从非常基本的开始,只是从Json中提取一些值放到类中,并尝试在动态创建的TextView中显示图像搜索的名称(基于搜索计数)。我已经在清单中声明了网络权限,所以我认为这不是网络问题。任何帮助都将不胜感激 您应该将所有依赖于asynctask的代码放在onPostExecute中
@Override
protected void onPostExecute(ResponseData result) {
final int N = result.results.size();
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView textView = new TextView(MainActivity.this);
textView.setText("Image Name:" + result.results.get(i).titleNoFormatting);
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.container);
// add the textview to the linearlayout
myLayout.addView(textView);
// save a reference to the textview for later
myTextViews[i] = textView;
}
super.onPostExecute(result);
}
及
如果再次得到null,可能是因为类“ResponseData”的名称和json中的标记“ResponseData”不相同(第一个字母) 当我这样做时,我似乎找不到一种方法来获取应用程序的上下文来创建textview。我编辑了我的答案。您可以使用MainActivity.this或activity而不是“this”。不幸的是,在
final int N=response.results.size()上,我的结果列表似乎仍然为空代码>行。我不明白为什么它不能正确解析。我已经按照你的建议进行了调整。cm0011,我编辑了我的代码,现在应该可以工作了。只需将result而不是response.results放入onPostExecute。我很抱歉给你添麻烦,但是你的代码把我弄糊涂了。如果查看我的Responsedata类,它所包含的只是结果对象列表的初始化。但是,您所说的“结果”是onPostExecute中参数的Responsedata对象本身,因此调用result.size()是无效的。基于我想要解析的json,我构建类的方式是否不正确?Json来源:
@Override
protected void onPostExecute(ResponseData result) {
final int N = result.results.size();
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView textView = new TextView(MainActivity.this);
textView.setText("Image Name:" + result.results.get(i).titleNoFormatting);
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.container);
// add the textview to the linearlayout
myLayout.addView(textView);
// save a reference to the textview for later
myTextViews[i] = textView;
}
super.onPostExecute(result);
}
final int N = result.results.size();
textView.setText("Image Name:" + result.results.get(i).titleNoFormatting);