no communication between pub/sub code in android using zeromq - android

I tried to implement a simple publisher and subscriber in android using zeromq. When i try to debug it loops in subscriber recv. I dont know where i am going wrong. I think it is not able to get any data from the publisher.
Below is the code :subscriber
package com.example.jeromqps;
import java.util.*;
import org.jeromq.ZMQ;
import android.os.AsyncTask;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
public class client implements Runnable {
Messenger messenger;
public client()
{
System.out.println("client started");
}
#Override
public void run()
{
ZMQ.Context context=ZMQ.context(1);
System.out.println("collecting data from server");
ZMQ.Socket subscriber=context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:4444");
String code="10001";
subscriber.subscribe(code.getBytes());
int totalvalue=0;
//store the data in a data structure
for(int i=0;i<10;i++)
{
byte[] msg = subscriber.recv(0);
String string=new String(subscriber.recv(0));
StringTokenizer sscanf=new StringTokenizer(string," ");
int value=Integer.valueOf(sscanf.nextToken());
String string= new String(msg);
System.out.println();
totalvalue+=value;
}
int avg=totalvalue;
Message msg1=Message.obtain();
msg1.obj=string;
try {
messenger.send(msg1);
System.out.println("sent to main");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
subscriber.close();
context.term();
}
}
The publisher code is below
package com.example.jeromqps;
import java.util.*;
import org.jeromq.*;
public class server implements Runnable{
public server()
{
System.out.println("server started");
}
#Override
public void run()
{
ZMQ.Context context=ZMQ.context(1);
ZMQ.Socket publisher=context.socket(ZMQ.PUB);
publisher.bind("tcp://*:4444");
Random srandom=new Random(System.currentTimeMillis());
System.out.println("in server");
while(!Thread.currentThread().isInterrupted())
{ //System.out.println("in while")
int zipcode =1000 +srandom.nextInt(10000);
int temperature = srandom.nextInt(215) - 80 + 1;
String update = String.format("%05d %d", zipcode, temperature);
String update="publisher";
publisher.send(update.getBytes(),0);
}
publisher.close();
context.term();
}
}
Main is below:
package com.example.jeromqps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Handler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends Activity implements Handler.Callback {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new server()).start();
new Thread(new client()).start();
}
#Override
public boolean handleMessage(Message arg0)
{
String str = new String((byte[]) arg0.obj);
System.out.println("****");
System.out.println(str);
//new AlertDialog.Builder(this).setMessage(str).show();
System.out.println("****");
textView.append(str+ "\n");
return false;
}
}
In program loops at byte[] msg = subscriber.recv(0); in the subscribers class. Where am i going wrong?Am i missing something?

First of all, you've got some errors in the code:
In the publisher, update is defined twice
String update = String.format("%05d %d", zipcode, temperature);
String update= "publisher";
You have a similar problem in the subscriber code, string is defined twice...
String string = new String(subscriber.recv(0));
String string = new String(msg);
In the subscriber, you're receiving messages twice in the same iteration..
byte[] msg = subscriber.recv(0);
String string = new String(subscriber.recv(0));
...you only need this in the loop to receive...
String string = new String(subscriber.recv(0));
Try fixing those problems and see how far you get...

This isn't a solution to the question posted here, but reading this question I noticed that 0 was specified as the second parameter in the send(...) method, which subsequently matches the parameter set in the recv(...) method.
I have a simple pub/sub system set up and couldn't figure out why messages weren't being sent. I was using recv(0) but was specifying some random flag in the send(...) method. Changing the value to 0 fixed my issues.
Figured I'd post this here as it was from reading through the code in the question that I happened to have that thought. So maybe this will help someone else in the future.

Related

OpenSubtitles api android class

