I find it hard to use Fragment because I still don't have enough knowledge about it, so I tried to create my project using an Activity class first, but I still have to convert it into fragment cause I was using a left nav. I need someone's guide because I can't seem to find anything on the internet
Everything turns out to be fine but when I change this section of the code
new ReportsTab.GetHttpResponse(ReportsTab.this).execute();
It would display an error "Gethttpresponse cannot be applied"
This is my Activity Class
public class Reports extends AppCompatActivity {
ListView ReportsListView;
ProgressBar progressBar;
Button status;
String HttpUrl = "http://................../reports_app2.php";
List<String> IdList = new ArrayList<>();
AlertDialog alertDialog;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reports);
ReportsListView = (ListView)findViewById(R.id.listview1);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
new GetHttpResponse(Reports.this).execute();
//Adding ListView Item click Listener.
ReportsListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(Reports.this,MainActivity.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
finish();
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nv);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupDrawerContent(nvDrawer);
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<ReportsJava> ReportsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
ReportsJava reports;
ReportsList = new ArrayList<ReportsJava>();
for(int i=0; i<jsonArray.length(); i++)
{
reports = new ReportsJava();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
if("0".equals(jsonObject.getString("status").toString()))
{
reports.LightpostStatus = "BLACKOUT";
}
else if("1".equals(jsonObject.getString("status").toString()))
{
reports.LightpostStatus = "FIXED";
}
else if("2".equals(jsonObject.getString("status").toString()))
{
reports.LightpostStatus = "DEFECTIVE";
}
reports.LightpostName = jsonObject.getString("lightpost_code").toString();
reports.LightpostAddress = jsonObject.getString("lightpost_location").toString();
reports.LightpostTime = jsonObject.getString("lightpost_time").toString();
ReportsList.add(reports);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
ReportsListView.setVisibility(View.VISIBLE);
ReportsListAdapterClass adapter = new ReportsListAdapterClass(ReportsList, context);
ReportsListView.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menuLogout:
SharedPrefManager.getInstance(this).logout();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.menuSettings:
Toast.makeText(this, "You clicked settings", Toast.LENGTH_LONG).show();
break;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
public void selectItemDrawer(MenuItem menuItem){
Fragment myFragment = null;
Class fragmentClass;
switch (menuItem.getItemId()){
case R.id.viewlights:
fragmentClass= ViewLightpost.class;
break;
case R.id.viewreports:
fragmentClass= ReportsTab.class;
break;
case R.id.viewaccount:
fragmentClass= EditAccount.class;
break;
case R.id.viewabout:
fragmentClass= AboutTab.class;
break;
default:
fragmentClass= ViewLightpost.class;
}
try{
myFragment=(Fragment) fragmentClass.newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
}
private void setupDrawerContent(NavigationView navigationView){
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return false;
}
});
}
}
new ReportsTab.GetHttpResponse(ReportsTab.this.getActivity()).execute();
Get the activity from the fragment instance.
Related
So I have the action bar back button which returns me from an activity to my main activity. The problem I have is that it calls loadData() (which loads data from an API) when you press the action bar back button.
If I press the back button on the device (the button beside the home button) then I will be brought back to the previous view (the mainactivity) and won't have to call the API again.
So I'm trying to find a way to mimic the physical back button as an action bar widget.
I don't want MainActivity's code to be called again as it will execute another API call (I can only have 5 per minute) and it is also slower. I just want it to go back to the view I was just at.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<ListItem> listItems;
private String defaultQuery = "ham";
private String builtURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadData(defaultQuery);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
listItems.clear();
loadData(query);
(menu.findItem(R.id.action_search)).collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setIconified(false);
return true;
}
public void loadData(String query) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading recipes...");
progressDialog.show();
Log.d("q", "loadData: " + query);
builtURL = buildURL(query);
StringRequest request = new StringRequest(Request.Method.GET,
builtURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject obj = new JSONObject(response);
JSONArray hits = obj.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject a = hits.getJSONObject(i);
JSONObject recipe = a.getJSONObject("recipe");
String ingredients = recipe.getString("ingredientLines");
ingredients = ingredients.replace("[", "");
ingredients = ingredients.replace("]", "");
ingredients = ingredients.replace("\"", "");
ingredients = ingredients.replace("\\", "");
ingredients = ingredients.replace(",", "\n");
ListItem item = new ListItem(
recipe.getString("label"),
recipe.getString("source"),
recipe.getString("image"),
ingredients,
recipe.getString("url")
);
listItems.add(item);
}
adapter = new Adapter(listItems, getApplicationContext(), builtURL);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(request);
}
private String buildURL(String query) {
Log.d("q", "buildURL: " + query);
Uri.Builder builder = new Uri.Builder();
//url built here but I removed it because it shows API key etc.
String urlToSend = builder.build().toString();
//debugging purposes to show the url created
Log.d("url", "doInBackground: " + urlToSend);
return urlToSend;
}
#Override
public boolean onNavigateUp(){
finish();
return true;
}
This is the activity that I'm coming from.
public class recipe_view extends AppCompatActivity {
ImageView ivRecipeImage;
TextView tvRecipeName;
TextView tvRecipeCreator;
TextView tvRecipeIngredients;
String url;
Integer pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_view);
Bundle data = getIntent().getExtras();
ArrayList<ListItem> list = data.getParcelableArrayList("list");
pos = data.getInt("pos");
for (int i = 0; i < list.size() ; i++) {
System.out.println(list.get(i));
System.out.println(pos);
}
ivRecipeImage = findViewById(R.id.recipeImage);
tvRecipeName = findViewById(R.id.recipeName);
tvRecipeCreator = findViewById(R.id.recipeCreator);
tvRecipeIngredients = findViewById(R.id.ingredients);
tvRecipeName.setText(list.get(pos).getTitle());
tvRecipeCreator.setText(list.get(pos).getAuthor());
Picasso.with(getApplicationContext())
.load(list.get(pos).getImageUrl())
.centerCrop()
.fit()
.into(ivRecipeImage);
tvRecipeIngredients.setText(list.get(pos).getListOfIngredients());
url = list.get(pos).getRecipeUrl();
final Button button = findViewById(R.id.bViewInstructions);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
}
});
}
}
In your manifest xml
set
<activity
android:name=".your_activity"
android:label="#string/title_activity_sign_up"
android:parentActivityName=".whateveractivity"
android:screenOrientation="portrait" >
</activity>
then in code
#Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
// Otherwise defer to system default behavior.
super.onBackPressed();
}
To elaborate what you are doing is overriding the onbackpressed hardware button.
Also make your parent activity's launchmode singleInstance.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
finish();
}
});
My app contains two activities and First activity load data from web using volley and after successful loading of data start second activity, the second activity contains dynamic tabs and view pager. My issues is when i press back button from second activity does not finish the activity but restart second activity again and it will finish when press ten times of back button that is my tabs count is 10, any one can help me to solve this issue..
First Actvity, SplashActivity.java
public class SplashActivity extends AppCompatActivity {
private static final String HOME_URL = "http://sampleurl.com/beta/Mobile_controller";
public static ArrayList<CategoryModel> categories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
getCategories();
}
private void getCategories() {
categories = new ArrayList<>();
StringRequest request = new StringRequest(Request.Method.POST, HOME_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONArray categoryJsonArray = object.getJSONArray("category");
for (int i = 0; i < categoryJsonArray.length(); i++) {
CategoryModel model = new CategoryModel();
JSONObject cat = categoryJsonArray.getJSONObject(i);
model.setCategoryID(cat.getString("category_id"));
model.setCategoryName(cat.getString("category_name"));
categories.add(model);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), String.valueOf("error : " + error.getMessage()),Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(SplashActivity.this);
queue.add(request);
}
}
Second Activity MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
MediaController mediaController;
private ArrayList<CategoryModel> categoryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.tb_home);
setSupportActionBar(toolbar);
categoryList = SplashActivity.categories;
NavigationView navDrawer = (NavigationView) findViewById(R.id.navigation_home);
navDrawer.setNavigationItemSelectedListener(this);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout_home);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.app_name, R.string.app_name);
drawer.setDrawerListener(toggle);
toggle.syncState();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tbl_home);
for (int i = 0; i < categoryList.size(); i++) {
tabLayout.addTab(tabLayout.newTab().setText(categoryList.get(i).getCategoryName()));
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_home_content);
SwipingTabsAdapter swipingTabsAdapter = new SwipingTabsAdapter(getSupportFragmentManager(), categoryList, tabLayout.getTabCount());
viewPager.setAdapter(swipingTabsAdapter);
viewPager.setOffscreenPageLimit(3);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_option_home, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_option_search).getActionView();
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(getApplicationContext(), newText, Toast.LENGTH_SHORT).show();
return true;
}
});
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_option_account:
Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
}
View pager Adapter
public class SwipingTabsAdapter extends FragmentStatePagerAdapter {
private int tabs;
private ArrayList<CategoryModel> categoryList;
public SwipingTabsAdapter(FragmentManager fm, ArrayList<CategoryModel> categories, int tabCounts) {
super(fm);
this.categoryList = categories;
this.tabs = tabCounts;
}
#Override
public Fragment getItem(int position) {
/*switch (position) {
case 0:
return new NewsCategoriesFragment();
case 1:
return new NewsCategoriesFragment();
default:
return new NewsCategoriesFragment();
}*/
return NewsCategoriesFragment.newInstance(Integer.parseInt(categoryList.get(position).getCategoryID()));
}
#Override
public int getCount() {
return tabs;
}
}
My fragment
public class NewsCategoriesFragment extends Fragment {
private ArrayList<SliderModel> sliderNews;
private SliderNewsAdapter sliderNewsAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_new_categories, container, false);
Button button = (Button) view.findViewById(R.id.button);
Bundle bundle = getArguments();
int id = bundle.getInt("id");
getNews(id);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.vp_slider_news);
sliderNewsAdapter = new SliderNewsAdapter(getContext(), sliderNews);
viewPager.setAdapter(sliderNewsAdapter);
button.setText(String.valueOf(id));
return view;
}
public static Fragment newInstance(int id) {
NewsCategoriesFragment fragment = new NewsCategoriesFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
return fragment;
}
private void getNews(final int categoryId) {
sliderNews = new ArrayList<>();
StringRequest request = new StringRequest(Request.Method.POST, NEWS_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONArray sliderNewsJsonArray = object.getJSONArray("slider_news");
for (int i = 0; i < sliderNewsJsonArray.length(); i++) {
SliderModel model = new SliderModel();
JSONObject data = sliderNewsJsonArray.getJSONObject(i);
model.setNewsThumbImg(data.getString("news_thump_image"));
sliderNews.add(model);
}
sliderNewsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "JSON Exception", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), String.valueOf("error "+ error.getMessage()), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("id", String.valueOf(categoryId));
return data;
}
};
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(request);
}
}
Problem is you put your startActivity inside the for loop, put start activity after for loop in Splashactiivty getCategories, it will work fine
Change this,
try {
JSONObject object = new JSONObject(response);
JSONArray categoryJsonArray = object.getJSONArray("category");
for (int i = 0; i < categoryJsonArray.length(); i++) {
CategoryModel model = new CategoryModel();
JSONObject cat = categoryJsonArray.getJSONObject(i);
model.setCategoryID(cat.getString("category_id"));
model.setCategoryName(cat.getString("category_name"));
categories.add(model);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
to
try {
JSONObject object = new JSONObject(response);
JSONArray categoryJsonArray = object.getJSONArray("category");
for (int i = 0; i < categoryJsonArray.length(); i++) {
CategoryModel model = new CategoryModel();
JSONObject cat = categoryJsonArray.getJSONObject(i);
model.setCategoryID(cat.getString("category_id"));
model.setCategoryName(cat.getString("category_name"));
categories.add(model);
}
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
in second activity override as
#Override
public void onBackPressed() {
finish();
}
You don't really need to Launch a intent to previous activity. Android has something called Back Stack which contains previous launched activities in a stack data structure.You could have just overridden onBackPressed() method to get it done.
#Override
public void onBackPressed(){
this.finish();
}
Also note launching intent as NewTask helps you to get away from existing backstack and has its own backstack.
I want to make a POS app. In this app, I need to print a receipt, but I have a problem with the bluetooth connection.
In this code, I want to set the printer device that I use in my fragment. I want the bluetooth to stay connected even though I move to another fragment. I put the code in my MainActivity, but the problem is every time I move to another fragment, mService is always null. So I couldn't connect to the device.
Please help me. Thanks in advance.
MainActivity.Java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "MainActivity";
Fragment fragment = null;
Class fragmentClass = null;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int MESSAGE_CONNECTION_LOST = 6;
public static final int MESSAGE_UNABLE_CONNECT = 7;
private String mConnectedDeviceName = null;
// Key names received from the BluetoothService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
public static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter mBluetoothAdapter = null;
public BluetoothService mService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
fragmentClass = RegisterFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main2, fragment).commit();
Log.v(TAG, "Starting DoDaily service...");
startService(new Intent(this, DoDaily.class));
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null) {
setMService();
}
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String TAG_FRAGMENT="";
if (id == R.id.nav_regist) {
fragmentClass = RegisterFragment.class;
TAG_FRAGMENT ="register";
// Handle the camera action
} else if (id == R.id.nav_activity) {
fragmentClass = ActivityFragment.class;
TAG_FRAGMENT ="activity";
}
else if(id == R.id.nav_inventory)
{
fragmentClass = InventoryFragment.class;
TAG_FRAGMENT ="inventory";
}
else if (id == R.id.nav_manage) {
fragmentClass = SettingFragment.class;
TAG_FRAGMENT ="setting";
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main2, fragment,TAG_FRAGMENT).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (DEBUG)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
//btnScan.setText(getText(R.string.Connecting));
fragment1.btnScanEnable(false);
break;
case BluetoothService.STATE_CONNECTING:
Toast.makeText(MainActivity.this,R.string.title_connecting,Toast.LENGTH_SHORT).show();
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Toast.makeText(MainActivity.this,R.string.title_not_connected,Toast.LENGTH_SHORT).show();
break;
}
break;
case MESSAGE_WRITE:
break;
case MESSAGE_READ:
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(MainActivity.this,"Connected to " + mConnectedDeviceName,
Toast.LENGTH_SHORT).show();
String text ="Connected to "+mConnectedDeviceName;
fragment1.setTvText(text);
break;
case MESSAGE_TOAST:
Toast.makeText(MainActivity.this, msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
case MESSAGE_CONNECTION_LOST:
Toast.makeText(MainActivity.this, "Device connection was lost",Toast.LENGTH_SHORT).show();
String text1 ="Not Connect to Any Device";
fragment1.setTvText(text1);
// editText.setEnabled(false);
// sendButton.setEnabled(false);
break;
case MESSAGE_UNABLE_CONNECT:
Toast.makeText(MainActivity.this, "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onStart() {
super.onStart();
// If Bluetooth is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null){
setMService();
}
}
}
#Override
public synchronized void onResume() {
super.onResume();
if (mService != null) {
if (mService.getState() == BluetoothService.STATE_NONE) {
// Start the Bluetooth services
mService.start();
}
}
}
#Override
public synchronized void onPause() {
super.onPause();
if (DEBUG)
Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if (DEBUG)
Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth services
if (mService != null)
mService.stop();
if (DEBUG)
Log.e(TAG, "--- ON DESTROY ---");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (DEBUG)
Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:{
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras().getString(
DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
if (BluetoothAdapter.checkBluetoothAddress(address)) {
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
// Attempt to connect to the device
mService.connect(device);
}
}
break;
}
case REQUEST_ENABLE_BT:{
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
// FragmentManager fm1 = getSupportFragmentManager();
// SettingFragment fragment1 = (SettingFragment) fm1.findFragmentByTag("setting");
// fragment1.KeyListenerInit();
setMService();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(MainActivity.this, R.string.bt_not_enabled_leaving,Toast.LENGTH_SHORT).show();
onBackPressed();
}
break;
}
}
}
public void setMService()
{
mService = new BluetoothService(MainActivity.this, mHandler);
}
}
SettingFragment.Java
public class SettingFragment extends Fragment {
public static final int REQUEST_CONNECT_DEVICE = 1;
private static final String CHINESE = "GBK";
SessionManagement sessionManagement;
DatabaseHandler db;
TextView tvConnected;
Button btnScan;
Button btnTest;
public SettingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_setting, container, false);
getActivity().setTitle("Setting");
btnScan = (Button)rootview.findViewById(R.id.btnScan);
btnTest = (Button) rootview.findViewById(R.id.btnTest);
tvConnected = (TextView) rootview.findViewById(R.id.tvPrinterConnect);
KeyListenerInit();
return rootview;
}
public void setTvText(String text)
{
tvConnected = (TextView) getActivity().findViewById(R.id.tvPrinterConnect);
tvConnected.setText(text);
}
public void btnScanEnable(Boolean set)
{
btnScan = (Button)getActivity().findViewById(R.id.btnScan);
btnScan.setEnabled(set);
}
public void KeyListenerInit() {
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
});
((MainActivity)getActivity()).setMService();
}
}
remove this line from fragment KeyListenerInit method because you already initialize object in Activity then why you again intialize this.
((MainActivity)getActivity()).setMService();
and remove this code from onCreate method because you already add this code in onStart method so no need in onCreate method:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null) {
setMService();
}
}
I am new to android. I have being trying to implement job portal application. Now in trying to invoke webservices and getting responses. But my problem is that when I am calling webservice everything is working fine but user details like username and email, id are not displaying on navigation drawer header. Please help me out.
Here is my piece of code:
public class UserHome extends FragmentActivity {
private static final CharSequence Vanaja = null;
private static final int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String OPERATION_NAME = "loginvalidate";
static boolean errored = false;
private static final CharSequence Home = null;
private DrawerLayout mDrawerLayout;
protected ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
protected CharSequence mDrawerTitle;
// used to store app title
protected CharSequence mTitle;
int childcount;
// slide menu items
protected String[] navMenuTitles;
private TypedArray navMenuIcons;
public String emailvalue,passwordvalue;
String emailid="";
String password="";
SoapObject result;
protected ArrayList<NavDrawerItem> navDrawerItems;
protected NavDrawerListAdapter adapter;
protected FrameLayout frameLayout;
TextView name,emailid1;
public void getLoginValues(String emailid,String password)
{ emailvalue=emailid;
passwordvalue=password;
}
final String s=emailid;
final String s1=password;
/*public void getLoginValues(String editTextUsername,
String editTextPassword) {
emailvalue=editTextUsername;
passwordvalue=editTextPassword;
}
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation1);
name = (TextView)findViewById(R.id.industry11);
emailid1=(TextView)findViewById(R.id.mail);
try
{
final ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#BDBDBD")));
#SuppressWarnings("unused")
AsyncTaskRunner async=(AsyncTaskRunner) new AsyncTaskRunner(this).execute();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items11);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons22);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawerlayout);
mDrawerList = (ListView) findViewById(R.id.slidermenu);
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.userslider, mDrawerList, false);
mDrawerList.addHeaderView(header, null, false);
mDrawerLayout.closeDrawers();
RelativeLayout update=(RelativeLayout)findViewById(R.id.update);
update.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("unused")
#Override
public void onClick(View v){
switch (v.getId()) {
case R.id.update:
//what to put here
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, new ProfileUpdate());
ft.commit();
bar.setTitle(" Updae Profile");
break;
}
}
}
);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.icd2, //nav menu toggle icon
R.string.drawer_open, // nav drawer open - description for accessibility
R.string.drawer_close // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
bar.setIcon(R.color.transparent);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(1);
}}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
#SuppressWarnings("unused")
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment=null;
String title="null";
switch (position) {
case 1:
fragment =new SearchJobs1();
title="";
/* Intent intent1 = new Intent(getApplicationContext(),HomeFragment.class);
startActivity(intent1);*/
break;
case 2:
fragment =new LatestJobs();
/* Intent intent2 = new Intent(getApplicationContext(), Homepage.class);
startActivity(intent2);*/
break;
case 3:
fragment =new AppliedJobs();
/* Intent intent3 = new Intent(getApplicationContext(), FindPeopleFragment.class);
startActivity(intent3);*/
break;
case 4:
fragment =new ChangePassword();
/*Intent intent4 = new Intent(getApplicationContext(), CommunityFragment.class);
startActivity(intent4);*/
break;
case 5:
fragment =new Unsubscribe();
/* Intent intent5 = new Intent(getApplicationContext(),PagesFragment.class);
startActivity(intent5);*/
break;
case 6:
fragment =new LogOut();
Intent intent6 = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent6);
break;
/*case 6:
fragment =new ContactUs();
Intent intent6 = new Intent(getApplicationContext(),PhotosFragment.class);
startActivity(intent6);
break;
case 7:
fragment =new AboutUs();
Intent intent6 = new Intent(getApplicationContext(),PhotosFragment.class);
startActivity(intent6);
break;*/
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position-1);
setTitle(navMenuTitles[position-1]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
getActionBar().setTitle(" " + mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setActionBarTitle(String string) {
// TODO Auto-generated method stub
getActionBar().setTitle(" " + string);
}
public void setActionBarImage(ImageView view)
{
Log.d("Tittlename", "image is"+view);
getActionBar().setCustomView(view);
}
private class AsyncTaskRunner extends AsyncTask<Void,Void,Void> {
String result1;
UserHome outer;
public AsyncTaskRunner(UserHome outer) {
this.outer = outer;
}
private String TAG;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
WebserviceCall service=new WebserviceCall();
try
{
/*if(isNetworkAvailable())
{*/
SoapObject result;
result=service.invokeLoginWS(emailvalue, passwordvalue, OPERATION_NAME);
/*
String s=outer.emailid;
String s1=outer.password;
=======
/*String s=UserHome.this.emailid;
String s1=UserHome.this.password;*/
/*
result=service.invokeLoginWS(s,s1," ");*/
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(R.layout.user_home, null);
String resultvalue=result.getProperty("firstname").toString();
emailid= result.getProperty(0).toString();
password = result.getProperty(1).toString();
name.setText(resultvalue);
resultvalue=result.getProperty("emailid").toString();
emailid1.setText(resultvalue);
/*else
{
Intent intent1 = new Intent(getActivity(),InternetProblem.class);
startActivity(intent1);
}*/
}
catch(Exception e)
{
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run()
{
try {
Intent intent1 = new Intent(getApplicationContext(),InternetProblem.class);
startActivity(intent1);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/*Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run()
{
try {
serviceCall();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}); */
/* int childCount = result.getPropertyCount();
*/
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
}
}
I have a MainActivity where the Swipeable Tabs are created and from there two fragments are called. I have 2 webservice for Fragment A and Fragment B where I have to parse data coming from server. I am using volley. When I am in the first fragment; both the webservice are being called and the data are not loaded for the first time.
But in the Second time it is showing correctly but it should be like this that when I am in Fragment A the service of the Fragment A should be called and when I am in Fragment B the service of the Fragment B should be called. I am attaching the code snippets.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
int status = 0 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
// Show menu icon
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
/**
* Lets inflate the very first fragment
* Here , we are inflating the NewsFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
// mNavigationView.setBackgroundColor(Color.parseColor("#CFCFCF"));
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
status = 1;
if (status == 1){
}
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sent){
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new VideosFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_draft) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new OpinionFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sports) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_weather) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about_us:
Intent intent = new Intent(MainActivity.this, AboutUs.class);
startActivity(intent);
return true;
case R.id.action_terms_of_use:
Intent intent_two = new Intent(MainActivity.this, TermsUse.class);
startActivity(intent_two);
return true;
case R.id.action_privacy_policy:
Intent intent_three = new Intent(MainActivity.this, PrivacyPolicy.class);
startActivity(intent_three);
return true;
case R.id.action_contact_us:
Intent intent_four = new Intent(MainActivity.this, ContactUs.class);
startActivity(intent_four);
case R.id.search:
// hidetext();
Toast.makeText(MainActivity.this, "In the development Phase... Thank You...", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// private void hidetext() {
//
// Intent i = new Intent(MainActivity.this, SearchResultActivity.class);
// startActivity(i);
// }
}
TopNewsFragment
public class TopNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/topnews";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
Movie movie;
private ListView listView;
private CustomListAdapter adapter;
String imageURL = "", title = "", description = "";
public static final String KEY_ID = "news_id";
public static final String KEY_HEADURL = "news_url";
public static final String KEY_DETAILS = "news_details";
public static final String KEY_TITLE = "news_title";
RequestQueue requestQueue;
public TopNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
intent.putExtra(KEY_ID, item.getNewsId());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0) {
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
title = movie.setTitle(homenews.getString("Title"));
description = movie.setDescription(homenews.getString("Description"));
movie.setDescription(homenews.getString("Description"));
imageURL = movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
// System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
LatestNewsFragment.java
public class LatestNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/latest";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
// contacts JSONArray
private JSONArray users = null;
RequestQueue requestQueue;
public static final String KEY_HEADURL="news_url";
public static final String KEY_DETAILS="news_details";
public static final String KEY_TITLE = "news_title";
public LatestNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
// intent.putExtra("URL", movie.getThumbnailUrl());
// intent.putExtra("title", movie.getTitle());
// intent.putExtra("description", movie.getDescription());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
// JsonObjectRequest jsonObjectRequest =
#Override
public void onResponse(JSONObject response) {
try {
hidePDialog();
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0){
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
movie.setDescription(homenews.getString("Description"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
What probably happens is that the two fragments are both loaded even though you are only looking at one fragment at a time. Instead of creating a new RequestQueue on every request you should only have one. For example create an Application class like so:
public class MyApp extends Application {
private RequestQueue mRequestQueue;
private static MyApp mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApp getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
}
Don't forget to add your application class to your manifest inside the <activity> tag:
<application
android:name=".MyApp"
Now you can put requests on that queue from your fragments:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Do something with error
}
});
//Put the actual request on the queue
MyApp.getInstance().addToRequestQueue(req);