I put a progress bar in my android studio project , and want it to move , but i don't know how to do that . I tried to look for tutorials on YouTube and follow along , but that didn't work out for me. Then i looked on google for tutorials but that didn't work for me . When i search them up i only see tutorials with the circle loading bars and I want mine to be horizontal . I only know where to start the loading bar but i really want to know how to make it move and then go into the game . I don't have any code because when i seen that it wasn't working i just deleted it . If anybody has a good tutorial or code that could help me i would appreciate very much . Thanks.
have very easy way to use progress bar within whole code
custom_progressbar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="#+id/progressbar_view"
android:layout_width="#dimen/_70sdp"
android:layout_height="#dimen/_70sdp"
android:indeterminate="true"
android:padding="#dimen/_10sdp" />
</RelativeLayout>
CustomProgressBar.java
public class CustomProgressBar extends Dialog {
Activity activity;
public CustomProgressBar(Activity act) {
super(act);
this.activity = act;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_progressbar);
setCancelable(false);
// set backgroung transparent
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
}
and apply whenever you want activity or fragment
public CustomProgressBar customProgressBar;
customProgressBar = new CustomProgressBar(context);
customProgressBar.show();
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView loading;
private int progressStatus = 0;
private Handler pHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
loading = (TextView) findViewById(R.id.loading);
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
progressStatus ++;
android.os.SystemClock.sleep(50);
pHandler.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
pHandler.post(new Runnable() {
#Override
public void run() {
loading.setText("COMPLETE");
}
});
}
}).start();
}
This code works. You should be able to use the default XML code for the ProgressBar. You will need to add the elements, for example, the actual progress bar in the visual design. You will need to add an extra '}' at the end I think.
Check this: Infact you have to code for the horizontal progress bar movement and set its progress, it's specially used in downloading to show percentage of operation completion.
XML code:
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="20dp"
android:indeterminate="false"
android:max="100"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1" />
java code:
public class MainActivity extends Activity {
private ProgressBar progressBar;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
textView = (TextView) findViewById(R.id.textView1);
//Long operation by thread
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
//Update progress bar with completion of operation
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
//Just to display the progress slowly
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items
//to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="50">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:id="#+id/Bar1"
android:max="10"
android:padding="15dp"
android:paddingTop="5dp"
android:paddingRight="20dp"
android:paddingLeft="20dp">
</ProgressBar>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startProgress"
android:text="Start" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar2"
android:layout_gravity="center_horizontal" />
</LinearLayout>
MainActivity.java
package com.example.dell.vlakna;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import static com.example.dell.vlakna.R.layout.activity_main;
public class MainActivity extends Activity {
private ProgressBar bar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
bar = (ProgressBar) findViewById(R.id.Bar1);
}
public void startProgress(View view) {
bar.setProgress(0);
new Thread(new Task()).start();
}
class Task implements Runnable {
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bar.setProgress(value);
}
}
}
}
this code run good.
Related
I am using this code, everything are working fine, but progressbar is not showing. I want to block my ui during the method implementation and want to show progressbar. I want to get behaviour like progressDialog.
Here is my method
public void effct(int effectNo) {
final int finalEffectNO = effectNo;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressLayout.setVisibility(View.VISIBLE);
progressLayoutLinear.setVisibility(View.VISIBLE);
Thread thread = new Thread(){
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
imageViewFragment.applyEffect(finalEffectNO);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressLayout.setVisibility(View.GONE);
progressLayoutLinear.setVisibility(View.GONE);
}
});
}
};
thread.start();
}
My xml code for progressLayout
<LinearLayout
android:id="#+id/progressBarLinearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:padding="12dp"
android:visibility="gone"
android:orientation="horizontal">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:textSize="18sp"/>
</LinearLayout>
For above your requirement you must use ProgressDialog for same, here is an example
Example
Try using an AsyncTask instead of Thread, something like this :
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressLayoutLinear.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(final Void ... params ) {
runOnUiThread(new Runnable() {
#Override
public void run() {
imageViewFragment.applyEffect(finalEffectNO);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
return null;
}
#Override
protected void onPostExecute( final Void result ) {
progressLayoutLinear.setVisibility(View.GONE);
}
}.execute();
Hope this helps
There’s a few ways to solve your problem - check this video for more information. The most basic approach might be an AsyncTask, which could look like this:
public class DummyAsyncTask extends AsyncTask<Void, Void, Void> {
private final Window window;
private final ProgressBar progressBar;
public DummyAsyncTask(Window window, ProgressBar progressBar) {
this.window = window;
this.progressBar = progressBar;
}
#Override protected void onPreExecute() {
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.VISIBLE);
}
#Override protected Void doInBackground(Void... voids) {
// Do the heavy lifting.
}
#Override protected void onPostExecute(Void aVoid) {
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.GONE);
}
}
You execute it by running new DummyAsyncTask(/* params */).execute();.
Do note that AsyncTask does not adhere to the lifecycle and holding a reference to a Context aware instance is just asking for trouble. A safer alternative might be using LiveData:
public void effect(int effectNo) {
// Show progress and disable user interaction here.
final ListData<Content> data = model.applyEffect(effectNo);
data.observe(this, (Observer<Content>) c -> {
// Apply results, hide progress & enable user interaction.
});
}
Given the above, you should be careful how you handle showing & hiding progress, so you don’t accidentally disable user interaction forever.
I've to just show a count down fragment at certain trigger which includes a progress bar that reduces count on tick of a countdown timer.
I'm using following simple steps:
Call startTimer() in onCreateView of fragment.
In startTimer() define a CountDownTimer class where onTick method reduces progress of a ProgressBar and onFinish shows a Toast message.
Start this timer on UI thread using getActivity().runOnUIThread()
Problem is the timer executes but ProgressBar keeps showing indeterminate progress i.e. it remains unchanged. Toast is also seen at the finish but nothing changes for progress bar.
What's going wrong here?
Below is the current code:
public class IncomingRequestFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private FrameLayout root;
private CountDownTimer mCountDownTimer;
private ProgressBar mProgressBar;
public IncomingRequestFragment() {
// Required empty public constructor
}
public static IncomingRequestFragment newInstance(String param1, String param2) {
IncomingRequestFragment fragment = new IncomingRequestFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
int progress=25;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
root = (FrameLayout) inflater.inflate(R.layout.fragment_incoming_request, container, false);
mProgressBar = (ProgressBar) root.findViewById(R.id.countDown);
progress = mProgressBar.getMax();
mProgressBar.setIndeterminate(false);
mProgressBar.setProgress(progress);
startTimer();
return root;
}
private void startTimer() {
mCountDownTimer = new CountDownTimer(25000,1000) {
#Override
public void onTick(long millisUntilFinished) {
mProgressBar.setProgress(progress--);
Log.d("count",String.valueOf(progress));
}
#Override
public void onFinish() {
Toast.makeText(getContext(),"You just missed a trip!",Toast.LENGTH_SHORT).show();
}
};
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mCountDownTimer.start();
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Layout XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.taxiwaxidriver.ui.fragments.IncomingRequestFragment">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/countDown"
android:layout_margin="60dp"
android:max="25"
android:progressTint="#android:color/holo_blue_dark"
android:progressBackgroundTint="#android:color/holo_blue_dark"
android:progress="25"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:padding="12dp"
android:weightSum="2"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/white"
android:text="REJECT"
android:id="#+id/rideLater"
android:background="#drawable/rounded_button_left"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ACCEPT"
android:textColor="#color/white"
android:background="#drawable/rounded_button_right"
android:id="#+id/rideNow"/>
</LinearLayout>
</FrameLayout>
Output of above code is:
05-07 10:49:05.623 21455-21455 D/count: 24
05-07 10:49:06.626 21455-21455 D/count: 23
05-07 10:49:07.636 21455-21455 D/count: 22
05-07 10:49:08.653 21455-21455 D/count: 21
.
.
.
05-07 10:49:28.917 21455-21455 D/count: 1<br>
mistake was missing the style attribute for ProgressBar defined in XML
style=""?android:attr/progressBarStyleHorizontal"
Thanks to pskink's comment
Ok, so, i want to make something like this:
http://postimg.org/image/qs3okxitf/
Now, im using zbarscannerview like this:
public class BarKodScreen extends AppCompatActivity implements ZBarScannerView.ResultHandler {
private ZBarScannerView mView;
private BarcodeFormat barcodeFormatEAN13, barcodeFormatEAN8;
private List<BarcodeFormat> listaZaFormat = new ArrayList<BarcodeFormat>();
private ImageView img;
private LinearLayout lejout;
private View kamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barkod);
mView = new ZBarScannerView(this);
lejout = (LinearLayout) findViewById(R.id.cameraPreview);
img = (ImageView) findViewById(R.id.cameraImageView);
kamera = (View) findViewById(R.id.zaKameru);
kamera = mView;
lejout.addView(kamera);
lejout.addView(kamera);
lejout.removeView(img);
lejout.addView(img);
barcodeFormatEAN13 = BarcodeFormat.EAN13;
barcodeFormatEAN8 = BarcodeFormat.EAN8;
listaZaFormat.add(barcodeFormatEAN13);
listaZaFormat.add(barcodeFormatEAN8);
mView.setFormats(listaZaFormat);
}
#Override
public void onResume() {
super.onResume();
mView.setResultHandler(this); // Register ourselves as a handler for scan results.
mView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.v("GetCOntent", rawResult.getContents()); // Prints scan results
barKodZahtev(rawResult.getContents());
}
}
and my xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cameraPreview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="#+id/zaKameru"
android:layout_width="match_parent"
android:layout_height="150dp"/>
<ImageView
android:id="#+id/cameraImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.6"
android:src="#drawable/share" />
</LinearLayout>
What I dont understand is how to add the image(text from the screenshot) as a child view for my zbarscannerView.
Check out their rapository on github, they have something there.
I'm trying to simply pull the system time, and input it into the TextView, wait one second, then update it. I use a while loop for this, though when the app starts, it freezes, with no display. Am I doing something wrong? perhaps a better way to do this? I need the method to have the ability to pull the integers so I can match them to set ones, I hope to add in an alarm feature.
MainActivity.java:
package com.example.polyphaser;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeUpdate();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void timeUpdate() {
boolean loop = true;
while (loop = true) {
String currentTimeString = new SimpleDateFormat("HH:mm:ss").format(new Date());
// textView is the TextView view that should display it
TextView sysTime = (TextView) findViewById(R.id.timeDisplay);
sysTime.setText(currentTimeString);
Thread.sleep(1000);
}
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/timeDisplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="50sp" />
</LinearLayout>
</LinearLayout>
This show how to use a handler:
public class MainActivity extends Activity {
private Handler handler = new Handler();
private Runnable runnable;
private TextView sysTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sysTime = (TextView) findViewById(R.id.timeDisplay);
runnable = new Runnable() {
#Override
public void run() {
timeUpdate();
handler.postDelayed(this, 1000);
}
};
}
#Override
protected void onResume() {
handler.postDelayed(runnable, 1000);
super.onResume();
}
#Override
protected void onPause() {
handler.removeCallbacks(runnable);
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void timeUpdate() {
String currentTimeString = new SimpleDateFormat("HH:mm:ss").format(new Date());
// textView is the TextView view that should display it
sysTime.setText(currentTimeString);
}
}
A much better way to do this is with a handler.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sysTime.setText(...
}
}, 1000);
I'm pretty sure the while loop locks up your main thread which is why it freezes.
Check out the handler at the dev pages.
http://developer.android.com/reference/android/os/Handler.html
You need move while loop into its own thread, so far you are sleep on UI thread, which means all UI drawing things are blocked. When you need update UI in second counting thread, call Activity.runInUIThread(new Runnable(...){...}) to post the update.
The big problem wrong, look at this line in your code:
while (loop = true)
I'm guessing the compiler optimizes out that statement (loop is already true, loop = true does not evaluate to a boolean, and furthermore, loop cannot be accessed by anything to change its value to false) and so you have a while (false) which results in the body of your loop never executing.
You should have that update occur in another read and update the textview using runonuithread.
I am trying to make a remote control for a Google TV.
I want to change the text I have in a layout (TextView statusText) with connected when the device has successfully connected. But I get an exception when I try to do this:
"07-07 22:42:20.870: E/AndroidRuntime(5750):android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
"Appreciate any help/pointers
Here is my MainActivity.java and main.xml:
MainActivity.java:
package uk.co.mypack.gtvremote;
//imports removed for paste
public class MainActivity extends Activity implements ClientListener{
private AnymoteSender anymoteSender;
private TextView statusText;
protected AnymoteClientService mAnymoteClientService;
private static String statusPrefix = "Status: ";
private Context mContext;
private ProgressBar progressBar;
private Handler handler;
private TouchHandler touchPadHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.a_progressbar);
progressBar.setVisibility(View.VISIBLE);
mContext = this;
ImageButton upArrowButton = (ImageButton) findViewById(R.id.upArrow);
ImageButton leftArrowButton = (ImageButton) findViewById(R.id.leftArrow);
ImageButton centreButton = (ImageButton) findViewById(R.id.centreButton);
ImageButton rightArrowButton = (ImageButton) findViewById(R.id.rightArrow);
ImageButton downArrowButton = (ImageButton) findViewById(R.id.downArrow);
upArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_UP);
}
});
leftArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_LEFT);
}
});
centreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_CENTER);
}
});
rightArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_RIGHT);
}
});
downArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_DOWN);
}
});
handler = new Handler();
// Bind to the AnymoteClientService
Intent intent = new Intent(mContext, AnymoteClientService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
statusText = (TextView) findViewById(R.id.statusText);
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
/*
* ServiceConnection listener methods.
*/
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAnymoteClientService = ((AnymoteClientService.AnymoteClientServiceBinder) service)
.getService();
mAnymoteClientService.attachClientListener(MainActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mAnymoteClientService.detachClientListener(MainActivity.this);
mAnymoteClientService = null;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConnected(AnymoteSender anymoteSender) {
if (anymoteSender != null) {
// Send events to Google TV using anymoteSender.
// save handle to the anymoteSender instance.
this.anymoteSender = anymoteSender;
//THIS IS WHERE I AM TRYING TO SET THE TEXTVIEW
TextView localStatusText = (TextView) findViewById(R.id.statusText);
localStatusText.setText(statusPrefix + "Connected to GoogleTV");
//ABOVE IS WHERE I AM TRYING TO SET THE TEXTVIEW
// Attach touch handler to the touchpad view
touchPadHandler = new TouchHandler(
findViewById(R.id.touchPad), Mode.POINTER_MULTITOUCH, anymoteSender);
} else {
statusText.setText(statusPrefix + "Connection attempt failed, cant find send handler");
//attempt to connect again?
//attemptToConnect();
}
// Hide the progressBar once connection to Google TV is established.
handler.post(new Runnable() {
public void run() {
progressBar.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onDisconnected() {
// show message to tell the user about disconnection.
statusText.setText(statusPrefix + "Disconnected");
// Try to connect again if needed. This may be need to be done via button
attemptToConnect();
this.anymoteSender = null;
}
#Override
public void onConnectionError() {
// show message to tell the user about disconnection.
statusText.setText(statusPrefix + "Connection error encountered");
// Try to connect again if needed.
attemptToConnect();
this.anymoteSender = null;
}
#Override
protected void onDestroy() {
if (mAnymoteClientService != null) {
mAnymoteClientService.detachClientListener(this);
}
unbindService(mConnection);
super.onDestroy();
}
public void attemptToConnect()
{
//stub to invoke connection attempt
}
private void sendKeyEvent(final int keyEvent) {
// create new Thread to avoid network operations on UI Thread
if (anymoteSender == null) {
Toast.makeText(MainActivity.this, "Waiting for connection",
Toast.LENGTH_LONG).show();
return;
}
anymoteSender.sendKeyPress(keyEvent);
}
}
Main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/control_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="#dimen/padding_medium"
android:text="#string/control_msg"
android:textSize="90dp"
tools:context=".MainActivity" />
<LinearLayout
android:id="#+id/middlePanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/statusText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Status: Disconnected - startup"
android:textSize="20dp" />
<ImageView
android:id="#+id/touchPad"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/greysquare"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageButton
android:id="#+id/upArrow"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/blackuparrow" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/leftArrow"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/blackleftarrow" />
<ImageButton
android:id="#+id/centreButton"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/emptycircle"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp" />
<ImageButton
android:id="#+id/rightArrow"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/blackrightarrow" />
</LinearLayout>
<ImageButton
android:id="#+id/downArrow"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/blackdownarrow" />
</LinearLayout>
</LinearLayout>
<ProgressBar
android:id="#+id/a_progressbar"
style="#android:style/Widget.ProgressBar.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>
The onConnected() callback is not called on the Main UI thread, but on a separate thread that is used by the Service. So it is not able to access the TextView created in Main UI thread. What you should do is create a Handler in the main UI thread and then use that handler to post a runnable that makes changes to the TextView. You can read more about Handlers on the Android developer site.