Handling OnPause and OnResume inside fragments android - java

I am trying to communicate with USB using InputOutput stream, I use constructor and make the communication part in a common class and I do use it inside a fragment, if i use it inside an activity it works properly if i use inside a fragment, the application hangs to overcome the problem i terminated the connection while OnPause but while resume connection not retains only on fragment same logic works on activity, I use some animations inside like Video is that be a reason?
#SuppressLint("ValidFragment")
public class Run_Screen extends Fragment implements OnClickListener {
Usb_Communciation usbCom;
RelativeLayout R_RelativeLayout, Run_Screen_Layout, Screen_Lock_Layout;
static SharedPreferences sharedpreferences;
Animation wipe;
static int machine;
MyLog myLog = new MyLog();
View root = null;
static Activity thisActivity = null;
#Override
public void onAttach(Activity activity) {
act = activity;
super.onAttach(activity);
thisActivity = Run_Screen.this.getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (Vars.Screen_Size == 400) {
root = inflater.inflate(R.layout.run_screen_400, container, false);
} else if (Vars.Screen_Size == 600) {
root = inflater.inflate(R.layout.run_screen_600, container, false);
} else if (Vars.Screen_Size == 800) {
root = inflater.inflate(R.layout.run_screen_800, container, false);
} else {
root = inflater.inflate(R.layout.run_screen, container, false);
}
sharedpreferences = this.getActivity().getSharedPreferences(Vars.MyPre, Context.MODE_PRIVATE);
GlobalClass.Current_Screen = "Run_Screen";
cmg = new Comment_Generate(act);
R_Wiper = (ImageButton) root.findViewById(R.id.R_Wiper);
wipe = AnimationUtils.loadAnimation(act, R.anim.wipe);
wipe.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
Wiper_anim.setVisibility(View.INVISIBLE);
R_Wiper.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
Wiper_anim.setVisibility(View.VISIBLE);
}
});
R_Pause_Play.setOnClickListener(this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
usbCom = new Usb_Communciation(Run_Screen.this.getActivity(), getActivity().getIntent());
}
#Override
public void onPause() {
super.onPause();
Usb_Communciation.AppDisconnect(Run_Screen.this.getActivity());
}
public void CheckFunc(){
if(Vars.ChangeMAchine==1){
R_Progress.setVisibility(View.VISIBLE);
R_Separator.setVisibility(View.VISIBLE);
R_Run.setVisibility(View.INVISIBLE);
R_Pause.setVisibility(View.VISIBLE);
R_Stop.setVisibility(View.VISIBLE);
R_Pause_Play.setVisibility(View.INVISIBLE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.R_Pause_Play:
DisableAll();
Reset_Machine_State(-2);
Vars.ChangeMAchine=1;
CheckFunc();
R_Progress.setVisibility(View.VISIBLE);
Send_Comment(Vars.C_Start_Machine, 0, 0);
myLog.Cmd("Write", Vars.C_Start_Machine, "0", "0",
"Start The Machine");
break;
}
}
private void Send_Comment(String Comment_No, int Address, int Data) {
Sending_Comment = cmg.Generate_Comment_for(Comment_No, Address, Data);
usbCom.Send_message(Sending_Comment);
}
public void SetUserLevelControls() {
Vars.CurrentUserLevel = sharedpreferences.getInt(Vars.UserLevel, 5);
if (Permission.Launcher_Operator_Screen_Defect_Height <= Vars.CurrentUserLevel) {
Screen_Lock_Layout.setVisibility(View.GONE);
} else {
Screen_Lock_Layout.setVisibility(View.VISIBLE);
}
if (Permission.Launcher_Operator_Screen_General <= Vars.CurrentUserLevel) {
R_Run.setOnClickListener(this);
R_Pause.setOnClickListener(this);
R_Stop.setOnClickListener(this);
R_Pause_Play.setOnClickListener(this);
Run_Lock.setVisibility(View.GONE);
} else {
R_Run.setOnClickListener(null);
R_Pause.setOnClickListener(null);
R_Stop.setOnClickListener(null);
R_Pause_Play.setOnClickListener(null);
Run_Lock.setVisibility(View.VISIBLE);
}
}
}
constructor class
public Usb_Communciation(Context mContext, Intent intent) {
try {
PackageManager manager = mContext.getPackageManager();
PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
Log.d(TAG, "Info:" + info.packageName + "\n" + info.versionCode + "\n" + info.versionName);
} catch (PackageManager.NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
accessoryManager.enable(mContext, intent);
}
AppDisconnect
public static void AppDisconnect(Context context) {
switch(firmwareProtocol) {
case 2:
byte[] commandPacket = new byte[2];
commandPacket[0] = (byte) APP_DISCONNECT;
commandPacket[1] = 0;
accessoryManager.write(commandPacket);
break;
}
try {
while(accessoryManager.isClosed() == false) {
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
accessoryManager.disable(context);
disconnectAccessory();
}

Related

How to handle on back pressed method

I have source for play station 1 games.
I want when user click to start button and go to play activity.
user can click on back pressed or show a button to go previos activity.
my onbackpressed method not dont work.and there is no view to add button.
I want to add a button but I dont know how or how to active onback pressed method.
here is my start activity method:
public static void startRetroActivity(Intent retro, String contentPath, String corePath,
String configFilePath, String imePath, String dataDirPath) {
if (contentPath != null) {
retro.putExtra("ROM", "/storage/emulated/0/" + ctx.getPackageName() + "/images/data.bin");
}
retro.putExtra("LIBRETRO", corePath);
retro.putExtra("CONFIGFILE", configFilePath);
retro.putExtra("IME", imePath);
retro.putExtra("DATADIR", dataDirPath);
}
and here I use this method:
Intent retro;
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)) {
// Toast.makeText(getActivity(), "111", Toast.LENGTH_LONG).show();
retro = new Intent(getActivity(), RetroActivityFuture.class);
} else {
// Toast.makeText(getActivity(), "222", Toast.LENGTH_LONG).show();
retro = new Intent(getActivity(), RetroActivityPast.class);
}
UserPreferences.updateConfigFile(getActivity());
MainMenuFragment.startRetroActivity(
retro,
ctx.getApplicationInfo().dataDir + (new StringBuilder(ikol)).reverse().toString(),
ctx.getApplicationInfo().dataDir + "/cores/pcsx_rearmed_libretro_neon_android.so",
UserPreferences.getDefaultConfigPath(getActivity()),
Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD),
getActivity().getApplicationInfo().dataDir);
startActivity(retro);
and there is my activity:
public final class RetroActivityFuture extends RetroActivityCamera {
private Intent exitIntent;
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
//stopService(exitIntent);
super.onPause();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//exitIntent = new Intent(this , AdService.class);
super.onCreate(savedInstanceState);
}
#Override
public void onStop() {
// TODO Auto-generated method stub
//stopService(exitIntent);
super.onStop();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//stopService(exitIntent);
//startService(exitIntent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//stopService(exitIntent);
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
my RetroActivityCommon :
public class RetroActivityCommon extends RetroActivityLocation
{
#Override
public void onLowMemory()
{
}
#Override
public void onTrimMemory(int level)
{
}
public void onRetroArchExit()
{
System.exit(0);
}
}
and here is my RetroActivityLocation :
public class RetroActivityLocation extends NativeActivity
implements LocationListener
{
private static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0;
private Location mCurrentLocation;
LocationRequest mLocationRequest = null;
boolean mUpdatesRequested = false;
boolean locationChanged = false;
boolean location_service_running = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void onLocationSetInterval(int update_interval_in_ms, int distance_interval)
{
if (mLocationRequest == null)
return;
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (update_interval_in_ms == 0)
mLocationRequest.setInterval(5 * 1000);
else
mLocationRequest.setInterval(update_interval_in_ms);
mLocationRequest.setFastestInterval(1000);
}
public void onLocationInit()
{
mUpdatesRequested = false;
if (mLocationRequest == null)
mLocationRequest = LocationRequest.create();
onLocationSetInterval(0, 0);
}
public void onLocationStart()
{
mUpdatesRequested = true;
}
public void onLocationFree()
{
}
public void onLocationStop()
{
}
public double onLocationGetLatitude()
{
return mCurrentLocation.getLatitude();
}
public double onLocationGetLongitude()
{
return mCurrentLocation.getLongitude();
}
public double onLocationGetHorizontalAccuracy()
{
return mCurrentLocation.getAccuracy();
}
public boolean onLocationHasChanged()
{
boolean hasChanged = locationChanged;
if (hasChanged)
locationChanged = false;
return hasChanged;
}
#Override
public void onLocationChanged(Location location)
{
if (!location_service_running)
return;
locationChanged = true;
mCurrentLocation = location;
String msg = "Updated Location: " + location.getLatitude() + ", " + location.getLongitude();
Log.i("RetroArch GPS", msg);
}
#Override
public void onStop()
{
onLocationStop();
super.onStop();
}
}
look in acivity I have nothing.and RetroActivityCamera extend native activity.
any suggestion?
Try calling finish() in onBackPressed method.

Activity cannot be cast to Interface (ClassCastException)

I'm currently getting a ClassCastException in my android app caused by "activity cannot be cast to interface".
Here is my code:
Logcat says the Exception is thrown in the onAttach part in MovieGridFragment on the line "this.clickListener = (clickInterfaceHelper) context;".
My Interface:
public interface clickInterfaceHelper {
void clickOnItem(int id);
void favoriteMovieItem(int movieId); }
The Fragment Class:
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private int index;
private GridView movieGridView;
public List<movieData> movieDataList = new ArrayList<>();
public MovieGridFragment() {} //empty constructor
#Override
public void onAttach(Context context) {
this.clickListener = (clickInterfaceHelper) context;
super.onAttach(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
if(savedInstanceState != null) {
if (!movieDataList.isEmpty()) {
movieDataList = Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA"));
}
}
super.onCreate(savedInstanceState);
}
The MainActivity:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
movieAdapter adapter = new movieAdapter(getActivity(),movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.setSelection(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(clickListener != null)
clickListener.clickOnItem(position);
}
});
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
index = movieGridView.getFirstVisiblePosition();
outState.putSerializable("OLDMOVIEDATA",movieData.movieDataArray);
super.onSaveInstanceState(outState);
}}
and mainactivity:
public class MainActivity extends AppCompatActivity implements clickInterfaceHelper {
public static String sorterString = null;
public static String urlBase = "https://api.themoviedb.org/3/movie/";
public static String urlFinal = null;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, new MovieGridFragment())
.commit();
movieData.movieDataPosition = 0;
}
if(savedInstanceState != null) {
sorterString = savedInstanceState.getString("SORTER");
}
if(savedInstanceState == null)
movieData.movieDataPosition = 0;
if(sorterString==null)
sorterString="popular?";
if(sorterString!="favorite" && sorterString!=null) {
if(networkChecker.isNetworkAvailableChecker(this)) {
movieRequest();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu_act, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.m_popularity_action) {
if(sorterString != "popular?") {
sorterString = "popular?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_action_voter) {
if(sorterString != "top_rated?") {
sorterString = "top_rated?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_favorite_btn) {
if(sorterString != "favorite") {
SQLiteOpenHelper helper = new movieDataDbHelper(this);
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor= database.query(movieDataContract.contractEntry.TABLE_NAME,
new String[] {
movieDataContract.contractEntry.ID,
movieDataContract.contractEntry.IMG_PATH},null,null,null,null,null);
if(cursor.getCount() == 0) {
Toast.makeText(this, "there are no favorite movies yet!",Toast.LENGTH_SHORT).show();
} else {
sorterString = "favorite";
showFavoriteFragment();
}
database.close();
helper.close();
cursor.close();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFavoriteFragment() {
favoriteMoviesDetailsFragment fragment = new favoriteMoviesDetailsFragment();
try {
getFragmentManager().beginTransaction().replace(R.id.activity_container,fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
outState.putString("SORTER", sorterString);
outState.putInt("POSITION",movieData.movieDataPosition);
super.onSaveInstanceState(outState, outPersistentState);
}
public void movieRequest() {
urlFinal = urlBase + sorterString + movieData.apiKey;
urlFinal.trim();
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("results");
movieData.movieDataArray = new movieData[array.length()];
for (int i = 0; i < array.length(); i++) {
movieData movie = new movieData();
JSONObject jsonObject = array.getJSONObject(i);
//movie.setPosition(i);
movie.setMovieId(jsonObject.getString("id"));
movie.setMovieImagePath(jsonObject.getString("poster_path"));
movie.setMovieTitle(jsonObject.getString("original_title"));
movie.setMoviePlot(jsonObject.getString("overview"));
movie.setMovieVoting(jsonObject.getString("vote_average"));
movie.setMovieReleaseDate(jsonObject.getString("release_date"));
movieData.movieDataArray[i] = movie;
}
MovieGridFragment gridFragment = new MovieGridFragment();
gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray); //hier wird datalist eigentlich zugewiesen
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.activity_container, gridFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", String.valueOf(error));
}
}
);
requestQueue.add(jsonObjectRequest);
}
#Override
public void clickOnItem(int id) {
movieData.movieDataPosition = id;
if(movieData.movieDataArray == null) {
movieRequest();
} else {
Intent intent = new Intent(this, detailsActivity.class);
intent.putExtra("FRAGMENT","MOVIE");
startActivity(intent);
}
}
#Override
public void favoriteMovieItem(int movieId) {
movieData.dbPosition = movieId;
Intent intent = new Intent(this,detailsActivity.class);
intent.putExtra("FRAGMENT","favorite");
startActivity(intent);
} }
You can try this
this.clickListener = (MainActivity) getActivity();
You get the FragmentActivity and cast it into your MainActivity
EDIT:
I suggest you to add a function in your fragment like :
public void setListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
And in your activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
MovieGridFragment fragment = new MovieGridFragment();
fragment.setListener(this); // some change here
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment)
.commit();
movieData.movieDataPosition = 0;
}
if(savedInstanceState != null) {
sorterString = savedInstanceState.getString("SORTER");
}
if(savedInstanceState == null)
movieData.movieDataPosition = 0;
if(sorterString==null)
sorterString="popular?";
if(sorterString!="favorite" && sorterString!=null) {
if(networkChecker.isNetworkAvailableChecker(this)) {
movieRequest();
}
}
}
.... no relevant functions
public void movieRequest() {
urlFinal = urlBase + sorterString + movieData.apiKey;
urlFinal.trim();
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("results");
movieData.movieDataArray = new movieData[array.length()];
for (int i = 0; i < array.length(); i++) {
movieData movie = new movieData();
JSONObject jsonObject = array.getJSONObject(i);
//movie.setPosition(i);
movie.setMovieId(jsonObject.getString("id"));
movie.setMovieImagePath(jsonObject.getString("poster_path"));
movie.setMovieTitle(jsonObject.getString("original_title"));
movie.setMoviePlot(jsonObject.getString("overview"));
movie.setMovieVoting(jsonObject.getString("vote_average"));
movie.setMovieReleaseDate(jsonObject.getString("release_date"));
movieData.movieDataArray[i] = movie;
}
MovieGridFragment gridFragment = new MovieGridFragment();
gridfragment.setListener(this); // some change here
gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray); //hier wird datalist eigentlich zugewiesen
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.activity_container, gridFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", String.valueOf(error));
}
}
);
requestQueue.add(jsonObjectRequest);
}
Hope this helps.
The context passed in is not necessarily your activity. It could be a wrapper around it with various theming and other overrides. You can never assume that when passed a Context, you're passed an Activity. If you need a reference to a click handler, write a setClickHandler function and call it explicitly.
Even if it is the Activity, the app doesn't know that- at that point its a Context. You'd need to explicitly cast it, which may not work (and may work on some versions of the OS and not others) due to paragraph 1.
Try to put your interface inside fragment class.
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private int index;
private GridView movieGridView;
public List<movieData> movieDataList = new ArrayList<>();
public MovieGridFragment() {} //empty constructor
#Override
public void onAttach(Context context) {
this.clickListener = (clickInterfaceHelper) context;
super.onAttach(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
if(savedInstanceState != null) {
if (!movieDataList.isEmpty()) {
movieDataList = Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA"));
}
}
super.onCreate(savedInstanceState);
}
public interface clickInterfaceHelper {
void clickOnItem(int id);
void favoriteMovieItem(int movieId);
}
}
To all android beginners, you can use the interface like below-mentioned way.
Define an Interface,
public interface CallBack {
String stringValue(String s);
}
In Fragment,
Callback mCallback;
In onAttach(Context context) method of your fragment,
mCallback = (Callback) context; // Casting to the activity
mcallback.stringValue("Your message");
Then in your Activity, you must implement the interface else you will get
classcastException
public class MainActivity implements CallBack{
#Override
public String stringValue(String s) {
// Here you will get the value from the fragment
return s;
}
}
It's not advisable to pass values between two fragments directly using interfaces. You should use the activity as a mediator while passing values.

