NOTE:
The code shown below may be a bit hard to read, but i hope it can help. Sorry for that.
I get this error whenever i press HOME button and my app goes background.
java.lang.RuntimeException: Parcel: unable to marshal value
elektro_fr.newapplication.FragmentsActivity$3#a6c25e4
I'm new to android programming and i would like to create a class which can offer me all the functions without implementing them each time.
I made a My_Activity class:
package elektro_fr.my_android;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public abstract class My_Activity extends AppCompatActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private int myLayout;
protected Bundle mySettings;
private boolean gesturesEnabled=false;
private GestureDetectorCompat myGestureDetector;
private boolean canStart=false;
private boolean menuEnabled=false;
private HashMap<String,Action> menuEntries;
protected List<My_Fragment> fragmentsList=new LinkedList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myGestureDetector = new GestureDetectorCompat(this,this);
if (savedInstanceState==null){
canStart=true;
}
init();
setContentView(myLayout);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("LIST",menuEntries);
for (int counter=0;counter<fragmentsList.size();counter++){
getSupportFragmentManager().putFragment(outState,"FRAGMENT_SETTINGS_"+counter,fragmentsList.get(counter));
}
}
#Override
protected void onStart() {
super.onStart();
if (canStart) setGraphics();
canStart=false;
}
protected abstract void init();
protected abstract void setGraphics();
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState!=null){
menuEntries=(HashMap<String, Action>) savedInstanceState.getSerializable("LIST");
int size=getSupportFragmentManager().getFragments().size();
for (int counter=0;counter<size;counter++){
fragmentsList.add(counter,(My_Fragment)getSupportFragmentManager().getFragment(savedInstanceState,"FRAGMENT_SETTINGS_"+counter));
}
}
refreshState();
}
abstract protected void refreshState();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuEnabled;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (menuEntries.get(item.getTitle())!=null){
menuEntries.get(item.getTitle()).doAction();
}
return menuEnabled;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (menuEnabled){
if (menuEntries.size()!=0){
menu.clear();
int counter=0;
for (String s: menuEntries.keySet()){
menu.add(Menu.NONE,counter,Menu.NONE,s);
counter++;
}
}
}
return menuEnabled;
}
protected void setGestures(boolean enabled){
gesturesEnabled=enabled;
}
protected void setMenu(boolean enabled){
menuEnabled=enabled;
menuEntries=new HashMap<>();
}
protected HashMap<String, Action> getMenuEntries(){
return menuEntries;
}
public My_Fragment addFragment(Class<? extends My_Fragment> fragmentClass, int fragmentContainer, int fragmentID, Bundle fragmentArgs){
My_Fragment fragment = null;
try {
fragment = fragmentClass.newInstance();
}
catch (InstantiationException e){
}
catch (IllegalAccessException e){
e.printStackTrace();
}
fragment.setArguments(fragmentArgs);
getSupportFragmentManager().beginTransaction().add(fragmentContainer, fragment).commit();
fragmentsList.add(fragment);
return fragment;
}
protected My_Fragment getFragment(Class<? extends My_Fragment> fragmentClass){
for (My_Fragment f: fragmentsList){
if (fragmentClass.isInstance(f)){
return f;
}
}
return null;
}
public void removeFragment(My_Fragment fragment,boolean addToBackStack){
if (fragment.isAdded()){
FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
if (addToBackStack)transaction.addToBackStack(null);
transaction.remove(fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
if (!addToBackStack)fragmentsList.remove(fragment);
}
}
protected void setFullScreen(boolean fullScreen){
WindowManager.LayoutParams attrs = getWindow().getAttributes();
if (fullScreen) {
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
else {
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
getWindow().setAttributes(attrs);
}
protected void hideActionBar(boolean hidden){
if (hidden){
getSupportActionBar().hide();
}
else getSupportActionBar().show();
}
protected void setLayout(int layoutID){
myLayout=layoutID;
}
public boolean onTouchEvent(MotionEvent event) {
if (gesturesEnabled){
this.myGestureDetector.onTouchEvent(event);
}
return true;
}
public boolean onSingleTapConfirmed(MotionEvent e) {
My_AndroidTools.KeyboardTools.closeInputKeyboard(getCurrentFocus());
return true;
}
public boolean onDoubleTap(MotionEvent e) {
return true;
}
public boolean onDoubleTapEvent(MotionEvent e) {
return true;
}
public boolean onDown(MotionEvent e) {
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return true;
}
public void onLongPress(MotionEvent e) {
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
This is FragmentsActivity, which extends and implements My_Activity:
package elektro_fr.newapplication;
import android.os.Bundle;
import android.util.Log;
import android.widget.RelativeLayout;
import elektro_fr.my_android.Action;
import elektro_fr.my_android.My_Activity;
import elektro_fr.my_android.My_Fragment;
import elektro_fr.newapplication.R;
public class FragmentsActivity extends My_Activity implements My_Fragment.fragmentOperations {
private MyTopFragment topFragment;
private MyBottomFragment bottomFragment;
#Override
protected void init() {
setLayout(R.layout.fragments);
setGestures(true);
setMenu(true);
}
#Override
protected void setGraphics() {
Bundle args=new Bundle();
args.putInt(MyTopFragment.LAYOUT_ID,R.layout.ts_fragment);
args.putInt(My_Fragment.CENTER_HORIZONTAL,RelativeLayout.CENTER_HORIZONTAL);
topFragment = (MyTopFragment) addFragment(MyTopFragment.class,R.id.MainLayout,R.layout.ts_fragment,args);
Bundle args2=new Bundle();
args2.putInt(My_Fragment.LAYOUT_ID,R.layout.bs_fragment);
args2.putInt(My_Fragment.LAYOUT_WIDTH,RelativeLayout.LayoutParams.MATCH_PARENT);
args2.putInt(My_Fragment.LAYOUT_HEIGHT,RelativeLayout.LayoutParams.WRAP_CONTENT);
args2.putInt(My_Fragment.BELOW, R.id.ts);
args2.putInt(My_Fragment.CENTER_HORIZONTAL,RelativeLayout.CENTER_HORIZONTAL);
bottomFragment = (MyBottomFragment) addFragment(MyBottomFragment.class,R.id.MainLayout,R.layout.bs_fragment,args2);
getMenuEntries().put("Menu Item #1", new Action() {
#Override
public void doAction() {
Log.i("Ciccio","you pressed 1");
}
});
getMenuEntries().put("Menu Item #2", new Action() {
#Override
public void doAction() {
Log.i("Ciccio","you pressed 2");
}
});
getMenuEntries().put("Menu Item #3", new Action() {
#Override
public void doAction() {
Log.i("Ciccio","you pressed 3");
}
});
}
protected void refreshState(){
topFragment = (MyTopFragment) getFragment(MyTopFragment.class);
bottomFragment = (MyBottomFragment) getFragment(MyBottomFragment.class);
}
#Override
public void ClickButtonOperation(Object[] arguments) {
switch((Integer)arguments[0]){
case 0:
bottomFragment.setText((String)arguments[1],(String)arguments[2]);
break;
}
}
}
This is My_Fragment class:
package elektro_fr.my_android;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Layout;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public abstract class My_Fragment extends Fragment {
public final static String LAYOUT_ID="layout_id";
public final static String LAYOUT_WIDTH="layout_width";
public final static String LAYOUT_HEIGHT="layout_height";
public final static String BELOW="layout_below";
public final static String ABOVE="layout_above";
public final static String ALIGN_PARENT_BOTTOM="align_parent_bottom";
public final static String CENTER_HORIZONTAL="center_horizontal";
private String[] params={
LAYOUT_ID,LAYOUT_WIDTH, LAYOUT_HEIGHT, ALIGN_PARENT_BOTTOM, CENTER_HORIZONTAL, BELOW, ABOVE
};
protected int fragmentLayout;
protected fragmentOperations myActivity;
protected Bundle mySettings;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState!=null){
mySettings=new Bundle();
mySettings.putAll(savedInstanceState);
}
else mySettings=getArguments();
fragmentLayout=mySettings.getInt(LAYOUT_ID);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mySettings.putAll(savedInstanceState);
refreshState();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setState();
outState.putAll(mySettings);
}
public interface fragmentOperations{
void ClickButtonOperation(Object[] arguments);
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(fragmentLayout,container,false);
int widthSettings=mySettings.getInt(params[1]);
int heightSettings=mySettings.getInt(params[2]);
view.setLayoutParams(new RelativeLayout.LayoutParams((widthSettings==0?RelativeLayout.LayoutParams.WRAP_CONTENT:widthSettings),(heightSettings==0?RelativeLayout.LayoutParams.WRAP_CONTENT:heightSettings)));
RelativeLayout.LayoutParams layoutConfig= (RelativeLayout.LayoutParams) view.getLayoutParams();
for (int counter=3;counter<params.length;counter++){
int settings=mySettings.getInt(params[counter]);
if (settings!=0){
if (counter==5){
layoutConfig.addRule(RelativeLayout.BELOW,settings);
}
else if (counter==6){
layoutConfig.addRule(RelativeLayout.ABOVE,settings);
}
else{
layoutConfig.addRule(settings);
}
}
}
init(view);
return view;
}
protected abstract void init(View v);
protected abstract void setState();
protected abstract void refreshState();
#Override
public void onAttach(Context context) {
super.onAttach(context);
myActivity=(fragmentOperations)getActivity();
}
}
EDIT:
Finally, Action (interface), which i edited in order to implement Serializable:
package elektro_fr.my_android;
import java.io.Serializable;
public interface Action extends Serializable{
public void doAction();
}
This is the error:
Process: elektro_fr.newapplication, PID: 24970
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = elektro_fr.newapplication.FragmentsActivity$3)
Caused by:
Caused by: java.io.NotSerializableException: elektro_fr.newapplication.FragmentsActivity
why should i implement serializable in this class?
You try to save menuEntries in OnSaveInstanceState, but the type is HashMap and this type is not serializable. Only primitive can be save or custom object when your implement the serialization yourself.
SOLUTION:
Following Johann67 idea:
Ok I understand your code. You can't do that. When you serialize an
object, only the fields are serialized and save. But here you try to
serialize the doAction() method... You need to change the Action
object. Maybe you can just save the item position on your HashMap or
create an object and store your information in the fields.
So I modified my code.
First of all Ichanged my menuEntries object to a List of String.
Second, i created a new method:
protected void dispatchItemAction(int itemID);
which can be overridden in order to switch between actions to do, based on the itemID.
And i modified this method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
dispatchItemAction(item.getItemId());
return menuEnabled;
}
protected void dispatchItemAction(int itemID){
}
now, to add menu items:
protected void addMenuItems(){
getMenuEntries().add("Menu Item #1");
getMenuEntries().add("Menu Item #2");
getMenuEntries().add("Menu Item #3");
}
#Override
protected void dispatchItemAction(int itemID) {
switch(itemID){
case 0:
Log.i("Log","Pressed #1.");
break;
case 1:
Log.i("Log","Pressed #2.");
break;
case 2:
Log.i("Log","Pressed #3.");
break;
}
}
Related
I'm using the value in a spinner to help filter a list that will be the datasource for a RecyclerView. The OnItemSelect method never seems to be called when I use the spinner
It is an Android application, built in Java, using Pie for the OS. The project was created using the Basic Activity Template.
The Activity Class
package com.logicscrew.android;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.logicscrew.android.helpers.APIHelper;
import com.logicscrew.android.helpers.EmployeeAdapter;
import com.logicscrew.android.models.Department;
import com.logicscrew.android.models.Employee;
import java.util.ArrayList;
import java.util.List;
public class ViewByDepartment extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private List<Employee> employees;
private List<Employee> filteredList;
private List<Department> deparments;
private RecyclerView rcView;
private EmployeeAdapter adapter;
private Context context;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
employees = new ArrayList<>();
deparments = new ArrayList<>();
filteredList = new ArrayList<>();
setContentView(R.layout.activity_view_by_department);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner =(Spinner)findViewById(R.id.spnDepartments);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
context = this;
FetchTask task = new FetchTask(new AsyncResponse() {
#Override
public void processFinished(List<Employee> output) {
Log.i("Employees", "Finished");
}
});
DeptTask deptTask = new DeptTask(new DeptResponse() {
#Override
public void processFinished(List<Department> output) {
Log.i("Department", "Finished");
}
});
task.execute();
deptTask.execute();
rcView = findViewById(R.id.rcEmp);
adapter = new EmployeeAdapter(context, filteredList);
rcView.setLayoutManager(new LinearLayoutManager(context));
rcView.setAdapter(adapter);
ArrayAdapter<Department> deptAdapter = new ArrayAdapter<>(
this,
R.layout.spinner,
deparments
);
deptAdapter.setDropDownViewResource(
R.layout.spinner
);
spinner.setAdapter(deptAdapter);
spinner.setOnItemSelectedListener(this);
}
private void filter(){
filteredList.clear();
filteredList.addAll(employees);
for(Employee e : filteredList){
if(e.department != spinner.getSelectedItem()){
filteredList.remove(e);
}
}
adapter.swapDataSet(filteredList);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
filter();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
private class FetchTask extends AsyncTask<Void, Void, List<Employee>> {
public AsyncResponse delegate = null;
public FetchTask(AsyncResponse asyncResponse){
delegate = asyncResponse;
}
#Override
protected List<Employee> doInBackground(Void... voids) {
return new APIHelper().fetchItems();
}
#Override
protected void onPostExecute(List<Employee> items) {
employees.addAll(items);
filteredList.addAll(items);
adapter.notifyDataSetChanged();
delegate.processFinished(items);
}
}
private class DeptTask extends AsyncTask<Void, Void, List<Department>>{
public DeptResponse delegate;
public DeptTask(DeptResponse response){
delegate = response;
}
#Override
protected List<Department> doInBackground(Void... voids) {
return new APIHelper().fetchDepartments();
}
#Override
protected void onPostExecute(List<Department> items){
deparments.addAll(items);
delegate.processFinished(items);
}
}
public interface AsyncResponse{
void processFinished(List<Employee> output);
}
public interface DeptResponse{
void processFinished(List<Department> output);
}
}
What should happen is when the event is called, it filters the list, removing anyone in the list who is not in a specific department, but the event is never called.
You try put in onCreate :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
//your method
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
Problem was an Async Race Condition. Fixed by moving the Spinner setup into the processFinished method in DeptTask.
DeptTask deptTask = new DeptTask(new DeptResponse() {
#Override
public void processFinished(List<Department> output) {
Log.i("Department", "Finished");
ArrayAdapter<Department> deptAdapter = new ArrayAdapter<Department>(
getApplicationContext(),
R.layout.spinner,
deparments
);
deptAdapter.setDropDownViewResource(
R.layout.spinner
);
spinner.setAdapter(deptAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.i("Selected Item", "I AM INDEED WORKING");
filter((Department)spinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
});
There is two arrows as you see in picture ..
one indicate to Activities in my project
other one indicate to recommended activity to declare in manifest ..
but there is no recommended activity except " StreamingActivity "
when i run my application ,, application show me that message " Unfortunately , application has stopped "
this code for publisheractivity
package khaabbas.huthaifa.com.talk_listen;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.red5pro.streaming.R5Connection;
import com.red5pro.streaming.R5Stream;
import com.red5pro.streaming.R5StreamProtocol;
import com.red5pro.streaming.config.R5Configuration;
import com.red5pro.streaming.source.R5Camera;
import com.red5pro.streaming.source.R5Microphone;
//import android.graphics.Camera;
public class PublishFragment extends android.support.v4.app.Fragment implements SurfaceHolder.Callback {
public static android.support.v4.app.Fragment newInstance() {
PublishFragment fragment = new PublishFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public PublishFragment() {
// Required empty public constructor
}
public R5Configuration configuration;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configuration = new R5Configuration(R5StreamProtocol.RTSP, "localhost", 8554, "live", 1.0f);
configuration.setLicenseKey("NBZF-UFM2-GCEP-OUYZ");
configuration.setBundleID(getActivity().getPackageName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_publish, container, false);
return v;
}
protected Camera camera;
protected boolean isPublishing = false;
protected R5Stream stream;
private void preview() {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
SurfaceView surface = (SurfaceView) getActivity().findViewById(R.id.surfaceView);
surface.getHolder().addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
#Override
public void onResume() {
super.onResume();
preview();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPublishToggle();
}
});
}
private void onPublishToggle() {
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
if(isPublishing) {
stop();
}
else {
start();
}
isPublishing = !isPublishing;
publishButton.setText(isPublishing ? "stop" : "start");
}
public void start() {
camera.stopPreview();
stream = new R5Stream(new R5Connection(configuration));
stream.setView((SurfaceView) getActivity().findViewById(R.id.surfaceView));
R5Camera r5Camera = new R5Camera(camera, 320, 240);
R5Microphone r5Microphone = new R5Microphone();
stream.attachCamera(r5Camera);
stream.attachMic(r5Microphone);
stream.publish("red5prostream", R5Stream.RecordType.Live);
camera.startPreview();
}
public void stop() {
if(stream != null) {
stream.stop();
camera.startPreview();
}
}
#Override
public void onPause() {
super.onPause();
if(isPublishing) {
onPublishToggle();
}
}
}
Remove both this activity because u used only single activity it define activity and two other is fragment.
<activity android:name=".S"/>
<activity android:name=".Sub"/>
and fragment call used below code..
Fragment fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
No need to declare fragment on manifest, remove fragment declaration from manifest because you are declare fragment within section in manifest file.
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
I want to create a loader for my list view but got
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, context)
know this error is very common but tried to import different library still error. Really appreciate if someone can point out why. Thanks in advance!
my code:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.app.Fragment;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.app.Activity;
public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
//showNoteList();
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
//String ds = note_database.getData();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.noteListAdapter);
getLoaderManager().initLoader(0, null, context);
note_database.close();
//note_list.setText(ds);
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context, note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context,data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
// THE LOADER
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_note_items;
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
this.loader_db = db;
}
#Override
protected void onStartLoading() {
if (loader_note_items != null) {
deliverResult(loader_note_items); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open(); // Query the database
ArrayList<NoteItems> note_items = loader_db.getNote_items();
loader_db.close();
return loader_note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
loader_note_items = data; // Caching
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_note_items = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_note_items = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}
I am developing an app in which i need to fill spinner from one webservice and there are second spinner are also exist which fill after select first spinner item. second(spinner B) is depend on spinner A. i got list for A but problem with b spinner.
my basic requirement is when i select the item of spinner "A" it will load all item of Spinner "b"
here is code ::
package com.CaribPay;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.Setting.CustomParser;
public class Register2 extends Activity implements OnItemClickListener {
private Button BtnReg2Next;
private EditText EdtxReg2Streetadd1,
EdtxReg2Streetadd2,
EdtxReg2City,
EdtxReg2Zipcode;
private Spinner
SpnrReg2Contry,
SpnrReg2Agent,
SpnrReg2State,
SpnrReg2PrimaryCurr,
SpnrReg2SecondaryCurr;
private CustomParser cstParsr = new CustomParser();
private String[] Regstrationstep1;
private String[] strCountry,strProvince;
private String[] Primarysecondarycur;
private int globPosition;
private String strSelecteccontry;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register2);
GetDataFromLastPage();
new FillSpinnerTask().execute();
}
private class FillSpinnerTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(
Register2.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage(getString(R.string.MsgPleasewait));
this.dialog.show();
this.dialog.setCancelable(false);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
strCountry = cstParsr.LoadCountriesForMobApp(getApplicationContext());
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
this.dialog = null;
} catch (Exception e) {
e.printStackTrace();
}
if(strCountry != null)
{
for(int i=0;i<strCountry.length;i++)
{
Log.i("TAG","strCountry"+strCountry[i]);
}
}
FillView();
}
}
}
private void FillView() {
BtnReg2Next = (Button)findViewById(R.id.BtnReg2Next);
EdtxReg2Streetadd1 = (EditText)findViewById(R.id.EdtxReg2Streetadd1);
EdtxReg2Streetadd2= (EditText)findViewById(R.id.EdtxReg2Streetadd2);
EdtxReg2City = (EditText)findViewById(R.id.EdtxReg2City);
EdtxReg2Zipcode = (EditText)findViewById(R.id.EdtxReg2Zipcode);
SpnrReg2Contry = (Spinner)findViewById(R.id.SpnrReg2Contry);
SpnrReg2Agent = (Spinner)findViewById(R.id.SpnrReg2Agent);
SpnrReg2State = (Spinner)findViewById(R.id.SpnrReg2State);
SpnrReg2PrimaryCurr = (Spinner)findViewById(R.id.SpnrReg2PrimaryCurr);
SpnrReg2SecondaryCurr= (Spinner)findViewById(R.id.SpnrReg2SecondaryCurr);
if(strCountry != null)
{
ArrayAdapter languagelist = new ArrayAdapter(
Register2.this,
android.R.layout.simple_spinner_item,
strCountry);
languagelist.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
SpnrReg2Contry.setAdapter(languagelist);
}
SpnrReg2Contry.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3)
{
strSelecteccontry = strCountry[position];
new FillProvinceSpinnerTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
/*SpnrReg2State.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(strProvince == null)
{
new FillProvinceSpinnerTask().execute();
}
return true;
}
});*/
BtnReg2Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(EdtxReg2Streetadd1.getText().toString().equalsIgnoreCase("")|
EdtxReg2Streetadd2.getText().toString().equalsIgnoreCase("")|
EdtxReg2City.getText().toString().equalsIgnoreCase("")|
EdtxReg2Zipcode.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getApplication(),getString(R.string.nullmessage),Toast.LENGTH_LONG).show();
}else
{
Intent Registration2 = new Intent(Register2.this,Register3.class);
startActivity(Registration2);
finish();
}
}
});
}
private void GetDataFromLastPage() {
// TODO Auto-generated method stub
Intent intent = getIntent();
Regstrationstep1 = new String[9];
Regstrationstep1 = intent.getStringArrayExtra("Regstrationstep1");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int Pos, long arg3) {
// TODO Auto-generated method stub
}
private class FillProvinceSpinnerTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(
Register2.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage(getString(R.string.MsgPleasewait));
this.dialog.show();
this.dialog.setCancelable(false);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
strProvince = cstParsr.LoadProvinceFromCountryForMobApp(getApplicationContext(),strSelecteccontry);
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
this.dialog = null;
} catch (Exception e) {
e.printStackTrace();
}
if(strProvince != null)
{
Primarysecondarycur = strProvince[0].split("~");
strProvince[0] = "Please Select a State";
ArrayAdapter languagelist = new ArrayAdapter(
Register2.this,
android.R.layout.simple_spinner_item,
strProvince);
languagelist.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
SpnrReg2State.setAdapter(languagelist);
}
}
}
}
}
The issue with OnItemSelectedListener is that it selects first value on declaration. To avoid the first call do something like this :
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(count>0) {
// do what you want on item selection
} else {
count++;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}