Link java class to xml file in android - java

I would like to link java class to my xml file.
There is no error in the coding however, it gave me force close.
I would like to know what's wrong with it.
Can anyone please advice me?
I've one main java class, having the same code as this, as I would like to display the same thing for both xml layout.
The main java class work perfectly fine, however, when I try to convert the coding to second java class, the force close error occurs.
Here is my coding.
public class event extends ListActivity{
ArrayList<String> psi;
public TextView psi_text;
TextView weather;
ImageView image;
private static Handler mHandler = new Handler();
class MyWeather{
String conditiontext;
String conditiontemp;
String conditiondate;
public String forecastToString(){
return
conditiontext + "\n" + " " + conditiontemp + "°C" ;
}
}
String[] Category = {
"Scientist for a day",
"Science Trail",
"Megalog Return"
};
String [] dates = {
"Today",
"Tomorrow",
"This Week"
};
Spinner s1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event);
weather = (TextView)findViewById(R.id.weather);
image = (ImageView)findViewById(R.id.image);
psi = new ArrayList<String>();
psi_text = (TextView) findViewById(R.id.psi_text);
TabHost th =(TabHost)findViewById(R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1");
specs.setContent(R.id.tab1);
specs.setIndicator("Suggested");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.tab2);
specs.setIndicator("All");
th.addTab(specs);
TabWidget tw = (TabWidget) th.findViewById(android.R.id.tabs);
View tab1 = tw.getChildTabViewAt(0);
TextView tv = (TextView) tab1.findViewById(android.R.id.title);
tv.setTextSize(15);
tv.setPadding(0, 0, 0, 50);
View tab2 = tw.getChildTabViewAt(1);
TextView tv1 = (TextView) tab2.findViewById(android.R.id.title);
tv1.setTextSize(15);
tv1.setPadding(0, 0, 0, 50);
//GridView
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category));
//SpinnerView
s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, dates);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long arg3) {
int index = s1.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have seleted item :" + dates[index] , Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?>arg0) {}
});
try {
URL url = new URL(
"http://app2.nea.gov.sg/data/rss/nea_psi.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList websiteList = fstElmnt.getElementsByTagName("psi");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
psi.add(""+ ((Node) websiteList.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
String temp = Html.fromHtml(psi.get(0)).toString();
String a[] = temp.split("\\)");
psi_text.setText(""+a[0]+")");
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.forecastToString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
String weatherCode = conditionNode.getAttributes()
.getNamedItem("code")
.getNodeValue()
.toString();
// thunderstorms
if(weatherCode.equals("4")){
mHandler.post(new Runnable() {
#Override
public void run() {
// This gets executed on the UI thread so it can safely modify
// Views
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//isolated thunderstorms
else if ( weatherCode.equals("37")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//scattered thunderstorms
else if ( weatherCode.equals("38")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//scattered thunderstorms
else if ( weatherCode.equals("39")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//thundershowers
else if ( weatherCode.equals("45")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//isolated thundershowers
else if ( weatherCode.equals("47")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.thunderstorm);
}
});
}
//drizzle
else if ( weatherCode.equals("9")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//showers
else if ( weatherCode.equals("11")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//showers
else if ( weatherCode.equals("12")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//scattered showers
else if ( weatherCode.equals("40")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.rainy);
}
});
}
//hail
else if ( weatherCode.equals("17")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.hail);
}
});
}
//mixed rain and hail
else if ( weatherCode.equals("35")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.hail);
}
});
}
//foggy
else if ( weatherCode.equals("20")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//haze
else if ( weatherCode.equals("21")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//smoky
else if ( weatherCode.equals("22")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.foggy);
}
});
}
//windy
else if ( weatherCode.equals("24")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.windy);
}
});
}
//cloudy
else if ( weatherCode.equals("26")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//fair (night)
else if ( weatherCode.equals("33")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//fair (day)
else if ( weatherCode.equals("34")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//partly cloudy
else if ( weatherCode.equals("44")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.cloudy);
}
});
}
//mostly cloudy (night)
else if ( weatherCode.equals("27")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.night_cloudy);
}
});
}
//partly cloudy (night)
else if ( weatherCode.equals("29")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.night_cloudy);
}
});
}
//mostly cloudy (day)
else if ( weatherCode.equals("28")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.day_cloudy);
}
});
}
//partly cloudy (day)
else if ( weatherCode.equals("30")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.day_cloudy);
}
});
}
//clear(night)
else if ( weatherCode.equals("31")) {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.moon);
}
});
}
//sunny
else {
mHandler.post(new Runnable() {
#Override
public void run() {
image.setImageResource(R.drawable.sunny);
}
});
}
myWeather.conditiontext = conditionNode.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString();
myWeather.conditiontemp = conditionNode.getAttributes()
.getNamedItem("temp")
.getNodeValue()
.toString();
return myWeather;
}
private Document convertStringToDocument(String src){
Document dest = null;
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(event.this,
e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return dest;
}
private String QueryYahooWeather(){
String qResult = "";
String queryString = "http://weather.yahooapis.com/forecastrss?w=1062617&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(queryString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(event.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return qResult;
}
public void onListItemClick(ListView parent, View v, int position,long id)
{
Toast.makeText(this, "You have selected " + Category[position], Toast.LENGTH_SHORT).show();
}
}

