How do I load different activities with this menuitem - java

I'm attempting to load different activites with this MenuItem when I click the menuitem (specifically - help) the correct activity User1Tap.class does not load (it brings me to the AddEditCountry.class instead)
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class CountryList extends ListActivity {
public static final String ROW_ID = "row_id";
private ListView conListView;
private CursorAdapter conAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
// map each name to a TextView
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list, null, from, to);
setListAdapter(conAdapter); // set adapter
}
#Override
protected void onResume()
{
super.onResume();
new GetContacts().execute((Object[]) null);
}
#Override
protected void onStop()
{
Cursor cursor = conAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
conAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(CountryList.this);
#Override
protected Cursor doInBackground(Object... params)
{
dbConnector.open();
return dbConnector.getAllContacts();
}
#Override
protected void onPostExecute(Cursor result)
{
conAdapter.changeCursor(result); // set the adapter's Cursor
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.deleteItem:
deleteContact();
return true;
case R.id.help:
Intent i = new Intent(ViewCountry.this, User1Tap.class);
CountryList.this.startActivity(i);
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact()
{
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DatabaseConnector dbConnector =
new DatabaseConnector(ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#Override
protected Object doInBackground(Long... params)
{
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
country_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="schemas.android.com/apk/res/android">;
<item android:id="#+id/addCountryItem"
android:title="#string/add_menu"
android:titleCondensed="#string/add_menu"
android:showAsAction="always"
android:alphabeticShortcut="e"/>
<item android:id="#+id/help"
android:title="#string/help"
android:titleCondensed="#string/help"
android:alphabeticShortcut="e"/>
</menu>

Try this:
case R.id.help:
Intent i = new Intent(this, User1Tap.class);
startActivity(i);
finish();
return true;

call the method setcontentview() in your oncreate() method...
i guesss its missing from there...
try if it works
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
//like this
setcontentview(R.layout.yourlayout);
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list, null, from, to);
setListAdapter(conAdapter); // set adapter
}

Related

Use getVIew() to find fragment container Id in non static method

I am trying to use the following code
public int id=GeneralPreferenceFragment.getView().getParent().getId();
inside SettingAvtivity/MainActivity .
but it shows following error
Non-static method 'getView()' can not be referenced from a static Context
please help me resolving this issue
following is the method used
public void method1(View view)
{
Button bt1=(Button)findViewById(R.id.button);
bt1.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
// ViewGroup vg = (ViewGroup) mCurrentFragment.getView().getParent();
Toast.makeText(SettingsActivity.this,"Sound",Toast.LENGTH_SHORT).show();
DataSyncPreferenceFragment fragment;
GeneralPreferenceFragment fragment1;
GeneralPreferenceFragment frag1;
fragment= new DataSyncPreferenceFragment();
fragment1=new GeneralPreferenceFragment();
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
int id = prefFragment.getView().getParent().getId();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.layout_1id,fragment);
ft.remove(fragment1);
ft.add(R.id.layout_1id,fragment);
ft.addToBackStack(null);
ft.commit();
}
});
}
if i use an instance of General preferenceFragment then it shows
Cannot resolve getId();
code for header that links fragment-pref_header.xml
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<!-- These settings headers are only used on tablets. -->
<header
android:fragment="com.example.amit.check1.SettingsActivity$GeneralPreferenceFragment"
android:icon="#drawable/ic_info_black_24dp"
android:title="#string/pref_header_general"
android:id="#+id/id3"/>
<header
android:fragment="com.example.amit.check1.SettingsActivity$NotificationPreferenceFragment"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/pref_header_notifications" />
<header android:fragment="com.example.amit.check1.SettingsActivity$DataSyncPreferenceFragment"
android:icon="#drawable/ic_sync_black_24dp"
android:title="#string/pref_header_data_sync" />
</preference-headers>
SettingActivity.java
package com.example.amit.check1;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.support.annotation.IdRes;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.telecom.Call;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class SettingsActivity extends AppCompatPreferenceActivity {
//private int mcontainerid;
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// int id=GeneralPreferenceFragment.getView().getParent().getId();
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
Preference preference = findPreference("launchFragment");
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// launch fragment
// addPreferencesFromResource(R.xml.pref_notification);
// Toast.makeText(getActivity(),"hellp",Toast.LENGTH_SHORT).show();
return false;
}
});
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
public void method1(View view)
{
Button bt1=(Button)findViewById(R.id.button);
bt1.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
// ViewGroup vg = (ViewGroup) mCurrentFragment.getView().getParent();
Toast.makeText(SettingsActivity.this,"Sound",Toast.LENGTH_SHORT).show();
DataSyncPreferenceFragment fragment;
GeneralPreferenceFragment fragment1;
GeneralPreferenceFragment frag1;
fragment= new DataSyncPreferenceFragment();
fragment1=new GeneralPreferenceFragment();
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
// int id = prefFragment.getView().getId();
//String st=Integer.toString(id);
//Toast.makeText(SettingsActivity.this,st,Toast.LENGTH_SHORT).show();
// int id = frag1.getView().getParent().getId();
//ViewGroup vg = (ViewGroup) findViewById(id);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
//ft.add(1234,fragment,"f1");
//int id=fragment.getId();
//String s1=Integer.toString(id);
// Toast.makeText(SettingsActivity.this,s1,Toast.LENGTH_SHORT).show();
// ft.add(R.id.layout_1id,fragment);
//ft.add() will add fragment in previous fragment to
// the previous fragment
// ft.replace(R.id.layout_1id,fragment);
// ft.hide(fragment1);
//ft.hide() is used to hide an fragment;
// ft.detach(fragment1);
//detach method removes the fragment from UI.but it can be reused with the help
//of attach method.
//Toast.makeText(SettingsActivity.this,"removed frag1",Toast.LENGTH_SHORT).show();
//ft.show(fragment);
ft.remove(fragment1);
//remove method removes the fragment from UI;you can reuse fragment again,for reusing
//again you would have to use add method
ft.add(R.id.layout_1id,fragment);
ft.addToBackStack(null);
ft.commit();
}
});
}
}
You need to call method getView() from instance of you class GeneralPreferenceFragment. I.e:
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
// ... some business logic
public int id = prefFragment.getView().getParent().getId();

