how to onUnbind AccessibilityService - accessibilityservice

I have created an ActivityMonitorService which extends AccessibilityService to capture TYPE_WINDOW_STATE_CHANGED events. But when I force close my app, the phone restart all the time. The onUnbind() was called when the main activity onDestroy(),But every time after phone restart, the ActivityMonitorService restart and cause my phone restarted for some reasons. Give me some advice,please.
ActivityMonitorService.java
public class ActivityMonitorService extends AccessibilityService {
public static final String LOG_TAG = "ActivityMonitorService";
private MyBinder myBinder = new MyBinder();
public class MyBinder extends Binder {
public ActivityMonitorService getService()
{
return ActivityMonitorService.this;
}
}
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
Log.i(LOG_TAG, "--------onRebind--------");
}
#Override
public boolean onUnbind(Intent intent) {
Log.i(LOG_TAG, "--------onUnbind--------");
return super.onUnbind(intent);
}
#Override
public void onCreate() {
super.onCreate();
Log.i(LOG_TAG, "--------onCreate--------");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "--------onStartCommand--------");
int i = super.onStartCommand(intent, flags, startId);
Log.e(LOG_TAG,"--------onStartCommand--------, i = " + i +",START_NOT_STICKY="+ START_NOT_STICKY);
return START_NOT_STICKY;
}
#Override
protected void onServiceConnected() {
Log.i(LOG_TAG,"onServiceConnected enter");
super.onServiceConnected();
//Configure these here for compatibility with API 13 and below.
AccessibilityServiceInfo config = new AccessibilityServiceInfo();
config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
config.notificationTimeout = 100;
if (Build.VERSION.SDK_INT >= 16)
//Just in case this helps
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(config);
Log.i(LOG_TAG,"onServiceConnected");
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.i(LOG_TAG,"onAccessibilityEvent");
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
ComponentName componentName = new ComponentName(
event.getPackageName().toString(),
event.getClassName().toString()
);
ActivityInfo activityInfo = tryGetActivity(componentName);
boolean isActivity = activityInfo != null;
if (isActivity)
Log.i("CurrentActivity", componentName.flattenToShortString());
}
}
private ActivityInfo tryGetActivity(ComponentName componentName) {
try {
return getPackageManager().getActivityInfo(componentName, 0);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
#Override
public void onInterrupt() {}
#Override
public void onDestroy() {
Log.i(LOG_TAG, "--------onDestroy--------");
super.onDestroy();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "MainActivity";
public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
private boolean isBoundMonitorService = false;
private ActivityMonitorService monitorService = null;//get minitor service through binder
private ActivityMonitorService.MyBinder myBinder = null;
private ServiceConnection monitorConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
Log.e(ActivityMonitorService.LOG_TAG, "------onServiceDisconnected---------");
isBoundMonitorService = false;
};
public void onServiceConnected(ComponentName name, IBinder service) {
isBoundMonitorService = true;
Log.e(ActivityMonitorService.LOG_TAG, "------onServiceConnected---------");
//myBinder = (ActivityMonitorService.MyBinder)service;
//monitorService = myBinder.getService();
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Toast.makeText(MainActivity.this, "no permission", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
}
}
Log.d(LOG_TAG, "onCreate");
//WindowUtils.showPopupWindow(getApplicationContext());
Intent ServiceIntent = new Intent(this, ServiceUtils.class);
startService(ServiceIntent);
Intent AndroidMonitorServiceIntent = new Intent(this, ActivityMonitorService.class);
bindService(AndroidMonitorServiceIntent,monitorConnection,BIND_AUTO_CREATE);//
Log.e(ActivityMonitorService.LOG_TAG, "------bindService---------");
//finish();
}
#Override
protected void onDestroy(){
if(isBoundMonitorService)
{
Log.e(ActivityMonitorService.LOG_TAG, "------unbindService---------");
unbindService(monitorConnection);
isBoundMonitorService = false;
}
super.onDestroy();
//Intent ServiceIntent = new Intent(this, ServiceUtils.class);
//stopService(ServiceIntent);
//finish();
}
}
AndroidManifest.xml
<service
android:name=".util.ActivityMonitorService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:enabled = "true"
android:exported = "false">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/accessibilityservice"/>
</service>
xml/accessibilityservice.xml
<accessibility-service
xmlns:tools="http://schemas.android.com/tools"
android:accessibilityEventTypes="typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagIncludeNotImportantViews"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:ignore="UnusedAttribute"/>
Add some logs
05-24 08:32:44.989 8313-8313/? I/HwLauncher: Launcher Launcher.onStart() cost 1 ms
05-24 08:32:44.989 6778-6814/? W/WindowManager: Attempted to remove non-existing token: android.os.Binder#342478f
05-24 08:32:44.989 8313-8313/? I/HwLauncher: Launcher onResume()
05-24 08:32:44.989 8313-8430/? E/HwLauncher: SettingsEx , no such field.
05-24 08:32:44.989 8313-8313/? I/HwLauncher: Launcher doResumeWork()
05-24 08:32:44.989 8313-8430/? W/HwLauncher: Clock getDataFormat the getSystemString failed.
05-24 08:32:44.990 6778-6814/? E/AndroidRuntime: *** FATAL EXCEPTION IN SYSTEM PROCESS: android.bg
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.PACKAGE_RESTARTED dat=package:com.example.org.floatwindow flg=0x10 (has extras) } in com.android.server.accessibility.AccessibilityManagerService$1#5de13ec
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1235)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.os.HandlerThread.run(HandlerThread.java:61)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.os.IBinder.unlinkToDeath(android.os.IBinder$DeathRecipient, int)' on a null object reference
at com.android.server.accessibility.AccessibilityManagerService$Service.unlinkToOwnDeathLocked(AccessibilityManagerService.java:3122)
at com.android.server.accessibility.AccessibilityManagerService$Service.onRemoved(AccessibilityManagerService.java:3113)
at com.android.server.accessibility.AccessibilityManagerService.removeServiceLocked(AccessibilityManagerService.java:1145)
at com.android.server.accessibility.AccessibilityManagerService.-wrap22(AccessibilityManagerService.java)
at com.android.server.accessibility.AccessibilityManagerService$Service.unbindLocked(AccessibilityManagerService.java:2385)
at com.android.server.accessibility.AccessibilityManagerService.updateServicesLocked(AccessibilityManagerService.java:1307)
at com.android.server.accessibility.AccessibilityManagerService.onUserStateChangedLocked(AccessibilityManagerService.java:1445)
at com.android.server.accessibility.AccessibilityManagerService.-wrap19(AccessibilityManagerService.java)
at com.android.server.accessibility.AccessibilityManagerService$1.onHandleForceStop(AccessibilityManagerService.java:343)
at com.android.internal.content.PackageMonitor.onReceive(PackageMonitor.java:388)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1222)
at android.os.Handler.handleCallback(Handler.java:761)?
at android.os.Handler.dispatchMessage(Handler.java:98)?
at android.os.Looper.loop(Looper.java:156)?
at android.os.HandlerThread.run(HandlerThread.java:61)?