You don't have the
setContentView(R.layout.YOUR_XML_NAME);
in your activity. That's why you could not connect your java class and xml file

Related

How to use timer in Android

In my application i have timer for some works.
When my application running after some time my application freeze and not work any View !
In this timer every 500ms i emit socket.io
My Codes:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
socketPingTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (isSendSocketPing) {
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}
//Show ping (from search)
Constants.currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (isShownPing) {
detailToolbar_ping.setVisibility(View.VISIBLE);
if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);
} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else {
detailToolbar_ping.setVisibility(View.GONE);
}
}
});
socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}
});
How can i run this timers in another thread and not freeze my app ?
It should be something similar to this code:
class MyActivity extends Activity
{
private void executeLoop()
{
Handler myHandler = new Handler()
{
public void handleMessage(Message msg)
{
if (isShownPing)
{
detailToolbar_ping.setVisibility(View.VISIBLE);
if (checkSocketPingTimer > 500) {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.RED);
} else {
detailToolbar_ping.setText(checkSocketPingTimer + "");
detailToolbar_ping.setTextColor(Color.GREEN);
}
} else
{
detailToolbar_ping.setVisibility(View.GONE);
}
}
}
socketPingTimer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run()
{
if (isSendSocketPing)
{
checkSocketPingTimer += startSocketPingTimer;
if (checkSocketPingTimer == sendSocketPingTimer) {
currentTimerForSocket = System.currentTimeMillis();
try {
detailSocketUtils.getSendRTTforPing(currentTimerForSocket + "");
} catch (Exception e) {
}
}
myHandler.sendEmptyMessage();
socketPing = checkSocketPingTimer;
}
}
}, 500, startSocketPingTimer);
}
}
private void startTimerAtFixRate() {
android.os.Handler handler = new android.os.Handler();
Runnable updateTimerThread = new Runnable() {
public void run() {
//write here whatever you want to repeat
// Like I called Log statement
// After every 1 second this below statement will be executed
Log.e("CALLED-->", "TRUE");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(updateTimerThread, 100);
}

why do i get th java.lang.RuntimeException: Unable to start activity ComponentInfo

Hi guys im making a auto update after following a tutorial online then editing the code to suit my needs.. but im getting this error in my logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.Homescreen}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.UpdateService}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
can some one please help me
this is my service class
public class UpdateService extends Service {
public UpdateService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = "<MY Link for version>";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
boolean resp = response.contains("<div class='post-body entry-content' id='post-body-6791062644900393367' itemprop='description articleBody'>\n" +
"1.1.8\n" +
"<div style='clear: both;'></div>");
if (!resp) {
//Dialog to show update
Intent intent1 = new Intent(UpdateService.this, UpdateDialog.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
} else {
Toast.makeText(UpdateService.this, "No New Update Found..", Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(stringRequest);
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
then this is my dialog class
public static Button btn;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Update";
public static File Dir = new File(path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidAuthSession session = buildSession();
dropboxAPI = new DropboxAPI<AndroidAuthSession>(session);
Dir.mkdir();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setTitle("update");
alertDialog.setMessage("New update Available...");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadFromDropboxFromPath(path + "downloadFileFromDropbox", "Update/Myupdate.apk");
}
});
alertDialog.show();
}
static DropboxAPI<AndroidAuthSession> dropboxAPI;
private static final String APP_KEY = "********* **** ** **";
private static final String APP_SECRET = "XXX XX X X XX X";
private static final String ACCESSTOKEN = "xx x x xxx x x x x";
private DropboxAPI.UploadRequest request;
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
session.setOAuth2AccessToken(ACCESSTOKEN);
return session;
}
static final int UploadFromSelectApp = 9501;
static final int UploadFromFilemanager = 9502;
public static String DropboxUploadPathFrom = "";
public static String DropboxUploadName = "";
public static String DropboxDownloadPathFrom = "";
public static String DropboxDownloadPathTo = "";
private void UploadToDropboxFromPath(String uploadPathFrom, String uploadPathTo) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final String uploadPathF = uploadPathFrom;
final String uploadPathT = uploadPathTo;
Thread th = new Thread(new Runnable() {
public void run() {
File tmpFile = null;
try {
tmpFile = new File(uploadPathF);
} catch (Exception e) {
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(tmpFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
dropboxAPI.putFileOverwrite(uploadPathT, fis, tmpFile.length(), null);
} catch (Exception e) {
}
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
private void UploadToDropboxFromSelectedApp(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Upload from ..."), UploadFromSelectApp);
}
private void UploadToDropboxFromFilemanager(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, UploadFromFilemanager);
}
private void DownloadFromDropboxFromPath(String downloadPathTo, String downloadPathFrom) {
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
UpdateDialog.dropboxAPI.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == UploadFromFilemanager) {
final Uri currFileURI = intent.getData();
final String pathFrom = currFileURI.getPath();
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
UploadToDropboxFromPath(pathFrom, "/db-test/" + DropboxUploadName + pathFrom.substring(pathFrom.lastIndexOf('.')));
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
if (requestCode == UploadFromSelectApp) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final Uri uri = intent.getData();
DropboxUploadPathFrom = getPath(getApplicationContext(), uri);
if (DropboxUploadPathFrom == null) {
DropboxUploadPathFrom = uri.getPath();
}
Thread th = new Thread(new Runnable() {
public void run() {
try {
final File file = new File(DropboxUploadPathFrom);
InputStream inputStream = getContentResolver().openInputStream(uri);
dropboxAPI.putFile("/db-test/" + DropboxUploadName + file.getName().substring(file.getName().lastIndexOf("."),
file.getName().length()), inputStream, file.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
return 100;
}
#Override
public void onProgress(long arg0, long arg1) {
}
});
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
super.onActivityResult(requestCode, resultCode, intent);
}
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Audio.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public UpdateDialog getMain() {
return this;
}
}
then finally i call it in my homescreen class. with an intent
Intent intent = new Intent(Homescreen.this, UpdateService.class);
startActivity(intent);
UpdateService is a Service. It is not an Activity. To start a service, you call startService(), not startActivity().
As UpdateService is a service you have to start it by startService() method like #CommonsWare mentioned above. Also don't forget to add your service in Manifest file.
UpdateService is not an activity, It's a class that is extending services.
I think u r a very beginner.
Please go to Udacity and learn the concepts before tingling with android, otherwise, u will waste lot of your time in finding a copy-paste solution.

How to validate the Nymi band Asynchronously?

I am trying to validate the Nymi band asynchronously . But when I try to do that, I get the following exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I have all the toasts in the following method as you can see:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
But Still I get the exception. The method works fine when run normally in the onCreate() method,but fails to run asynchronously .
Edit: Even after removing all the toasts, I still get the exception.
Here is my Thread class,where I am calling the validate() asynchronously :
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
TestBluetooth tb=new TestBluetooth();
tb.startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
Here is the main class where I have the validate methods:
public class TestBluetooth extends Activity implements OnClickListener,ProvisionController.ProvisionProcessListener,
ValidationController.ValidationProcessListener {
boolean isBluetoothEnabled = false;
static boolean nclInitialized = false;
static final String LOG_TAG = "AndroidExample";
SharedPreferences prefs;
Button checkBlue,proviNymi,validateNymi,disconnectNymi;
ProvisionController provisionController;
ValidationController valiationController;
boolean connectNymi = true;
int nymiHandle = Ncl.NYMI_HANDLE_ANY;
NclProvision provision;
//NclProvision provisionmid;
String temp_ID,temp_Key;
public String keyuse;
public String iduse;
public LinearLayout progressbar;
public ProgressBar pbHeaderProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testbluetooth);
// I tried this too final Handler timedThread= new Handler(Looper.getMainLooper());
final Handler timedThread=new Handler();
timedThread.postDelayed(new Runnable() {
#Override
public void run() {
NymiAsync task=new NymiAsync();
task.execute(1,1,1);
}
},10000);
}
public void startValidatingNymi(){
progressbar = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
pbHeaderProgress=(ProgressBar) findViewById(R.id.pbHeaderProgress);
pbHeaderProgress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#1109EE"), android.graphics.PorterDuff.Mode.SRC_ATOP);
// prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
// prefs.edit().clear().commit();
prefs=getSharedPreferences(Util.SharedPrefKey,MODE_PRIVATE);
temp_ID = prefs.getString(Util.provID, null);
temp_Key = prefs.getString(Util.provKey, null);
if ((temp_ID!=null) || (temp_Key!=null)){
// SHOW THE SPINNER WHILE LOADING FEEDS
progressbar.setVisibility(View.VISIBLE);
//Toast.makeText(getBaseContext(), "Nymi band is already provisined" , Toast.LENGTH_SHORT ).show();
initializeNcl();
provision = new NclProvision();
load();
if (valiationController == null) {
valiationController = new ValidationController(TestBluetooth.this);
}
else {
valiationController.stop();
}
valiationController.startValidation(TestBluetooth.this, provision);
proviNymi = (Button) findViewById(R.id.provisionNymi);
proviNymi.setOnClickListener(this);
proviNymi.setEnabled(false);
validateNymi = (Button) findViewById(R.id.validateNymi);
validateNymi.setOnClickListener(this);
validateNymi.setEnabled(false);
disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
disconnectNymi.setOnClickListener(this);
disconnectNymi.setEnabled(false);
}else {
// Toast.makeText(getBaseContext(), "provision key is null!" , Toast.LENGTH_SHORT ).show();
checkBlue = (Button) findViewById(R.id.testBLuetooth);
checkBlue.setOnClickListener(this);
proviNymi = (Button) findViewById(R.id.provisionNymi);
proviNymi.setOnClickListener(this);
validateNymi = (Button) findViewById(R.id.validateNymi);
validateNymi.setOnClickListener(this);
validateNymi.setEnabled(false);
disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
disconnectNymi.setOnClickListener(this);
disconnectNymi.setEnabled(false);
}
}
public void load(){
iduse = prefs.getString(Util.provID,null);
Toast.makeText(getBaseContext(), iduse , Toast.LENGTH_SHORT ).show();
keyuse = prefs.getString(Util.provKey,null);
if ((iduse!=null)||(keyuse!=null)) {
provision.id = new NclProvisionId();
provision.id.v = Base64.decode(iduse, Base64.DEFAULT);
provision.key = new NclProvisionKey();
provision.key.v = Base64.decode(keyuse, Base64.DEFAULT);
final String temp= keyuse.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "the temp provision key is " +temp , Toast.LENGTH_SHORT ).show();
}
});
}else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Provision key is null!" , Toast.LENGTH_SHORT ).show();
}
});
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == checkBlue.getId()){
// Toast.makeText(getBaseContext(), "Checking bluetooth is enabled or not!" , Toast.LENGTH_SHORT ).show();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
} else {
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enable :)
// Toast.makeText(getBaseContext(), " bluetooth is not enabled !" , Toast.LENGTH_SHORT ).show();
isBluetoothEnabled=false;
}else {
// Toast.makeText(getBaseContext(), " bluetooth is enabled !" , Toast.LENGTH_SHORT ).show();
isBluetoothEnabled=true;
Log.d("is nabled", "blue is enalble");
}
}
}
if (v.getId()==proviNymi.getId()){
connectNymi = true;
initializeNcl();
nymiHandle = -1;
if (provisionController == null) {
provisionController = new ProvisionController(TestBluetooth.this);
}
else {
provisionController.stop();
}
provisionController.startProvision(TestBluetooth.this);
}
if (v.getId()==validateNymi.getId()){
proviNymi.setEnabled(false);
if (valiationController == null) {
valiationController = new ValidationController(TestBluetooth.this);
}
else {
valiationController.stop();
}
valiationController.startValidation(TestBluetooth.this, provisionController.getProvision());
}
if (v.getId()==disconnectNymi.getId()){
prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
prefs.edit().clear().commit();
if (nymiHandle >= 0) {
disconnectNymi.setEnabled(false);
validateNymi.setEnabled(true);
proviNymi.setEnabled(true);
Ncl.disconnect(nymiHandle);
nymiHandle = -1;
}
}
}
/**
* Initialize the NCL library
*/
protected void initializeNcl() {
if (!nclInitialized) {
if (connectNymi) {
initializeNclForNymiBand();
}
}
}
/**
* Initialize NCL library for connecting to a Nymi Band
* #return true if the library is initialized
*/
protected boolean initializeNclForNymiBand() {
if (!nclInitialized) {
NclCallback nclCallback = new MyNclCallback();
boolean result = Ncl.init(nclCallback, null, "NCLExample", NclMode.NCL_MODE_DEFAULT, this);
if (!result) { // failed to initialize NCL
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
return false;
}
nclInitialized = true;
// nclInitialized();
}
return true;
}
#Override
public void onStartProcess(ProvisionController controller) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi start provision ..",
Toast.LENGTH_LONG).show();
}
});
}
public void save(){
final String id = Base64.encodeToString(provision.id.v, Base64.DEFAULT);
final String key = Base64.encodeToString(provision.key.v, Base64.DEFAULT);
SharedPreferences pref = getSharedPreferences(Util.SharedPrefKey, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Util.provID, id);
editor.putString(Util.provKey, key);
editor.apply();
editor.commit();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(TestBluetooth.this, id + key,
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onAgreement(final ProvisionController controller) {
nymiHandle = controller.getNymiHandle();
controller.accept();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Agree on pattern: " + Arrays.toString(controller.getLedPatterns()),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onProvisioned(final ProvisionController controller) {
nymiHandle = controller.getNymiHandle();
provision = controller.getProvision();
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
proviNymi.setEnabled(false);
validateNymi.setEnabled(true);
Toast.makeText(TestBluetooth.this, "Nymi provisioned: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
save();
}
});
}
#Override
public void onFailure(ProvisionController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi provision failed!",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDisconnected(ProvisionController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
validateNymi.setEnabled(provision != null);
disconnectNymi.setEnabled(false);
Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onStartProcess(ValidationController controller) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi start validation for: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFound(ValidationController controller) {
nymiHandle = controller.getNymiHandle();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi validation found Nymi on: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onValidated(ValidationController controller) {
nymiHandle = controller.getNymiHandle();
runOnUiThread(new Runnable() {
#Override
public void run() {
validateNymi.setEnabled(false);
disconnectNymi.setEnabled(true);
// HIDE THE SPINNER AFTER LOADING FEEDS
progressbar.setVisibility(View.GONE);
Toast.makeText(TestBluetooth.this, "Nymi validated!",
Toast.LENGTH_LONG).show();
prefs.edit().putBoolean(Util.isValidated, true).commit();
//move to new activity once nymi is validated
Intent intent = new Intent(TestBluetooth.this,CustomNotificationTest.class);
startActivity(intent);
}
});
}
#Override
public void onFailure(ValidationController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi validated failed!",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDisconnected(ValidationController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
disconnectNymi.setEnabled(false);
validateNymi.setEnabled(true);
proviNymi.setEnabled(true);
Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
Toast.LENGTH_LONG).show();
}
});
}
/**
* Callback for NclEventInit
*
*/
class MyNclCallback implements NclCallback {
#Override
public void call(NclEvent event, Object userData) {
Log.d(LOG_TAG, this.toString() + ": " + event.getClass().getName());
if (event instanceof NclEventInit) {
if (!((NclEventInit) event).success) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
}
}
}
}
}
Edit: After I made the NYmiAssync as inner class, I am able to run the it async using the following :
new Thread() {
public void run() {
TestBluetooth.this.runOnUiThread(new Runnable(){
#Override
public void run() {
try {
NymiAsync task = new NymiAsync();
task.execute(1, 1, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}.start();
But, I have no idea, how to make it run for every 10 seconds.
The problem is in the asynctask:
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
TestBluetooth tb=new TestBluetooth();
tb.startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
Just make the class an inner class of TestBluetooth and then just call startValidatingNymi()
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
that is because the code below in TestBlutooth:
final Handler timedThread=new Handler();
but in doInBackground you create a instance of TestBluetooth, so you get the exception

android socket client/server disconnect

I'm writing a simple client server for android, it works super until I reran the client. Then nothing happens. The server runs continuously and the client must be connected and disconnected. Any some help would be very useful. Thank you.
Server
public class MyService extends Service {
String line = null;
String temp_comand = null;
Socket client;
public static String SERVERIP = "10.0.2.15";
public final static int DISPATCH_KEY_FROM_IME = 1011;
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.i("SERVISE", "STARTED");
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
Log.v("wlan0", Utils.getMACAddress("wlan0"));
Log.v("eth0", Utils.getMACAddress("eth0"));
Log.v("<< IP4 >>", Utils.getIPAddress(true));
Log.v("<< IP6 >>", Utils.getIPAddress(false));
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// LISTEN FOR INCOMING CLIENTS
client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
if (line.equals("next")){
simulateKey(22);
}
if (line.equals("beack")){
simulateKey(21);
}
if (line.equals("up")){
simulateKey(19);
}
if (line.equals("down")){
simulateKey(20);
}
if (line.equals("ok")){
simulateKey(23);
}
if (line.equals("power")){
simulateKey(170);
}
if (line.equals("exit")){
simulateKey(4);
}
if (line.equals("vol_m")){
simulateKey(25);
}
if (line.equals("vol_up")){
simulateKey(24);
}
if (line.equals("menu")){
simulateKey(82);
}
if (line.equals("left")){
simulateKey(88);
}
if (line.equals("right")){
simulateKey(87);
}
if (line.equals("home")){
simulateKey(3);
}
if (line.equals("close")){
simulateKey(4);
}
// Log.d("ServerActivity", line);
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
}
});
e.printStackTrace();
}
}
}
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
public void simulateKey(final int KeyCode) {
new Thread() {
#Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyCode);
} catch (Exception e) {
Log.e("Exception when sendKeyDownUpSync", e.toString());
}
}
}.start();
}
}
Client
public class ClientActivity extends Activity {
String comand = "Жду команду";
private Button right, left, up, dn, menu, pow, min, plus, ok, sw_l, sw_r, close, home;
private String serverIpAddress = "";
String serverIp;
Socket socket;
private boolean connected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.client);
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
serverIp = Formatter.formatIpAddress(dhcp.gateway);
if (!connected) {
serverIpAddress = serverIp;
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
right = (Button) findViewById(R.id.btn_right);
left = (Button) findViewById(R.id.btn_left);
up= (Button) findViewById(R.id.btn_up);
dn= (Button) findViewById(R.id.btn_dn);
menu= (Button) findViewById(R.id.btn_menu);
pow= (Button) findViewById(R.id.btn_pow);
min= (Button) findViewById(R.id.btn_min);
plus= (Button) findViewById(R.id.btn_plus);
ok= (Button) findViewById(R.id.btn_ok);
sw_l= (Button) findViewById(R.id.btn_sw_left);
sw_r= (Button) findViewById(R.id.btn_sw_rig);
close = (Button) findViewById(R.id.btn_close);
home= (Button) findViewById(R.id.btn_home);
Log.e("KeyEvent.KEYCODE_HOME", String.valueOf(KeyEvent.KEYCODE_HOME));
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "next";
}});
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "beack";
}});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "up";
}});
dn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "down";
}});
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "menu";
}});
pow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "power";
}});
min.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "vol_m";
}});
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "vol_up";
}});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "ok";
}});
sw_l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "left";
}});
sw_r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "right";
}});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "home";
}});
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
comand = "close";
}});
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, 8080);
connected = true;
while (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
if(out.checkError())
{Log.d("ClientActivity", "Error transmitting data");
throw new Exception("Error transmitting data.");
}
if (comand.equals("next")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("beack")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("up")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("down")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("ok")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("power")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("exit")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("vol_m")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("vol_up")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("menu")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("left")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("right")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("home")){
out.println(comand);
comand = "Жду";
}
if (comand.equals("close")){
out.println(comand);
comand = "Жду";
}
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
protected String wifiIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
// Convert little-endian to big-endianif needed
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
} catch (UnknownHostException ex) {
Log.e("WIFIIP", "Unable to get host address.");
ipAddressString = null;
}
return ipAddressString;
}
}
If the client does not disconnect the server stays in this loop: while ((line = in.readLine()) != null) waiting and waiting for the next line. In the mean time no other client can connect.

