How to validate the Nymi band Asynchronously? - java

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

Related

start method only after checking is there a needed value in sharedPref

Theres edit text field. It has to work like this:
1) if it is empty - nothing happen
2) if user put some NEW text starts method of TextWatcher with HTTP request which takes JSON object. Also the value of String will put in sharedpreference
3) if user open activity when sharedpreference already have value of previous string it has to just set text from that string and don't start method of TextWatcher with HTTP request.
So there are three conditions and progrmm has to make request only in case when value of string is not tha same as in shared pref. Now it sends request even if person just open app. I want to avoid wrong requests and make request only after new value of string.
THE MAIN QUESTION: How to launch HTTP request code ONLY in case if value in textfield is not the same as in sharedpref?
P.S. If you think my question is bad. Please tell me in notes NOT JUST MAKE -1 please. Teach new programmers
Here is the code
public class MainActivity extends AppCompatActivity {
AppCompatButton chooseLanguageButton;
AppCompatButton cleanButton;
AppCompatEditText translatedTextOutput;
AppCompatEditText translatedTextInput;
String translatedInputString;
RequestQueue requestQueue;
final String TAG = "myTag";
String language;
SharedPreferences mSettings;
SharedPreferences textReference;
SharedPreferences translateReference;
SharedPreferences longLangReference;
SharedPreferences shortLangReference;
final String SAVED_TEXT = "text";
final String SAVED_TRANSLATION = "translation";
final String LANGUAGE_LONG = "lang_long";
final String LANGUAGE_SHORT = "lang_short";
public static final String APP_PREFERENCES = "mysettings";
private ProgressBar progressBar;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
Log.v(TAG, "in afterTextChanged");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (translatedTextInput.getText().length() != 0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
requestQueue = Volley.newRequestQueue(MainActivity.this);
sendJsonRequest();
}
});
}
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 600);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (timer != null) {
timer.cancel();
}
saveText();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "in Oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
int textLength = translatedTextInput.getText().length();
translatedTextInput.setSelection(textLength);
translatedTextInput.addTextChangedListener(searchTextWatcher);
chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v(TAG, "in chooseLanguageListener");
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivity(intent);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
translatedTextInput.setText("");
translatedTextOutput.setText("");
}
});
mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
if (mSettings.contains(LANGUAGE_LONG)){
Log.v(TAG, "here");
chooseLanguageButton.setText(mSettings.getString(LANGUAGE_LONG,""));
} else {
Log.v(TAG, "THERE");
chooseLanguageButton.setText("Choose language");
}
if (mSettings.contains(SAVED_TEXT)){
Log.v(TAG, "here");
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
} else {
Log.v(TAG, "boooooom");
}
if (mSettings.contains(SAVED_TRANSLATION)){
Log.v(TAG, "here in TRANSLATION FIELD" + mSettings.getString(SAVED_TRANSLATION,""));
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
} else {
Log.v(TAG, "boooooom");
}
}
#Override
protected void onResume() {
super.onResume();
translatedTextInput.post(new Runnable() {
#Override
public void run() {
Selection.setSelection(translatedTextInput, );
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mSettings = null;
}
void saveText() {
// mSettings = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
SharedPreferences.Editor ed = mSettings.edit();
ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
ed.putString(SAVED_TRANSLATION, translatedTextOutput.getText().toString());
ed.apply();
Log.v(TAG, "Text saved==========>" + translatedTextInput.getText().toString());
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
textReference = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
translateReference = getSharedPreferences(SAVED_TRANSLATION, MODE_PRIVATE);
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
Log.v(TAG, "IN LOAD TEXT METHOD" + mSettings.getString(SAVED_TEXT,""));
Log.v(TAG, "IN LOAD TRANSLATION METHOD" + mSettings.getString(SAVED_TRANSLATION,""));
}
public void sendJsonRequest() {
Log.v(TAG, "in sendJsonObject");
Intent myIntent = getIntent();
// language = myIntent.getStringExtra("short");
shortLangReference = getSharedPreferences(LANGUAGE_SHORT, MODE_PRIVATE);
language = mSettings.getString(LANGUAGE_SHORT,"");
Log.v(getClass().getSimpleName(), "language short = " + language);
translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v(TAG, "Inside OnResponse" + response.toString());
JSONArray results = null;
try {
results = response.getJSONObject("data").getJSONArray("translations");
for (int i=0,j=results.length();i<j;i++) {
String webTitle = results.getJSONObject(i).getString("translatedText");
translatedTextOutput.setText(webTitle);
}
} catch (JSONException e) {
Log.e(TAG, "Error :" + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Log.e(TAG, "NetworkError");
} else if (error instanceof ServerError) {
Log.e(TAG, "The server could not be found. Please try again after some time!!");
} else if (error instanceof AuthFailureError) {
Log.e(TAG, "AuthFailureError");
} else if (error instanceof ParseError) {
Log.e(TAG, "Parsing error! Please try again after some time!!");
} else if (error instanceof NoConnectionError) {
Log.e(TAG, "NoConnectionError!");
} else if (error instanceof TimeoutError) {
Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
}
}
});
requestQueue.add(jsObjRequest);
}
}