You don't start AccessibilityServices from activities. Accessibility services are started from the
Settings > Accessibility
area on the phone. You cannot start an Accessibility Service in the way you are attempting.

Related

Signing in an account to use google play leaderboard

The following sign in code causes my game to flicker then crash after printing "bad stuff". What am I doing wrong? I tried to implement the code shown here. I attempt a silent sign in, then if that does not work I attempt an interactive sign in. I am testing an a physical Nexus 5 with the latest version of Android 8.1.0.
public class MainActivity extends Activity {
private GLSurfaceView mGLView;
private GoogleSignInAccount account;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a GLSurfaceView instance and set it
// as the ContentView for this Activity.
mGLView = new MyGLSurfaceView(this, this);
setContentView(mGLView);
hideStatusBar();
getAccount();
}
public void hideStatusBar() {
View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
// Remember that you should never show the action bar if the
// status bar is hidden, so hide that too if necessary.
//ActionBar actionBar = getActionBar();
//actionBar.hide();
}
private void getAccount() {
account = GoogleSignIn.getLastSignedInAccount(this);
if (account == null) {
signInSilently();
}
}
public void submitScore(int score) {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.submitScore("leaderboardID", score);
}
}
private static final int leaderboardRequestCode = 9004;
private static final int signInRequestCode = 101;
public void showLeaderboard() {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.getLeaderboardIntent("leaderboardID")
.addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, leaderboardRequestCode);
}
});
}
}
//interactive sign in
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, signInRequestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == signInRequestCode) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
account = result.getSignInAccount();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "bad stuff";
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
//silent sign in
private void signInSilently() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
account = task.getResult();
} else {
startSignInIntent();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
signInSilently();
}
}

