Issue
I am new to android development and this is my first application. I am using Fragments and Adapters to display the Tabs. This is Tab2 (Downoad Details) fragment code, in which on select of Tab, I am calling a webserive which gets the data from database and sets it in the view. Everything is working and I am getting response from WS in Jason. I am parsing this Jason data and wants to display in tabLayout. While display I am getting NPE.
Few post have suggested to use setUserVisibleHint
but I am not able to achieve desired output with this.
Please suggest what should I do so that when I select the Tab2 (Downoad Details) or swipes to this Tab, my WS gets called and data would be displayed on the Tab page.
Below is My Activity
@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) {
}
}
Below is the Fargement code.
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++;
}
}
}
}
}
The error is onpostExecute() at line tl = (TableLayout) rootView.findViewById(R.id.ddfragment_table)
;
Error: NullPointerException.. Attempet to invoke virtual method..findViewbyId(int) on a null obj refrence
Solution
The rootView in Your oncreateView in the fragment is not the same rootview that is class member. Replace:
View rootView = inflater.inflate(R.layout.dd_fragement, container, false);
with:
rootView = inflater.inflate(R.layout.dd_fragement, container, false);
By the way, thats why it is preferable to name class members like this: View mRootView;
Answered By - Pavel B.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.