Realm database is not updating

Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key
Here is below link i had tried nothing worked:
How to update the values in Table using Realm android?
Update mutiple rows in table using Realm in Android
public class Chat_history extends AppCompatActivity {
#BindView(R.id.chat_history_toolbar)
CustomToolbar chat_history_toolbar;
#BindView(R.id.sendmessgae)
CustomEditText sendmessgae;
#BindView(R.id.chat_history_list)
ListView chat_history_list;
Chat_history_Adapter chathisadapter;
RealmResults<Chat_history_pojo> chathistorylist;
Realm chatrealm;
BroadcastReceiver chatreceiver;
public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
#Override
public void onChange(Object element) {
chathisadapter.addmessage(chathistorylist);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_history);
ButterKnife.bind(this);
Realm.init(getApplicationContext());
setSupportActionBar(chat_history_toolbar);
assert getSupportActionBar() != null;
**chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
for (Chat_history_pojo chtapojo:registrationRealm) {
chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.copyToRealm(registrationRealm);
}
chatrealm.commitTransaction();**
chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
chat_history_list.setStackFromBottom(true);
chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
chat_history_list.setAdapter(chathisadapter);
/*chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Constant.l("Realm Update Called");
RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
for(Chat_history_pojo updatepojo:updatehispojo){
updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.insertOrUpdate(updatepojo);
chathisadapter.notifyDataSetChanged();
}
}
});*/
sendmessgae.setDrawableClickListener(new DrawableClickListener() {
#Override
public void onClick(DrawablePosition target) {
switch (target) {
case RIGHT:
if (sendmessgae.getText().toString().isEmpty()) {
Constant.t(getApplicationContext(), "Please Enter Message");
} else {
sendmessage();
}
break;
default:
break;
}
}
});
if (getIntent().hasExtra("mtype")) {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
} else {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
}
chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
#Override
public void onClick(View view) {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
});
chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
startActivity(chathisintent);
}
});
chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
#Override
public void onClick(View v) {
chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
deleteresults.deleteAllFromRealm();
}
});
}
});
chatreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
chatupdatepojo.setType("text");
if (intent.getStringExtra("type").equals("image")) {
chatupdatepojo.setType("image");
} else if (intent.getStringExtra("type").equals("text")) {
chatupdatepojo.setType("text");
}
chatrealm.commitTransaction();
chatrealm.close();
}
};
IntentFilter intfil = new IntentFilter(BroadCastAction);
registerReceiver(chatreceiver, intfil);
}
#Override
protected void onDestroy() {
unregisterReceiver(chatreceiver);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
chatrealm.addChangeListener(chatupdatelisterner);
Session.pushnotification(getApplicationContext());
}
#Override
protected void onStop() {
super.onStop();
chatrealm.removeChangeListener(chatupdatelisterner);
Session.removepushnotification(getApplicationContext());
}
#OnClick(R.id.camera)
public void camera() {
TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
.setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
#Override
public void onImageSelected(Uri uri) {
try {
Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
} catch (IOException e) {
Constant.l(e.toString());
}
}
})
.setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
.create();
bottomSheetDialogFragment.show(getSupportFragmentManager());
}
private void sendimages(String sid, String rid, Bitmap sendbitmap) {
Constant.showloader(Chat_history.this);
String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
Constant.l(sendumageurl);
AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
Constant.l(String.valueOf(response));
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(response.getString("url"));
chatupdatepojo.setType("image");
chatrealm.commitTransaction();
chatrealm.close();
}
} catch (JSONException e) {
Constant.l(e.toString());
Constant.dismissloader();
}
Constant.dismissloader();
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
Constant.dismissloader();
}
});
}
#Override
public void onBackPressed() {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
private void sendmessage() {
String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
Constant.l(schatsendmesg);
AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setMessage(sendmessgae.getText().toString());
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setType("text");
chatrealm.commitTransaction();
chatrealm.close();
sendmessgae.setText("");
}
} catch (JSONException e) {
Constant.l(e.toString());
}
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
Session.pushnotification(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
Session.removepushnotification(getApplicationContext());
}
}
Try this way of updation.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//Here i am checking the condition
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);
//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();
//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);
//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();
If you need to update all, then get a RealmResults object and iterate through
RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();
NOTE:
When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.
Realm reference

