Placing a ListView in a Fragment Activity - java

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

Related

maketext is not applicable for arguments

I am writing one app to display user's current address based on latitude and longitude but i am getting one error in this code on line Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show(); It's saying makeText in the type toast is not applicable for arguments. I am unbable to resolve this error.
Any help??
I am trying to display user address in a TextView, but i am not sure whether i am doing good or some runtime error may occur in future.
Here is my Main activity java code:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemSelectedListener, ConnectionCallbacks, OnConnectionFailedListener{
private static final int REQUEST_RESOLVE_ERROR = 1001;
private static final String DIALOG_ERROR = "dialog_error";
private static final String STATE_RESOLVING_ERROR = "resolving_error";
GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
private boolean mResolvingError=false;
private AddressResultReceiver mResultReceiver;
// Request code to use when launching the resolution activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.shop_category);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.shop_category, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView mytext = (TextView) view;
Toast.makeText(this,"You selected "+mytext.getText(),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
protected void startIntentService() {
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
startService(intent);
}
#Override
public void onConnected(Bundle arg0) {
boolean mAddressRequested=false;
// TODO Auto-generated method stub
TextView myLatitude = (TextView)findViewById(R.id.lat_value);
TextView myLongitude = (TextView)findViewById(R.id.lang_value);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
myLatitude.setText(String.valueOf(mLastLocation.getLatitude()));
myLongitude.setText(String.valueOf(mLastLocation.getLongitude()));
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available,
Toast.LENGTH_LONG).show();
return;
}
else{
mAddressRequested=true;
if (mAddressRequested) {
startIntentService();
}
}
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (mResolvingError) {
Toast.makeText(this, "Resolving errors", Toast.LENGTH_SHORT).show();
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((MainActivity) getActivity()).onDialogDismissed();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Display the address string
// or an error message sent from the intent service.
String mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
// Show a toast message if an address was found.
if (resultCode == Constants.SUCCESS_RESULT) {
TextView myaddress=(TextView) findViewById(R.id.myaddress);
myaddress.setText(mAddressOutput);
}
else{
Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show();
}
}
}
}
Thank you in advance.
Replace this with MainActivity.this as the first parameter to your makeText() call. this is an instance of your AddressResultReceiver inner class. It is not your activity, and makeText() needs a Context, like an Activity.
Use getApplicationContext() instead of this. Use:
Toast.makeText(getApplicationContext(), "message", Toast.LENGTH_SHORT).show();
this refers to AddressResultReceiver which is not subclass of Context.
Toast.makeText() needs Context.

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.

Method OnItemClickListener from JSONParser override OnItemLongClickListener from another activity

I'm trying to create the favorites list from Json Objects which I received by URL.
When I got Json array, I defined methods OnItemLongClickListener and OnItemClickListener that get different things:
The OnItemClickListener method has to open another activity with description of product
The OnItemLongClickListener method has to add product to favorite list
The Problem that method OnItemClickListener which I defined in MainActivity is override method OnItemLongClickListener which I defined in FragmentActivty and the method OnItemLongClickListener doesn't work at all then I tried to define both methods in FragmentActivity but after that both methods don't work at all.
Is there any way to determine this problem?
Main Activity:
package com.boom.kayakapp.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.model.Airlines;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
listView = (ListView) findViewById(R.id.list);
adapter = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to movies array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
// setFragmentTitle(R.string.app_name);
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
}
FragmentActivity:
package com.boom.kayakapp.fragment;
import android.app.Activity;
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.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.ArrayList;
import java.util.List;
public class AirlinesFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
public static final String ARG_ITEM_ID = "airlines_list";
Activity activity;
ListView airlinesListView;
List<Airlines> airlines;
AirlinesAdapter airlinesAdapter;
public AirlinesFragment() {
airlines = new ArrayList<>();
}
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
findViewsById(view);
airlinesAdapter = new AirlinesAdapter(activity, airlines);
airlinesListView.setAdapter(airlinesAdapter);
airlinesListView.setOnItemClickListener(this);
airlinesListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
airlinesListView = (ListView) view.findViewById(R.id.list);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Airlines airlines = (Airlines) parent.getItemAtPosition(position);
Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, airlines.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity, airlines.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
super.onResume();
}
}
In my way I deleted definition both Methods from FavoriteFragment and defined it in MainActivity:
Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
now it works

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

How do I load different activities with this menuitem

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
}

Categories

Resources