Android fragments must be static

I've got this error, but I don't know how to resolve this error.
Error: Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static [ValidFragment]
Please help me if you know how to solve
This is the MainActivity.java
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private String keyPref = "test";
private SharedPreferences pref;
private static SharedPreferences.Editor editor;
private static ViewPager view;
private FoodListFragment makanan = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private FoodListFragment minuman = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private FoodListFragment snack = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private Adapter adapter = new Adapter(getSupportFragmentManager());
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 4343;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private static ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences(keyPref, MODE_PRIVATE);
editor = pref.edit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(Color.rgb(183,28,28)));
fab.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
MainActivity.this.startActivity(intent);
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
DBHelper db = new DBHelper(this);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
}
};
loading = new ProgressDialog(this);
loading.setMessage("Loading");
loading.setTitle("Menu");
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateData() {
ServerHelper server = new ServerHelper() {
#Override
public void onStart() {
loading.show();
}
#Override
public void onFinish() {
loading.dismiss();
}
#Override
public void onSuccess(int statusCode, String response) {
try {
editor.putString("response", response);
editor.commit();
makanan.clearFood();
minuman.clearFood();
snack.clearFood();
JSONArray foods = new JSONArray(response);
for (int i = 0; i <= foods.length()-1; i++) {
JSONObject object = foods.getJSONObject(i);
JSONObject subs = object.getJSONObject("SubCategory");
FoodCategory addFood = new FoodCategory(subs.getString("name"), subs.getString("photo"));
if (subs.getString("categories_id").contains("1")) {
makanan.addFood(addFood);
} else if (subs.getString("categories_id").contains("2")) {
minuman.addFood(addFood);
} else if (subs.getString("categories_id").contains("3")) {
snack.addFood(addFood);
}
}
makanan.doneRefresh();
minuman.doneRefresh();
snack.doneRefresh();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(view.getContext(),"Terjadi masalah koneksi, silahkan coba kembali", Toast.LENGTH_LONG).show();
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, String response) {
if (view != null) {
Snackbar.make(view, "Terjadi Masalah Koneksi", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
Toast.makeText(MainActivity.this,"Terjadi Masalah Koneksi", Toast.LENGTH_LONG).show();
}
makanan.doneRefresh();
minuman.doneRefresh();
snack.doneRefresh();
loading.dismiss();
}
};
server.getAllSubs();
}
private void setupViewPager(ViewPager viewPager) {
makanan.setRetainInstance(true);
minuman.setRetainInstance(true);
snack.setRetainInstance(true);
adapter.addFragment(makanan, "Makanan");
adapter.addFragment(minuman, "Minuman");
adapter.addFragment(snack, "Snack");
viewPager.setAdapter(adapter);
updateData();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private void setupDrawerContent(final NavigationView navigationView) {
View header = navigationView.getHeaderView(0);
TextView username = (TextView) header.findViewById(R.id.main_username);
DBHelper db = new DBHelper(this);
username.setText(db.getUsers().getName());
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home: {
menuItem.setChecked(true);
break;
}
case R.id.nav_order: {
navigationView.getMenu().getItem(0).setChecked(true);
Intent order = new Intent(MainActivity.this, OrderActivity.class);
startActivity(order);
break;
}
case R.id.nav_cart: {
navigationView.getMenu().getItem(0).setChecked(true);
Intent cart = new Intent(MainActivity.this, CartActivity.class);
startActivity(cart);
break;
}
case R.id.nav_logout: {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setMessage("Anda yakin ingin logout akun anda ?");
dialog.setNegativeButton("Batal",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
dialog.setPositiveButton("Keluar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
DBHelper logout = new DBHelper(MainActivity.this);
logout.clearSPConfig();
LocalBroadcastManager.getInstance(MainActivity.this).unregisterReceiver(mRegistrationBroadcastReceiver);
Intent goLogin = new Intent(MainActivity.this, LoginMainActivity.class);
startActivity(goLogin);
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
public static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
and this is the fragment class FoodListFragment.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public abstract class FoodListFragment extends Fragment {
private ArrayList<FoodCategory> foodList = new ArrayList<FoodCategory>();
private RecyclerView rv;
private RecyclerViewAdapter adapter;
private SwipeRefreshLayout swipeLayout;
private View view;
FoodListFragment() {
}
public void addFoods(ArrayList<FoodCategory> food) {
foodList = food;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
public void addFood(FoodCategory food) {
foodList.add(food);
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
public void clearFood() {
foodList.clear();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// final RecyclerView rv = (RecyclerView) inflater.inflate(R.layout.fragment_food_list, container, false);
view = inflater.inflate(R.layout.fragment_food_list, null);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
doRefresh();
}
});
swipeLayout.setColorSchemeColors(Color.RED, Color.GRAY);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
setupRecyclerView(rv);
return view;
}
private void setupRecyclerView(final RecyclerView recyclerView) {
//recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), 2));
recyclerView.setHasFixedSize(true);
setRetainInstance(true);
adapter = new RecyclerViewAdapter(getActivity(),foodList);
recyclerView.setAdapter(adapter);
}
public void doneRefresh(){
if (swipeLayout != null) {
swipeLayout.setRefreshing(false);
}
}
public abstract void doRefresh();
}
You are declaring your Fragment as abstract class. Abstract class can't be instantiated. It can be used only as a base class. The way you are trying to use it (anonymous class) is not possible in Android framework. A Fragment class must be a subclass of Fragment (or an existing subclass of it) and concrete.
Remove abstract keyword
public class FoodListFragment extends Fragment {
Things your are trying to achieve with
public abstract void doRefresh();
should be done using an interface.

MainActivity has leaked ServiceConnection

This is my MainActivity.class. I am trying to make a music player app for Android. This player will run in the background. It plays a song but when I press the back button it shows the following errors on line number 105 and 118.
import com.example.shadowman.audio_player_two.MusicService.MusicBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.MediaController.MediaPlayerControl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import static android.content.Context.BIND_AUTO_CREATE;
public class MainActivity extends Activity implements MediaPlayerControl {
//song list variables
private ArrayList<Song> songList;
private ListView songView;
//service
private MusicService musicSrv;
private Intent playIntent;
//binding
private boolean musicBound=false;
//controller
private MusicController controller;
//activity and playback pause flags
private boolean paused=false, playbackPaused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//retrieve list view
songView = (ListView)findViewById(R.id.song_list);
//instantiate list
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
//create and set adapter
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
//setup controller
setController();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//start and bind the service when the activity starts
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
//user song select
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#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) {
//menu item selected
switch (item.getItemId()) {
case R.id.action_shuffle:
musicSrv.setShuffle();
break;
case R.id.action_end:
stopService(playIntent);
musicSrv=null;
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
//method to retrieve song info from device
public void getSongList(){
//query external audio
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//iterate over results if valid
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public void start() {
musicSrv.go();
}
//set the controller up
private void setController(){
controller = new MusicController(this);
//set previous and next button listeners
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
//set and show
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.song_list));
controller.setEnabled(true);
}
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
protected void onPause(){
super.onPause();
paused=true;
}
#Override
protected void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
protected void onStop() {
if(controller !=null) {
controller.hide();
controller=null;
}
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
stopService(playIntent);
musicSrv=null;
}
}
Here is the error:
Please help me to understand & solve this error
You need to unbind service:
#Override
protected void onStop() {
// your onStop code
if(musicConnection != null) {
unbindService(musicConnection);
}
super.onStop();
}

Using a fragment to display user installed apps

In the android app I am creating, I have a scrollable tabs from my TabsPagerAdapter class which extends FragmentPagerAdapter. However, in my app, I am trying to display all user installed apps on the phone into a section of a tab. However the class which was able to return all of that extended FragmentActivity.
I tried to follow this, but it is not working.
How to list all downloaded android apps in a fragment
Sadly, after much research I found out that I can only put fragments in different tabs and only have one Activity displayed at any one time and the tabs themselves can only return Fragments.
I really need to put all the user installed apps into a Fragment in this case I guess but I am unsure how to implement this...I have an Adapter class and everything.
Here is my InstalledAppActivity class which extends FragmentActivity to return all user downloaded apps.
package com.spicycurryman.getdisciplined10.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.javatechig.listapps.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends FragmentActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
ListView InstalledAppList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installed_apps);
InstalledAppList = (ListView) findViewById(R.id.Installed_List);
packageManager = getPackageManager();
new LoadApplications().execute();
InstalledAppList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ApplicationInfo app = applist.get(i);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
packageManager = getPackageManager();
new LoadApplications().execute();
return inflater.inflate(R.layout.installed_apps, container, false);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.main_text: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.slogan));
builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
startActivity(browserIntent);
dialog.cancel();
}
});
builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
private AdapterView.OnItemClickListener OnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
protected void onListItemClick(ListView InstalledAppList, View v, int position, long id) {
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
};
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
//setListAdapter(listadaptor);
InstalledAppList.setAdapter(listadaptor);
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Here is an example of how you would do it:
package com.spicycurryman.getdisciplined10.app;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.ibc.android.demo.appslist.app.ApkAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class InstalledAppActivity extends Fragment
implements OnItemClickListener {
//hi
PackageManager packageManager;
ListView apkList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.user_installed, container, false);
packageManager = getActivity().getPackageManager();
/*To filter out System apps*/
apkList = (ListView) rootView.findViewById(R.id.applist);
new LoadApplications(getActivity().getApplicationContext()).execute();
return rootView;
}
/**
* Return whether the given PackageInfo represents a system package or not.
* User-installed packages (Market or otherwise) should not be denoted as
* system packages.
*
* #param pkgInfo
* #return boolean
*/
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private boolean isSystemPackage1(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
: true;
}
// Don't need in Fragment
/*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.block, menu);
// super.onCreateOptionsMenu(menu,inflater);
}*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//ApkAdapter apkAdapter=(ApkAdapter)apkList.getAdapter();
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
Context mContext;
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
/* List<ApplicationInfo> list = mContext.getPackageManager().getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for(int n = 0;n<list.size();n++){
if ((list.get(n).flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))
}*/
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this.getActivity());
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(getActivity(), packageList1, packageManager));
if (pDialog.isShowing()){
pDialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
way don't you just from youre main activity on click off the tab create a fragment with a listview in it and displays the data list there?? you can pars the list to the fragment bay saying
fragmentclass fragment = new fragmentclass(list);
fragment.show();
if youre having truble understanding fragments you can watch this great tutorial on it especialy the part on inter fragment communication is realy use full

Placing a ListView in a Fragment Activity

In my Android app, I am trying to place a ListView in my FragmentActivity. Unfortunately there is no such thing as FragmentListActivity. The problem is that I can't call setListAdapter() and onListItemClick() methods.
So I did a lot of research and I went to my XML file and manually added the ListView there. Then instead of getListView(), I declared a ListView variable so I could call the methods on my new ListView variable. Unfortunately the method is still riddled with errors The method is unable to be resolved etc.
Here is my java code:
package com.spicycurryman.getdisciplined10.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.javatechig.listapps.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends FragmentActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
//Implementing the Listview Programatically
ListView InstalledAppList = (ListView) findViewById(R.id.Installed_List);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
packageManager = getPackageManager();
new LoadApplications().execute();
return inflater.inflate(R.layout.installed_apps, container, false);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.main_text: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.slogan));
builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
startActivity(browserIntent);
dialog.cancel();
}
});
builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
//here
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
//setListAdapter(listadaptor);
InstalledAppList.setAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(InstalledAppActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Here is my XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/Installed_List"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Try this..
You have missed onCreate
ListView InstalledAppList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installed_apps);
InstalledAppList = (ListView) findViewById(R.id.Installed_List);
packageManager = getPackageManager();
new LoadApplications().execute();
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
and remove onCreateView and add ItemClickListener also inside onCreate
public class MyAndroidVersionListFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
CustomDoctorsListAdapter adapter= new CustomDoctorsListAdapter(getActivity(), getResources().getStringArray(R.array.doctors_name), getResources().getStringArray(R.array.doctors_address),
getResources().getStringArray(R.array.doctors_category), getResources().obtainTypedArray(R.array.doctors_rating), getResources().getIntArray(R.array.doctors_clinic_distance));
getResources().obtainTypedArray(R.array.doctors_rating).recycle();
android.R.layout.simple_list_item_multiple_choice, android_versions);
setListAdapter(adapter);
Toast.makeText(getActivity(), "Mypostion"+position+"", Toast.LENGTH_LONG).show();
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
position = getArguments().getInt("second");
}
#Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
try List fragment like this hope it will help you

Categories

Resources