SpeechRecognitionService with word recognition

The title it's not clear i think. In my project i want a service that runs in background and when the user says "hello phone" or some word/phrase my app starts to recognize the voice. Actually it "works" but not in right way... I have a service and this service detect the voice.
public class SpeechActivationService extends Service
{
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static String TAG = "Icaro";
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
private int mBindFlag;
private Messenger mServiceMessenger;
#Override
public void onCreate()
{
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
protected static class IncomingHandler extends Handler
{
private WeakReference<SpeechActivationService> mtarget;
IncomingHandler(SpeechActivationService target)
{
mtarget = new WeakReference<SpeechActivationService>(target);
}
#Override
public void handleMessage(Message msg)
{
final SpeechActivationService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= 16);//Build.VERSION_CODES.JELLY_BEAN)
{
// turn off beep sound
target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening)
{
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
Log.d(TAG, "message start listening"); //$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d(TAG, "message canceled recognizer"); //$NON-NLS-1$
break;
}
}
}
// Count down timer for Jelly Bean work around
protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
#Override
public void onFinish()
{
mIsCountDownOn = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
try
{
mServerMessenger.send(message);
message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
}
};
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
try
{
Message msg = new Message();
msg.what = MSG_RECOGNIZER_START_LISTENING;
mServerMessenger.send(msg);
}
catch (RemoteException e)
{
}
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
// speech input will be processed, so there is no need for count down anymore
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
#Override
public void onBufferReceived(byte[] buffer)
{
String sTest = "";
}
#Override
public void onEndOfSpeech()
{
Log.d("TESTING: SPEECH SERVICE", "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mIsListening = false;
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
if (Build.VERSION.SDK_INT >= 16);//Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("TESTING: SPEECH SERVICE", "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Log.d(TAG, (String) data.get(0));
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
Log.d(TAG, "onResults"); //$NON-NLS-1$
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
And i start service in my MainActivity just to try:
Intent i = new Intent(context, SpeechActivationService.class);
startService(i);
It detect the voice input...and TOO MUCH!!! Every time it detects something it's a "bipbip". Too many bips!! It's frustrating.. I only want that it starts when i say "hello phone" or "start" or a specific word!! I try to look at this https://github.com/gast-lib/gast-lib/blob/master/library/src/root/gast/speech/activation/WordActivator.java but really i don't know how use this library. I try see this question onCreate of android service not called but i not understand exactly what i have to do.. Anyway, i already import the gast library.. I only need to know how use it. Anyone can help me step by step? Thanks
Use setStreamSolo(AudioManager.STREAM_VOICE_CALL, true) instead of setStreamMute. Remember to add setStreamSolo(AudioManager.STREAM_VOICE_CALL, false) in case MSG_RECOGNIZER_CANCEL

show indeterminate progress indicator

I am trying to show a progress indicator when doing network requests with volley. I am getting the error "Only the original thread that create a view hierarchy can touch its views". I cannot figure out how to get my hideProgressDialog() onto the same thread as showProgressDialog(). Here's my code...
showProgressDialog("Logging you in");
String url = ApplicationController.getInstance().getBaseURL() + "Customer/LoginCustomer";
JsonRequest<String> jr = new JsonRequest<String>(Method.POST, url, jo.toString(), this.createSuccessListener(),
this.createErrorListener()) {
#Override
protected Response<String> parseNetworkResponse(NetworkResponse nr) {
hideProgressDialog();
try {
String str = new String(nr.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
ApplicationController.getInstance().addToRequestQueue(jr);
}
/** Create Volley Listeners **/
private Response.ErrorListener createErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
};
}
private Response.Listener<String> createSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideProgressDialog();}
};
}
Solution
Thanks to tautvydas. I ended up putting these methods in my base class.
protected void showProgressDialog(String message) {
if(mHandler == null){
mHandler = new Handler();
}
if (mDialog == null || !mDialog.isShowing()) {
mDialog = new ProgressDialog(getActivity());
mDialog.setMessage(message);
mDialog.setCancelable(false);
mDialog.setIndeterminate(true);
mDialog.show();
}
}
protected void hideProgressDialog() {
if (mDialog != null) {
mHandler.post(new Runnable() {
#Override
// this will run on the main thread.
public void run() {
mDialog.hide();
}
});
}
}
Create a Handler and pass a Runnable to it to run on the main thread.
1) Declare Handler in the constructor on onCreate() method by Handler handler = new Handler(). 2) Then in your parseNetworkResponse() method call
handler.post(new Runnable() {
#Override
// this will run on the main thread.
public void run() {
hideProgressDialog();
}
});

Link java class to xml file in android

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

Categories

Resources