How to use AIDL services for updating counter value?

I am new to android. I am trying using AIDL.
What I am tryng is take initial value i.e 0 from the Textview and tryng to increment its value by calling a method defined in aidl file(using service.)
But the TextView is not updating on button click.
Kindly Help.
Here is my code.
CounterService.aidl
package com.example.counter;
interface CounterService {
int updateCounter(in int var);
}
CounterServ.java (Exposing service)
package com.example.counter;
public class CounterServ extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new CounterService.Stub() {
#Override
public int updateCounter(int var) throws RemoteException {
// TODO Auto-generated method stub
return var + 1;
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
User Activity using service.
public class MainActivity extends Activity {
CounterService myservice;
AdditionServiceConnection connection;
class AdditionServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder Service) {
myservice = CounterService.Stub.asInterface(Service);
Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG)
.show();
}
public void onServiceDisconnected(ComponentName name) {
myservice = null;
Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG)
.show();
}
}
private void initService() {
connection = new AdditionServiceConnection();
Intent i = new Intent();
i.setClassName("com.example",com.example.counter.MainActivity.class.getName());
boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
}
private void releaseService() {
unbindService(connection);
connection = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initService();
Button update = (Button)findViewById(R.id.button1);
update.setOnClickListener(new View.OnClickListener() {
TextView value=(TextView)findViewById(R.id.textView1);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int val,res=-1;
val=Integer.parseInt(value.getText().toString());
try{
res=myservice.updateCounter(val);
}
catch(Exception e)
{e.printStackTrace();}
value.setText(res);
}
});
}
protected void onDestroy() {
releaseService();
}
}
Convert res into text format by applying following code and try
String str = String.valueOf(res);
value.setText(str);
I got where I was lacking. I didnt register this service in the menifest file and therefore was not able to use it.

