我是Android开发的新手,这是我的第一个应用程序。 我正在使用片段和适配器来显示选项卡。这是Tab2(Downoad Details)片段代码,在选择Tab时,我正在调用webserive,它从数据库中获取数据并在视图中设置它。一切正常,我在Jason的WS得到回应。我正在解析这个Jason数据并希望在tabLayout中显示。显示我正在获得NPE。
很少有帖子建议使用setUserVisibleHint
,但我无法用此获得所需的输出。
请建议我应该做什么,以便当我选择Tab2(Downoad Details)或滑动到此选项卡时,我的WS被调用,数据将显示在Tab页面上。
以下是我的活动
@SuppressLint("NewApi")
public class DownloadStatusActivity extends FragmentActivity implements ActionBar.TabListener {
ProgressDialog prgDialog1;
TextView errorMsg1;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Download Overview", "Downoad Details" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dwnld_status_activity);
String value1= getIntent().getStringExtra("loccodeselected");
String value2= getIntent().getStringExtra("bccodeselected");
String value3= getIntent().getStringExtra("bmselected");
TextView dwndActlbl = (TextView) findViewById(R.id.dwndActlbl);
dwndActlbl.setText(Html.fromHtml("Download Status for " + value1 +","+value2 +","+value3+ "is as below: </b>"));
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
////passing data to fragement start//
//bundle
Bundle bundle =new Bundle();
bundle.putString("value1",value1);
bundle.putString("value2",value2);
bundle.putString("value3",value3);
DSFragment frag_in = new DSFragment();
DDFragement frag_out = new DDFragement();
frag_in.setArguments(bundle);
frag_out.setArguments(bundle);
mAdapter.addFrag(frag_in," ");
mAdapter.addFrag(frag_out," ");
viewPager.setAdapter(mAdapter);
///////////////
///passing data to fragement end///
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
以下是Fargement代码。
public class DDFragement extends Fragment {
JsonArray arrayFromString=new JsonArray();
private ProgressDialog prgDialog1;
View rootView=null;
private boolean isViewShown = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null ) {
isViewShown = true;
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
} else {
isViewShown = false;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dd_fragement, container, false);
String loc="";
String bc="";String bm="";
if(!isViewShown)
{
if(getArguments()!=null)
{
loc = getArguments().getString("value1");
bc = getArguments().getString("value2");
bm = getArguments().getString("value3");
}
new invokegetDwnldDetailDataAsynTask().execute(loc,bc,bm);
}
return rootView;
}
/*******Implmentation of Async Task******************/
class invokegetDwnldDetailDataAsynTask extends AsyncTask<String, String, JsonArray> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
prgDialog1 = new ProgressDialog(getActivity());
prgDialog1.setMessage("Loading Download Details. Please wait...");
prgDialog1.setIndeterminate(false);
prgDialog1.setCancelable(false);
prgDialog1.show();
}
/**
* getting All products from url
* @return
* */
protected JsonArray doInBackground(String... dwnparams) {
String loc = dwnparams[0];
String bc = dwnparams[1];
String bm = dwnparams[2];
RequestParams reqparams = new RequestParams();
reqparams.put("loccodeselected", loc);
reqparams.put("bccodeselected", bc);
reqparams.put("bmselected", bm);
// Show Progress Dialog
//prgDialog1.show();
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:8081/useraccount/queries/fetchdwnDetailStatus",reqparams ,new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response code '200'
@SuppressWarnings("unused")
@Override
public void onSuccess(String response) {
// Hide Progress Dialog
// prgDialog1.hide();
try {
// JSON Object
JSONObject jObj = new JSONObject(response);
if(jObj!=null)
{
System.out.println("RESPONSE1===>"+jObj.getString("downloadDetails"));
JsonParser jsonParser = new JsonParser();
arrayFromString = jsonParser.parse((String) jObj.getString("downloadDetails")).getAsJsonArray();
System.out.println("RESPONSE2===>"+arrayFromString);
}
// Else display error message
else{
// errorMsg1.setText(jObj.getString("error_msg"));
Toast.makeText(getActivity().getApplicationContext(), "ERROR SOME", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
// When the response returned by REST has Http response code other than '200'
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog
// prgDialog1.hide();
// When Http response code is '404'
if(statusCode == 404){
Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if(statusCode == 500){
Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else{
Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
return arrayFromString;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JsonArray arrayFromString1) {
// dismiss the dialog after getting all products
prgDialog1.dismiss();
/**
* Updating parsed JSON data into ListView
* */
if (arrayFromString1 != null) {
int count=0;
TableLayout tl;
tl = (TableLayout) rootView.findViewById(R.id.ddfragment_table);
for (int i=0;i<arrayFromString.size();i++){
// System.out.println("array==>"+arrayFromString.get(i).toString());
TableRow tr1 = new TableRow(getActivity());
if(count%2!=0) tr1.setBackgroundColor(Color.LTGRAY);
tr1.setId(i);
// tr.setBackgroundResource(Color.MAGENTA);
tr1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//TEXTVIEWS********
TextView tv1 = new TextView(getActivity());
String textLabel="";
tv1.setText(textLabel ); //seetting first response in cell
tv1.setId(i);
tv1.setTextColor(Color.BLACK);
tv1.setTextSize(15);
tv1.setPadding(5, 5, 5, 5);
tr1.addView(tv1);
tl.addView(tr1, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
count++;
}
}
}
}
}
错误是行tl = (TableLayout) rootView.findViewById(R.id.ddfragment_table)
上的onpostExecute();
错误:NullPointerException ..尝试在null obj refrence上调用虚方法..findViewbyId(int)
答案 0 :(得分:1)
片段中的oncreateView中的rootView与类成员的rootview不同。替换:
View rootView = inflater.inflate(R.layout.dd_fragement, container, false);
使用:
rootView = inflater.inflate(R.layout.dd_fragement, container, false);
顺便说一句,这就是为什么最好这样命名类成员:查看mRootView;