我有一个带片段的viewpager。我想将JSON数据显示在我片段中的textview中。有人可以告诉我如何。我是初学者。
这是我的代码。每次我在手机上运行它都会崩溃。日志说我的文本视图中有一个空对象引用。
此代码来自我正在观看的教程。我只是在我的片段上应用它但它不起作用。帮帮我谢谢。
HttpResponse httpResponse;
TextView textView;
JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
// Adding HTTP Server URL to string variable.
String HttpURL =
"http://192.168.1***/android_login_api/topic_conservation.php";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
textView = (TextView)getActivity().findViewById(R.id.textViewC);
progressBar = (ProgressBar)getActivity().findViewById(R.id.progressBar);
// Showing progress bar on button click.
progressBar.setVisibility(View.VISIBLE);
//Calling GetDataFromServerIntoTextView method to Set JSon MySQL data into TextView.
new GetDataFromServerIntoTextView(getActivity()).execute();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_eco_conservation, container, false);
}
// Declaring GetDataFromServerIntoTextView method with AsyncTask.
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
// Declaring CONTEXT.
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
// Passing string holder variable to JSONArray.
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
// Adding JSOn string to textview after done loading.
textView.setText(jsonObject.getString("topicdesc"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hiding progress bar after done loading TextView.
progressBar.setVisibility(View.GONE);
}
}
答案 0 :(得分:0)
试试这个,
View view=inflater.inflate(R.layout.fragment_eco_converstion,container,false);
textview=(TextView)view.findViewById(R.id.text_view);
return view;