Restore scroll position

I have a simple fragment which retrieve data from Firebase database.
I use firebase recycler view to display retrieving data. And after scrolling or screen rotation I can't force recycler view (or linear layout manager) restore scroll position.
I found here some answers but they don't work.
My code is:
public class NewsListFragment extends ParentNewsFragment {
static int color_naval, color_black;
private boolean mProcessLikes = false;
private DatabaseReference mDatabaseLikes;
private DatabaseReference mDatabaseViews;
private FirebaseAuth mAuth;
private int position = 0;
public static NewsListFragment getInstance() {
return new NewsListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabaseReference = FirebaseDatabase.getInstance().getReference()
.child("App_news");
mDatabaseLikes = FirebaseDatabase.getInstance().getReference().child("news_likes");
mDatabaseViews = FirebaseDatabase.getInstance().getReference().child("news_views");
mAuth = FirebaseAuth.getInstance();
mQuery = mDatabaseReference.orderByChild("pos").startAt("100");
color_naval = getResources().getColor(R.color.colorPrimary);
color_black = getResources().getColor(R.color.colorBlack);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rv_choose, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv_choose);
lm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(lm);
rv.setHasFixedSize(true);
return rootView;
}
#Override
public void onPause() {
super.onPause();
position = lm.findFirstVisibleItemPosition();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", position);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState != null) {
position = savedInstanceState.getInt("position");
}
}
#Override
public void onResume() {
super.onResume();
if (position != 0) {
lm.scrollToPosition(position);
showToast(position+"");
}
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<NewsList, NewsListViewHolder> adapter =
new FirebaseRecyclerAdapter<NewsList, NewsListViewHolder>(
NewsList.class,
R.layout.frag_newslist_card_view,
NewsListViewHolder.class,
mQuery
) {
#Override
protected void populateViewHolder(NewsListViewHolder viewHolder, final NewsList model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setDate(model.getDate()+",");
viewHolder.setTime(model.getTime());
viewHolder.setTitle(model.getTitle());
viewHolder.setImage(getContext(), model.getImage());
viewHolder.setEye(model.getCode());
viewHolder.setThumb(post_key);
viewHolder.thumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLikes = true;
mDatabaseLikes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLikes){
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.removeValue();
mProcessLikes = false;
}
else {
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("like");
mProcessLikes = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseViews.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseViews.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("view");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChooserListener.chooseNews(model.getCode());
}
});
}
};
rv.setAdapter(adapter);
}
public static class NewsListViewHolder extends RecyclerView.ViewHolder {
//some text here
}
}
method showToast in the end shows real number of position but recyclerview starts from the beginning.
any ideas?
Make sure you are not reloading data from the server or wherever you are retrieving data.
Add is not null check in your fragment's onCreateView or activity's onCreate like:
if(savedInstanceState != null){
...
}else{
loadData();
}
Replace your linear layout manager with something similar to the following. I have used this implementation many times when using RecyclerView in fragments. Let me know how it goes
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
yourItem.setLayoutManager(mLayoutManager);

Not getting callback from google api, android?

I have connected to google api for loaction in android. but i not getting any callback from google api. not getting location.
my code is
public class SplashScreen extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static int SPLASH_TIME_OUT = 3000;
private final String LOG_TAG = "logTagMngr";
private TextView loactionout;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private LocationManager locationManager;
SharedPreferences sharedPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
sharedPref = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
loactionout = (TextView) findViewById(R.id.loactionout);
}
#Override
protected void onResume() {
super.onResume();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Turn on location?")
.setCancelable(false)
.setPositiveButton("Turn on Location", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
openWifiSettings();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else {
googleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
public void openWifiSettings() {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(500);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(LOG_TAG,"Failed");
}
#Override
public void onLocationChanged(Location location) {
Log.i("AAA",location.toString());
loactionout.setText(location.getLatitude()+"");
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("userLongitude",location.getLongitude()+"");
editor.putString("userLatitude",location.getLatitude()+"");
if(editor.commit()){
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(LOG_TAG,"Failed");
}
}
i dont know the problem. not getting connection failed on suspended callbacks also. please help me.

Android-how to send continuous latitude and longitude to the server?

I continuously get the current location, now I want to send this continuous location to the sever every 1 to 5 sec. How do I do this?
Android code:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
TextView txtOutputLat, txtOutputLon;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String lat, lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOutputLat = (TextView) findViewById(R.id.textView);
txtOutputLon = (TextView) findViewById(R.id.textView2);
buildGoogleApiClient();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());
}
updateUI();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
updateUI();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
void updateUI() {
txtOutputLat.setText(lat);
txtOutputLon.setText(lon);
}
}

