Singleton with Android - java

I'm having a bit of trouble using the singleton pattern correctly in my android studio project. I created a textView in my mainActivity class in which I want to set the text of that textView the string value of the variable "a" in the GrouseSingleton class. However, the textView always displays as "hello" (the way it was initialized) and not the actual string it should be (it should be "mainly cloudy skies", parsed from the website). I'm assuming that I'm not set the variable "a" correctly in the singleton class. Any help would be appreciated, thanks!
SINGLETON CLASS CODE:
public class GrouseSingleton extends AppCompatActivity {
private static GrouseSingleton instance = null;
public Document grouseWeather;
public String a = "hello";
private GrouseSingleton() throws IOException {
startThread();
}
public static GrouseSingleton getInstance() throws IOException {
if (instance == null) {
instance = new GrouseSingleton();
}
return instance;
}
public void startThread() throws IOException {
new Thread() {
public void run() {
try {
grouseWeather = Jsoup.connect("https://www.grousemountain.com/current_conditions#weather").get();
runOnUiThread( new Runnable()
{
public void run()
{
a = grouseWeather.select("h3.metric").first().text();
setA(a);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
public void setA(String a) {
this.a = a;
}
}
MAIN ACITVITY CODE:
try {
grouseSingleton = GrouseSingleton.getInstance();
} catch (IOException e) {
e.printStackTrace();
}
TextView tv45 = findViewById(R.id.textView45);
tv45.setText(grouseSingleton.a);

Your singleton is fine. The issue is that you create the instance of class GrouseSingleton and then right after that you get the value of a which is the default value "hello" . So you need to use an interface like below to inform your activity when the value of a is fetched from server:
public interface ResultListener {
void onResultFetched(int textViewId, String txt);
}
In your Activity:
try {
grouseSingleton = GrouseSingleton.getInstance(new ResultListener () {
#Override
public void onResultFetched(int textViewId, String txt) {
TextView tv45 = findViewById(id);
tv45.setText(txt);
});
grouseSingleton.startThread();
} catch (IOException e) {
e.printStackTrace();
}
set the listener in your GrouseSingleton class:
private static ResultListener listener;
public static GrouseSingleton getInstance(ResultListener listener) throws IOException {
if (instance == null) {
instance = new GrouseSingleton();
GrouseSingleton.listener = listener;
}
return instance;
}
public void startThread() throws IOException {
new Thread() {
public void run() {
try {
grouseWeather = Jsoup.connect("https://www.grousemountain.com/current_conditions#weather").get();
runOnUiThread( new Runnable()
{
public void run()
{
a = grouseWeather.select("h3.metric").first().text();
listener.onResultFetched(txtViewId, a);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}

All code is fine. But the problem is before load data textview set default value hello. Afterload data it's cannot update the value. To simply achieve this just sent your textView as a parameter when calling your singleton. like:
SingletonClass:
public class GrouseSingleton extends AppCompatActivity {
private static GrouseSingleton instance = null;
public Document grouseWeather;
public String a = "hello";
TextView textView;
private GrouseSingleton(TextView textView) throws IOException {
this.textView = textView;
startThread();
}
public static GrouseSingleton getInstance(TextView textView) throws IOException {
if (instance == null) {
instance = new GrouseSingleton(textView);
}
return instance;
}
public void startThread() throws IOException {
new Thread() {
public void run() {
try {
grouseWeather = Jsoup.connect("https://www.grousemountain.com/current_conditions#weather").get();
runOnUiThread( new Runnable()
{
public void run()
{
a = grouseWeather.select("h3.metric").first().text();
textView.setText(a);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
And from MAinActivity:
TextView tv45 = findViewById(R.id.textView45);
try {
grouseSingleton = GrouseSingleton.getInstance(tv45);
} catch (IOException e) {
e.printStackTrace();
}
tv45.setText(grouseSingleton.a);

Related

After calling the notify method the thread is still waiting

I have several classes:
WorkerQueue - queue.
WorkerRunnable - runnable which contain worker thread method with loop and its stop flag.
SomeClass - just class for initalize and management thread stuff.
I need to stop thread in destroy method. For it I create endTask method but it doesn't work thread still waiting.
If I replace called endTask method to mWorkerQueue.add(...), it's working fine and thread stop waiting.
class WorkerQueue {
private Queue<BasePrintTask> mTaskQueue = new ArrayDeque<>();
private Object obj = new Object();
public BasePrintTask get() {
while (mTaskQueue.isEmpty())
{
try {
synchronized (obj) {
obj.wait();
}
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return mTaskQueue.remove();
}
public void add(BasePrintTask task) {
mTaskQueue.add(task);
synchronized (obj) {
obj.notify();
}
}
public void endTask() {
synchronized (obj) {
obj.notify();
}
}
}
public class WorkerRunnable implements Runnable
{
private boolean mFlag = false;
private WorkerQueue mWorkerQueue = null;
public WorkerRunnable(WorkerQueue workerQueue)
{
this.mPrinterManager = printerManager;
this.mWorkerQueue = workerQueue;
}
public void endThread() { mFlag = false; }
public void startThread() { mFlag = true; }
#Override
public void run() {
while(mFlag)
{
try
{
BasePrintTask task = mWorkerQueue.get();
}
catch (NoSuchElementException el)
{
}
}
}
}
public class SomeClass
{
private final Context mContext;
private WorkerQueue mWorkerQueue = new WorkerQueue();
private Thread mWorkerThread = null;
private WorkerRunnable mWorkerRunnable = null;
public SomeClass(final Context context)
{
this.mContext = context;
}
public void init()
{
mWorkerRunnable = new WorkerRunnable(mWorkerQueue);
}
public int prepare() {
mWorkerRunnable.startThread();
mWorkerThread = new Thread(mWorkerRunnable);
mWorkerThread.start();
return 0;
}
public int destroy() {
mWorkerRunnable.endThread();
mWorkerQueue.endTask();
try {
if(mWorkerThread.isAlive()) {
mWorkerThread.join();
}
}
catch (InterruptedException e) {
}
return 0;
}

How to convert UTF-8 to String in Java

I am stuck here because after making the convertion from byte to String I works with append method but if I want to use setText instead of append, I get no text shown on my phone. And I don't want to write text next to the last one.
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0 , "UTF-8");
tvAppend(mostrarEntradaAnalogica, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
public void tvAppend(TextView tv, String text) {
final TextView ftv = tv;
final String ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}

Android ChangeOverTime method freezing at runtime (but not consistently)

So I am running into a problem with a function I made to slowly change the value of a monitored variable over time that is causing all the java logic to lock up. It doesn't seem to be producing an error or make the application crash so it must be getting stuck in the while loop or something but the logging isn't firing while it is locked so I am just very confused. If anyone can help me figure out how to diagnose what is causing the freezing that would be very much appreciated
EDIT: Turns out the problem was updating the UI from another thread, I manged to get it to crash and got the error and used a CountDownTimer instead of the background thread and now it is working fine. For those curious checkout my GitHub for this project.
Function in question:
public static void changeOverTime(final MonitoredVariable<Integer> tVar, final int tTo, final long tTime, final long tUpdateFreq) {
if (tTime < tUpdateFreq) { Log.e(TAG, "Time must be greater then update freq."); }
if (tVar == null) { Log.e(TAG, "Container cannot be null."); }
else {
final Thread tBackgroundThread = new Thread(new Runnable() {
#Override
public void run() {
float tSteps = tTime / tUpdateFreq; // 2000/100 = 20
float tInterval = (tTo - tVar.get()) / tSteps; // 67-175 = -108/20 = -5.4
float tVal = tVar.get(); //175
while (Math.round(tVal) != tTo) { //67(After 20 Times) != 67 -> FALSE
Debug.Log(TAG, "EQ: " + Math.round(tVal) + "?=" + tTo);
tVal += tInterval; // -5.4 * 20(Times) = -108+175 = 67
tryToSleep(tUpdateFreq); // 100ms * 20(Times) = 2000ms total
tVar.set(Math.round(tVal));
}
}
});
tBackgroundThread.start();
}
}
Supporting Function:
private static void tryToSleep(long tTime) {
try { sleep(tTime); }
catch (InterruptedException e) { e.printStackTrace(); }
}
Monitored Variable Class:
public class MonitoredVariable<Prototype> {
protected Prototype mData;
protected ChangeListener mListener;
public MonitoredVariable(Prototype tData) {
this(tData, null);
}
public MonitoredVariable(Prototype tData, ChangeListener tListener) {
if (tListener != null) setListener(tListener);
mData = tData;
}
public Prototype get() {
return mData;
}
public void set(Prototype tData) {
if (mData != tData) {
mData = tData;
notifyChange();
}
}
public void setListener(ChangeListener tListener) {
mListener = tListener;
}
public ChangeListener getListener() {
return mListener;
}
public void notifyChange() {
if (mListener != null) mListener.onChange();
}
public interface ChangeListener {
void onChange();
}
}
Usage:
public static void init() {
MonitoredVariable.ChangeListener tUpdateBackground = new MonitoredVariable.ChangeListener() {
#Override
public void onChange() { updateBackgroud();
}
};
mTop = new MonitoredVariable[]{
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground)
};
mBottom = new MonitoredVariable[]{
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground),
new MonitoredVariable<>(0, tUpdateBackground)
};
mAnimationLoop = new Handler();
mAnimation = new Runnable() {
#Override
public void run() {
Debug.Log(TAG, "RUNNING ANIMATION");
final Random RNG = new Random();
for (MonitoredVariable<Integer>[] tBackground: new MonitoredVariable[][] {mTop, mBottom}) {
for (MonitoredVariable<Integer> tColor : tBackground) {
int tRandomColor = RNG.nextInt(255);
//tColor.set(tRandomColor);
Shift.changeOverTime(tColor, tRandomColor, 2000, 100);
}
}
if(mAnimate.get()) {
mAnimationLoop.postDelayed(mAnimation, 10000);
}
}
};
mAnimate = new MonitoredVariable<>(false, new MonitoredVariable.ChangeListener() {
#Override
public void onChange() {
if (mAnimate.get()) mAnimationLoop.postDelayed(mAnimation, 0);
else mAnimationLoop.removeCallbacks(mAnimation);
}
});
}
public static void setBackground(final Activity tActivity){
final View tActivityBackground = tActivity.findViewById(R.id.background);
mListener = new ChangeListener() {
#Override
public void onChange() { tActivityBackground.setBackground(mBackground); }
};
notifyChange();
}
private static void updateBackgroud() {
int tTop = Color.argb(255, mTop[0].get(), mTop[1].get(), mTop[2].get());
int tBottom = Color.argb(255, mBottom[0].get(), mBottom[1].get(), mBottom[2].get());
int[] colors = {tTop, tBottom};
mBackground = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
mBackground.setCornerRadius(0f);
notifyChange();
}
public static void animateBackground(boolean tAnimate) {
mAnimate.set(tAnimate);
}
public static void notifyChange() {
if (mListener != null) mListener.onChange();
}
public interface ChangeListener {
void onChange();
}

android, oauth 1.0a, scribe = exception

I am getting these error when retrieving ucoz.api.ru (oauth 1.0a) token using scribe library oauth (4.2.0) on android :
Caused by: com.github.scribejava.core.exceptions.OAuthException:
Response body is incorrect. Can't extract token and secret from this:
'{"oauth_token":"NAzoveaGm5XIlBvLcLRxUvamEK8P2.BAlQZ.M.aV","oauth_token_secret":"SJsqC0IfFAKS3BkdauQ3bY4ha01PDHTlFIy7GSro","oauth_callback_confirmed":"true"}'
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:42)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:32)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:19)
at
com.github.scribejava.core.oauth.OAuth10aService.getRequestToken(OAuth10aService.java:49)
at
com.vasyaevstropov.oauth10test.MainActivity.request(MainActivity.java:96)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:61)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:53)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841)
My source code:
final OAuth10aService service = new ServiceBuilder(CONSUMER_KEY)
.apiSecret(CONSUMER_SECRET)
.debug()
.build(UcozApi.instance());
final Scanner in = new Scanner(System.in);
// Obtain the Request Token
final OAuth1RequestToken requestToken = service.getRequestToken(); // <<--- Error is in this place
System.out.println(service.getAuthorizationUrl(requestToken));
final String oauthVerifier = in.nextLine();
// Trade the Request Token and Verfier for the Access Token
OAuth1AccessToken accessToken = null;
try {
accessToken = service.getAccessToken(requestToken, oauthVerifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Ucozapi module:
public class UcozApi extends com.github.scribejava.core.builder.api.DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken=%s";
private static final String REQUEST_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetrequesttoken";
private static final String ACCESS_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetaccesstoken";
protected UcozApi() {
}
private static final UcozApi INSTANCE = new UcozApi();
public static UcozApi instance() {
return INSTANCE;
}
#Override
public String getAccessTokenEndpoint() {
return ACCESS_TOKEN_RESOURCE;
}
#Override
public String getRequestTokenEndpoint() {
return REQUEST_TOKEN_RESOURCE;
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
}
Can somebody help me?
I answer my question. This code will work good with scribe-java library:
MainActivity:
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.vasyaevstropov.oauthtest.ucoz.UcozApi;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
Button button;
public WebView webView;
String verifier;
OAuth1RequestToken requestToken = null;
OAuth10aService service;
OAuth1AccessToken accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
service = new ServiceBuilder("murka1")
.apiSecret("DqUQJzeCPmwD9CRqbHo6sGBzKCb5U4")
.debug()
.build(UcozApi.instance());
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
String PROTECTED_RESOURCE_URL = "http://artmurka.com/uapi/shop/request?page=categories";
try {
requestToken = service.getRequestToken();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
String url = service.getAuthorizationUrl(requestToken);
return url;
}
#Override
protected void onPostExecute(String result) {
loadURL(result);
}
}.execute();
}
});
}
public void loadURL(final String url) {
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (url.contains("oauth_verifier")) {
webView.setVisibility(webView.GONE);
Log.d("Log.d", url);
verifier = uri.getQueryParameter("oauth_verifier");
Toast.makeText(getApplicationContext(), verifier, Toast.LENGTH_SHORT).show();
getAccessToken();
}
return false;
}
});
webView.loadUrl(url);
}
private void getAccessToken() {
new AsyncTask<Void, Void, OAuth1AccessToken>() {
protected OAuth1AccessToken doInBackground(Void... params) {
try {
accessToken = service.getAccessToken(requestToken, verifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return accessToken;
}
#Override
protected void onPostExecute(OAuth1AccessToken result) {
Toast.makeText(getApplicationContext(), "Token = " + result.getToken() + "Secret = " + result.getTokenSecret(), Toast.LENGTH_LONG).show();
}
}.execute();
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
UcozApi
public class UcozApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken?oauth_token=%s";
protected UcozApi() {
}
private static class InstanceHolder {
private static final UcozApi INSTANCE = new UcozApi();
}
public static UcozApi instance() {
return InstanceHolder.INSTANCE; }
#Override
public String getAccessTokenEndpoint(){
return "http://uapi.ucoz.com/accounts/oauthgetaccesstoken"; }
#Override
public String getRequestTokenEndpoint() {
return "http://uapi.ucoz.com/accounts/oauthgetrequesttoken"; }
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken()); }
#Override
public TokenExtractor<OAuth1AccessToken> getAccessTokenExtractor() {
return OAuth1AccessUcozTokenExtractor.instance();
}
#Override
public TokenExtractor<OAuth1RequestToken> getRequestTokenExtractor() {
return OAuth1RequestUcozTokenExtractor.instance();
}
}
OAuth1RequestUcozTokenExtractor
import com.github.scribejava.core.model.OAuth1RequestToken;
public class OAuth1RequestUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1RequestToken> {
protected OAuth1RequestUcozTokenExtractor() {
}
#Override
protected OAuth1RequestToken createToken(String token, String secret, String response) {
return new OAuth1RequestToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1RequestUcozTokenExtractor INSTANCE = new OAuth1RequestUcozTokenExtractor();
}
public static OAuth1RequestUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
OAuth1AccessUcozTokenExtractor
public class OAuth1AccessUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1AccessToken> {
protected OAuth1AccessUcozTokenExtractor() {
}
#Override
protected OAuth1AccessToken createToken(String token, String secret, String response) {
return new OAuth1AccessToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1AccessUcozTokenExtractor INSTANCE = new OAuth1AccessUcozTokenExtractor();
}
public static OAuth1AccessUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
AbstractOauth1UcozTokenExtractor
public abstract class AbstractOauth1UcozTokenExtractor<T extends OAuth1Token> implements TokenExtractor<T> {
private Pattern OAUTH_TOKEN_PATTERN = Pattern.compile("\"oauth_token\"\\s*:\\s*\"(\\S*?)\"");
private Pattern OAUTH_TOKEN_SECRET_PATTERN = Pattern.compile("\"oauth_token_secret\"\\s*:\\s*\"(\\S*?)\"");
#Override
public T extract(Response response) throws IOException {
final String body = response.getBody();
Preconditions.checkEmptyString(body,
"Response body is incorrect. " + "Can't extract a token from an empty string");
final String token = extract(body, OAUTH_TOKEN_PATTERN);
final String secret = extract(body, OAUTH_TOKEN_SECRET_PATTERN);
return createToken(token, secret, body);
}
private String extract(String response, Pattern p) {
final Matcher matcher = p.matcher(response);
if (matcher.find() && matcher.groupCount() >= 1) {
return OAuthEncoder.decode(matcher.group(1));
} else {
throw new OAuthException("Response body is incorrect. Can't extract token and secret from this: '"
+ response + "'", null);
}
}
protected abstract T createToken(String token, String secret, String response);
}

java.net.scoket exception address not supported by protocol

the android code
public class androidconn extends Activity {
private rabbitmqclient mConsumer;
private TextView mOutput;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conn);
//The output TextView we'll use to display messages
mOutput = (TextView) findViewById(R.id.moutput);
//Create the consumer
mConsumer = new rabbitmqclient("10.0.2.2:5672",
"logs",
"fanout");
//Connect to broker
mConsumer.connectToRabbitMQ();
//register for messages
mConsumer.setOnReceiveMessageHandler(new OnReceiveMessageHandler(){
public void onReceiveMessage(byte[] message) {
String text = "";
try {
text = new String(message, "UTF");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mOutput.append("\n"+text);
}
});
}
#Override
protected void onResume() {
super.onPause();
mConsumer.connectToRabbitMQ();
}
#Override
protected void onPause() {
super.onPause();
mConsumer.dispose();
}
}
rabbitmq code
public abstract class rabbitmq {
public String mServer;
public String mExchange;
protected com.rabbitmq.client.Channel mModel = null;
protected Connection mConnection;
protected boolean Running ;
protected String MyExchangeType ;
/**
*
* #param server The server address
* #param exchange The named exchange
* #param exchangeType The exchange type name
* #return
*/
public rabbitmq(String server, String exchange, String exchangeType)
{
mServer = server;
mExchange = exchange;
MyExchangeType = exchangeType;
}
public void Dispose() throws SQLException
{
Running = false;
try {
if (mConnection!=null)
mConnection.close();
if (mModel != null)
mModel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/** * Connect to the broker and create the exchange
* #return success
*/
public boolean connectToRabbitMQ()
{
if(mModel!= null && mModel.isOpen() )//already declared
return true;
try
{
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost(mServer);
connectionFactory.setPort(5672);
mConnection = (Connection) connectionFactory.newConnection();
mModel = ((com.rabbitmq.client.Connection) mConnection).createChannel();
mModel.exchangeDeclare(mExchange, MyExchangeType, true);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
}
rabbitmqclient code
public class rabbitmqclient extends rabbitmq{
public rabbitmqclient(
String server,String exchange,String exchangeType) {
super(server,exchange,exchangeType);
}
//The Queue name for this consumer
private String mQueue;
private QueueingConsumer MySubscription;
//last message to post back
private byte[] mLastMessage;
// An interface to be implemented by an object that is interested in messages(listener)
public interface OnReceiveMessageHandler{
public void onReceiveMessage(byte[] message);
};
//A reference to the listener, we can only have one at a time(for now)
private OnReceiveMessageHandler mOnReceiveMessageHandler;
/**
*
* Set the callback for received messages
* #param handler The callback
*/ public void setOnReceiveMessageHandler(OnReceiveMessageHandler handler)
{
mOnReceiveMessageHandler = handler;
};
private Handler mMessageHandler = new Handler();
private Handler mConsumeHandler = new Handler();
// Create runnable for posting back to main thread
final Runnable mReturnMessage = new Runnable() {
public void run() {
mOnReceiveMessageHandler.onReceiveMessage(mLastMessage);
}
};
final Runnable mConsumeRunner = new Runnable() {
public void run() {
Consume();
}
};
/**
* Create Exchange and then start consuming. A binding needs to be added before any messages will be delivered
*/
#Override
public boolean connectToRabbitMQ()
{
if(super.connectToRabbitMQ())
{
try {
mQueue = mModel.queueDeclare().getQueue();
MySubscription = new QueueingConsumer(mModel);
mModel.basicConsume(mQueue, false, MySubscription);
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (MyExchangeType == "fanout")
AddBinding("");//fanout has default binding
Running = true;
mConsumeHandler.post(mConsumeRunner);
return true;
}
return false;
}
/**
* Add a binding between this consumers Queue and the Exchange with routingKey
* #param routingKey the binding key eg GOOG
*/
public void AddBinding(String routingKey)
{
try {
mModel.queueBind(mQueue, mExchange, routingKey);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Remove binding between this consumers Queue and the Exchange with routingKey
* #param routingKey the binding key eg GOOG
*/
public void RemoveBinding(String routingKey)
{
try {
mModel.queueUnbind(mQueue, mExchange, routingKey);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Consume()
{
Thread thread = new Thread()
{
#Override
public void run() {
while(Running){
QueueingConsumer.Delivery delivery;
try {
delivery = MySubscription.nextDelivery();
mLastMessage = delivery.getBody();
mMessageHandler.post(mReturnMessage);
try {
mModel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
} catch (IOException e) {
e.printStackTrace();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
};
thread.start();
}
public void dispose(){
Running = false;
}
}
and the logcat is
07-24 22:57:45.412: D/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
kindly tell me the eror
make sure the rabbitmq server is not blocking the connection and the connectivity information supplied is correct. You can add this to the android manifest file as well:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Catch SocketException and ensure that you can connect to the destination ip address/port number.

Categories

Resources