I'm having trouble getting data from OpenSubtitles api. I have looked at many examples for java and python. Below is the class I'm trying to use to authenticate with OpenSubtitles api. After that I want to make request that will return a list of items I can pass to my recyclerview.
package com.shivito.subreader;
import android.app.DownloadManager;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class OpensubsRequest {
static String username;
static String password;
static String language;
static String useragent;
#RequiresApi(api = Build.VERSION_CODES.O)
public static void makerequest(){
Thread thread = new Thread() {
#Override
public void run() {
try {
Log.d("here","nope");
URL Opensubs = new URL("https://api.opensubtitles.org/xml-rpc");
URL url = new URL("https", "api.opensubtitles.org", 443, "/xml-rpc");
URLConnection uc = Opensubs.openConnection();
Log.d("working",uc.toString());
uc.addRequestProperty("username",username);
uc.addRequestProperty("password",password);
uc.addRequestProperty("language",language);
uc.addRequestProperty("useragent",useragent);
uc.connect();
Log.d("anythingnow", String.valueOf(uc.getAllowUserInteraction()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
Okay so in the above class I am trying to send my login information to the api then I try to check if it was successful by reading the response from(uc.getAllowUserInteraction()). Up to this point it always says false. Of course I'm likely not doing this right and I hope someone can point me in the right direction. Thank you!!

Connect android studio to azure sql database using Java

package com.example.workdb;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.Bundle;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.sourceforge.jtds.jdbc.*;
public class MainActivity extends AppCompatActivity {
public Button run;
public TextView message;
public TextView txtvw;
public Connection con;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
run= (Button) findViewById(R.id.button);
run.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
CheckLogin checkLogin= new CheckLogin();
checkLogin.execute("");
Log.d("CREATION","ON CREATE WORKS");
// Log.d("txtvw", connection);
//System.out.println("Yes");
// txtvw.setText("hello");
}
});
} public class CheckLogin extends AsyncTask<String,String,String>
{
String z="";
Boolean IsSuccess= false;
String name1="";
// Log.d("txtvw","step 1 done");
protected void onPostExecute(String r){
if (IsSuccess){
message=(TextView)findViewById(R.id.textView);
message.setText(name1);
Log.d("TAG", "STEP 1 DONE");
}
}
#Override
protected String doInBackground(String... strings) {
try
{
Connection con = connectionClass();
if(con==null){
z="Check interent";
//Log.d("txtvw", z);
}
else
{
String query= "select * from Value";
Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery(query);
if (rs.next())
{
name1=rs.getString("KneeAngle");
Log.d("MYTAG", "name 1 works");
z="Query success";
IsSuccess=true;
con.close();
}
else{
z="Invalid query";
IsSuccess=false;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return z;
}
}
public Connection connectionClass(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL ;
try{
Class.forName("net.sourceforge.jtds.jdbs.Driver");
ConnectionURL="jdbc:jtds:sqlserver://havvasemserv3.database.windows.net:1433;DatbaseName=Newfin;user=;password=;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30";
connection= DriverManager.getConnection(ConnectionURL);
} catch(ClassNotFoundException e){
Log.e("Error here 2 ",e.getMessage());
}
catch (Exception e) {
Log.e("error here 3:",e.getMessage());
}
//Log.d("txtvw", connection);
return connection;
}
}
I am trying to connect azure sql database to android studio. I have added all the permissions in the manifest file and I have also added a jtds module 1.3.1 in the project and implemented it in the gradle module app. My code exits with 0 errors but data is not displayed on the emulator. Expected output is the first value from my database which is "8".
Thanks.,
Add this at the end of you current connection url after timeout=30
;ssl=request
Also make sure in your firewall settings of your azure server!/database your current device ip is allowed to access as by default all access is blocked,
To allow all devices to access server go to the firewall settings and in the insert ip section add this ip range
0,0,0,0 and 255,255,255,255

While loop or for loop for json object for android not working

I am trying to add a for loop or while loop for method getuserDetailWhileLoop(); but i am having a hard time figuring out on how to do it. This code suppose to show json object to text view and text view has scroll view in it. However when i ran the code the while loop is not working and only show 1 object. I need the while loop to show multiple object. How will i be doing that? Thanks.
package com.demo.myblog.profile;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.demo.myblog.R;
import com.demo.myblog.volley.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class UserProfile extends AppCompatActivity {
private String ID,NAME,EMAIL,CREATED_DATE, ID2;
private String appURl, appURl2;
Activity mContext = this;
TextView mId,mName,mEmail,mDate, mid2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile2);
mId = findViewById(R.id.txt_Id);
mid2 = findViewById(R.id.textView5);
mName = findViewById(R.id.txt_Name);
mEmail = findViewById(R.id.txt_Email);
mDate = findViewById(R.id.txt_Data);
Intent data = getIntent();
EMAIL = data.getStringExtra("email");
appURl = "url here";
appURl2 = "url2 here";
getUserDetail();
getuserDetailWhileLoop();
}
private void getuserDetailWhileLoop()
{
if (EMAIL.isEmpty()){
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setMessage("Email cannot be empty");
alert.setCancelable(false);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
else{
StringRequest stringRequest = new StringRequest(Request.Method.GET,appURl2, new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try
{
JSONObject jo = new JSONObject( response );
for(int i =0 ;i < jo.length(); i++)
{
ID2 = jo.getString( "id" );
//NAME = jsonObject.getString("username");
//EMAIL = jsonObject.getString("user_email");
//CREATED_DATE = jsonObject.getString("created_date");
//sonObject = jsonObject.getJSONObject( "id" );
mid2.setText( ID2 );
//mName.setText(NAME);
//mEmail.setText(EMAIL);
//mDate.setText(CREATED_DATE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I like to use for loops over while loops, because with a for loop you're able to check the progress of the loop.
In this case it is best to use a for loop, just like you already did.
Can you post a example response of the StringRequest?
[EDIT]
You forgot to add the counter 'i', your for loop is fine.
JSONObject obj = jo.getJSONObject(i);
obj.getString("id");
I think this is the solution to your problem.

NullPointerException on grabbing sql data from database

I'm trying to pull all the data from a table using SELECT * from book, but I'm getting:
Attempt to invoke interface method 'java.sql.ResultSet java.sql.Statement.executeQuery(java.lang.String)' on a null object reference
I got it working when triggering the SQL statement in Eclipse. I'm trying to recreate it in Android Studio, but seems to throw this issue. Any help is appreciated.
SQL.java
package com.example.andy.loginapp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* Created by Andy on 1/4/2017.
*/
public class SQL {
private Statement st;
private Connection con;
private ResultSet rs;
public SQL(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sqltest", "root", "");
st = con.createStatement();
}
catch(Exception e){
System.out.println(e);
}
}
public void getData(){
try{
String query = "SELECT * from book";
String queryInsert = "INSERT into Book " + "VALUE(authorField.getText(), titleField.getText(), yearField.getText())";
rs = st.executeQuery(query);
while(rs.next()){
String author = rs.getString("author");
String title = rs.getString("title");
System.out.println("Author: " + author + " " + "Title" + " " + title);
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("success");
}
}
MainActivity.java
package com.example.andy.loginapp;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private Statement st;
private Connection con;
private ResultSet rs;
TextView hi;
RelativeLayout background;
Button sqlButton;
SQL data = new SQL();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqlButton = (Button) findViewById(R.id.sqlButton);
sqlButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
data.getData();
}
});
}
}
You would have to write a webservice to connect to any external databases such as MYSQL to connect android application to a database. It also involves writing a very basic PHP script.
See the following link for some examples.
https://www.b4x.com/android/forum/threads/connect-android-to-mysql-database-tutorial.8339/
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
So you're better off using SQLLite unless its absolutely necessary.

Error : method gettext() must be call from UI thread is worker

While working on a project I'm getting this error
Error : method gettext() must be call from UI thread is worker
on the following line :
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Please Help
This is my entire code for the class ChatActivity.java
package com.example.ankit.myapplication;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.ankit.myapplication.XmppService;
import com.squareup.okhttp.OkHttpClient;
import org.jivesoftware.smack.packet.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
//import services.XmppService;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Scanner in = new Scanner(System.in);
XmppService xm= new XmppService();
Log.d("pavan","in chat "+getIntent().getStringExtra("user_id"));
Log.d("pavan","in chat server "+Util.SERVER);
XmppService.setupAndConnect(ChatActivity.this, Util.SERVER, "",
getIntent().getStringExtra("user_id"), Util.XMPP_PASSWORD);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
// new SendMessage().execute();
XmppService.sendMessage(ChatActivity.this, editText_mail_id.getText().toString() + Util.SUFFIX_CHAT, Message.Type.chat, message);
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
Do not access the Android UI toolkit from outside the UI thread
Pass editText_mail_id.getText() and editText_chat_message.getText() as parameters to your async task or set it in onPreExecute to some variable
Like :
private class SendMessage extends AsyncTask<String, Void, String> {
private String mailId;
private String msgText;
#Override
protected void onPreExecute() {
super.onPreExecute();
mailId = editText_mail_id.getText().toString();
msgText = editText_chat_message.getText().toString();
}
Change url in doInBackground as :
String url = Util.send_chat_url+"?email_id="+mailId+"&message="+msgText;
you can create class for storing your parameter like i do,
Just create one class
example :
public class MyTaskParams
{
String mailId;
String message;
public MyTaskParams(String mailId, String message)
{
this.mailId = mailId;
this.message = message;
}
}
public class SendMessage extends AsyncTask<MyTaskParams, Void, String {
#Override
protected String doInBackground(MyTaskParams... params) {
String mailId = params[0].mailId;
String message = params[0].message;
String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;
}
}
so you can just call like this
MyTaskParams params = new MyTaskParams(editText_mail_id.getText().toString(),editText_chat_message.getText().toString());
SendMessage myTask = new SendMessage();
myTask.execute(params);
with this code you can call SendMessage Class from any activity, dont bind your asynctask with get text because if you do that you just can use SendMessage only in that activity
Hope this can help you.

Categories

Resources