setBackgroundResource doesn't set the image

Handler hnd = new Handler() {
#Override
public void handleMessage(Message msg) {
int id = sequence.get(msg.arg1);
if(msg.arg1 % 2 == 0) {
sq.get(id-1).setBackgroundResource(R.drawable.square_show);
} else {
sq.get(id-1).setBackgroundResource(R.drawable.square);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i < sequence.size()-1; i++) {
record_tv.setText(""+i);
Thread.sleep(200);
Message msg = hnd.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch(Throwable t) {
}
}
});
background.start();
}
[CODE UPDATED] now it goes through the first loop and stops
do you have any idea why the code in the first runOnUiThread gets executed but it doesn't do what i want?
what i want is: change the image to "square", wait 2 seconds, change the image to "square_show", wait 2 secs and repeat the loop
i've been struggling for an hour now...
You can easily set image using following code.
sq.get(id-1).setImageResource(R.drawable.square_show);
sq.get(id-1).setImageResource(R.drawable.square);
public void show(int size) {
// CICLE THROUGH EACH SQUARE
for(int i = 0; i <= size-1; i++) {
Thread thrd = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id-1).setImageResource(R.drawable.square_show);
// System.out.println("1st..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sq.get(id-1).setImageResource(R.drawable.square);
// System.out.println("2nd..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thrd.start();
}
}
This is a wrong way to achieve it. This may help you.
http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation
I would suggest you to use a handler
int drawablebkg[] ={R.drawable.ic_launcher,R.drawable.icon};
Handler m_handler;
Runnable m_handlerTask ;
ImageView iv;
iv = (ImageView)findViewById(R.id.imageView1);
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
iv.setImageResource(android.R.color.transparent);
if(i<2)
{
ivsetBackgroundResource(drawablebkg[i]);
i++;
}
else
{
i=0;
}
m_handler.postDelayed(m_handlerTask, 2000);
}
};
m_handlerTask.run();
In onPause() of your activity
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//_t.cancel();
m_handler.removeCallbacks(m_handlerTask);
}
Another way
iv= (ImageView)findViewById(R.id.imageView1);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.ic_launcher), 2000);
iv.setImageResource(android.R.color.transparent);
animation.addFrame(getResources().getDrawable(R.drawable.icon), 2000);
animation.setOneShot(false);
iv.setBackgroundDrawable(animation);
//set setBackgroundDrawable(animation) is decprecreated i guess. not sure in which api
// start the animation!
animation.start();
Another way
Define background.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="#drawable/ic_launcher" android:duration="2000" />
<item android:drawable="#drawable/icon" android:duration="2000" />
</animation-list>
I your activity onCreate();
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setBackgroundResource(R.drawable.background);
AnimationDrawable animation= (AnimationDrawable)loadingRaven.getBackground();
loadingRaven.setImageResource(android.R.color.transparent);
animation.start();
Note to stop the animation you need to call animation.stop()
Because the resource changes in the UI thread and you are sleeping your background thread. The UI thread is running normally.
Use handlers:
public class MainActivity extends Activity {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 % 2 == 0) {
b.setBackgroundResource(R.drawable.analytic_icon);
} else {
b.setBackgroundResource(R.drawable.ic_launcher);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(2000);
Message msg = handler.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch (Throwable t) {
// just end the background thread
}
}
});
background.start();
}
}
Try this,It will work:
public void show(final int size) {
Thread thrd = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= size - 1; i++) {
id = (Integer) sequence.get(i);
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square_show);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thrd.start();
}

Categories

Resources