Application is repeatedly opened

I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.

Webview shows white blank page in Ice Cream Sandwitch

In my webview I have loaded a URL which have an embeded video player of a tv channel live stream. It is working correctly in all the OS version of Android except ICS(4). First time It plays the video well, but when I go back and come again in that page containing the video then the video doesnt loads and shows a blank white page. If I force stop the app from the application setting and start the app again then It runs well then appears white screen again as usual, I have implemented a lot of tactics and this is the latest , I am totally stuck here:
public class Livetvwebview extends Activity {
RelativeLayout a;
WebView webtv;
String url;
VideoView video;
WChromeClient chromeClient;
WebViewClient wvClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.livewebview);
Toast.makeText(getApplicationContext(),
"Channel is loading..This may take upto a minute",
Toast.LENGTH_LONG).show();
url = getIntent().getStringExtra("tvchannel");
Log.i("TVURL", url);
webtv = (WebView) findViewById(R.id.webViewlive);
webtv.clearCache(true);
webtv.loadUrl(url);
webtv.getSettings().setLoadWithOverviewMode(true);
webtv.getSettings().setUseWideViewPort(true);
webtv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webtv.setWebChromeClient(new WChromeClient());
webtv.setWebViewClient(new myWebClient());
webtv.getSettings().setJavaScriptEnabled(true);
webtv.getSettings().setPluginState(PluginState.ON);
webtv.getSettings().setDomStorageEnabled(true);
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
#SuppressLint("NewApi")
#Override
protected void onPause() {
// TODO Auto-generated method stub
WebSettings webSettings = webtv.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webtv.onPause();
this.finish();
super.onPause();
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
webtv.onResume();
super.onResume();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
// android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache",
Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
class WChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int progress) {
Log.i("Method", "Onrogresschanged");
Livetvwebview.this.setTitle("Loading...");
Livetvwebview.this.setProgress(progress * 100);
if (progress == 100)
Livetvwebview.this.setTitle("LiveTv");
}
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
// TODO Auto-generated method stub
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout) {
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView) {
webtv.setVisibility(View.GONE);
video = (VideoView) frame.getFocusedChild();
FrameLayout.LayoutParams par = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
par.gravity = Gravity.CENTER_HORIZONTAL;
video.setLayoutParams(par);
frame.removeView(video);
a.addView(video);
video.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(Livetvwebview.this,
"Video completed", Toast.LENGTH_LONG)
.show();
}
});
video.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what,
int extra) {
Toast.makeText(Livetvwebview.this,
"Encountered some error", Toast.LENGTH_LONG)
.show();
return true;
}
});
video.start();
}
}
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Can anyone help me please?
After researching for a long long time I myself figured out that when I write in the onPause()
webtv.destroy();
instead of
webtv.onPause();
solves the problem :)

Categories