java.lang.ClassCastException: java.lang.String cannot be cast to com.example.owner.stock.Item

I want to display a list in fragment. i am using a custom arraylist. it is giving me classcast exception. i searched for the soluo solvetion but it dosnt solve my problem. i am new to android so i have no idea how this.. can anyone help..
this is my Item class
public class Item {
public String item_name;
public String item_desc;
public String item_qty;
public Item(String item_name, String item_desc,String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public String getItem_name(){
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name=item_name;
}
public String getItem_desc()
{
return item_desc;
}
public void setItem_desc(String item_desc)
{
this.item_desc=item_desc;
}
public String getItem_qty()
{
return item_qty;
}
public void setItem_qty(String item_qty) {
this.item_qty = item_qty;
}
}
this is my addstock fragment
public class AddStock extends Fragment {
EditText edit_item_name,edit_item_desc,edit_item_qty;
Button btn_save;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_stock, container, false);
edit_item_name = (EditText)rootView.findViewById(R.id.edittext_item_name);
edit_item_desc = (EditText) rootView.findViewById(R.id.editText_item_desc);
edit_item_qty = (EditText) rootView.findViewById(R.id.editText_item_qty);
btn_save = (Button) rootView.findViewById(R.id.button_Save);
MainActivity act=(MainActivity)this.getActivity();
final ArrayList stock = act.arrayList;
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item_name=edit_item_name.getText().toString();
String item_desc=edit_item_desc.getText().toString();
String item_qty=edit_item_qty.getText().toString();
stock.add(item_name);
stock.add(item_desc);
stock.add(item_qty);
Toast.makeText(AddStock.this.getActivity(), "Saved", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
this is my viewstock fragment
public class ViewStock extends Fragment {
public ViewStock() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_view_stock, container, false);
ListView listview = (ListView)rootview.findViewById(R.id.list);
// Context mCtx = getActivity().getApplicationContext();
MainActivity act=(MainActivity)this.getActivity();
ItemAdapter adapter = new ItemAdapter(getActivity(),R.layout.list_item,act.arrayList);
listview.setAdapter(adapter);
return rootview;
}
}
this is my main activity
Public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FrameLayout mContentFrame;
FragmentManager fragmentManager;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
public ArrayList<Item> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
setUpToolbar();
arrayList=new ArrayList<Item>();
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
newFragment = new AddStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 0;
mDrawerLayout.closeDrawers();
return true;
case R.id.navigation_item_2:
newFragment = new ViewStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 1;
return true;
default:
return true;
}
}
});
//fragmentManager.beginTransaction().replace(R.id.nav_contentframe, fragment).commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
}
this is my ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> {
Context context;
public ItemAdapter(Context context, int resourceId,
ArrayList<Item> items) {
super(context, resourceId, items);
this.context = context;
}
/* public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
*/
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Item rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.txtItemName = (TextView) convertView.findViewById(R.id.txt_item_name);
holder.txtItemDesc = (TextView) convertView.findViewById(R.id.txt_item_desc);
holder.txtItemQty = (TextView) convertView.findViewById(R.id.txt_item_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(rowItem.getItem_name());
holder.txtItemDesc.setText(rowItem.getItem_desc());
holder.txtItemQty.setText(rowItem.getItem_qty());
return convertView;
}
private class ViewHolder {
TextView txtItemName;
TextView txtItemDesc;
TextView txtItemQty;
}
}
this is the exception m getting
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.owner.stock.Item
at com.example.owner.stock.ItemAdapter.getView(ItemAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1673)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:907)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2102)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1859)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5884)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
07-22 23:34:00.334 20992-20992/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
You are adding String objects to a list that is typed to take Item objects.
Instead of:
stock.add(someString);
stock.add(someString);
stock.add(someString);
Do
stock.add(new Item(someString, someString, someString));