Cannot resolve symbol - java

I try to mage Google Cloud Messaging.
I have follow class:
package de.phcom.avs;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GcmRegistrationAsyncTask extends AsyncTask<Void, Void, String> {
private static Registration regService = null;
private GoogleCloudMessaging gcm;
private Context context;
// TODO: change to your own sender ID to Google Developers Console project number, as per instructions above
private static final String SENDER_ID = "131952017954";
public GcmRegistrationAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
if (regService == null) {
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// Need setRootUrl and setGoogleClientRequestInitializer only for local testing,
// otherwise they can be skipped
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest)
throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end of optional local run code
regService = builder.build();
}
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
String regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regId;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
regService.register(regId).execute();
} catch (IOException ex) {
ex.printStackTrace();
msg = "Error: " + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Logger.getLogger("REGISTRATION").log(Level.INFO, msg);
}
}
and they say:
Cannot resolve symbol 'Registration'
Cannot resolve symbol 'AndroidHttp'
Cannot resolve symbol 'AndroidJsonFactory'
and so on.
I have downloaded Google API 19 and 21.

Just elaborating Mena's answer
You can fix this by adding the following dependency:
compile 'com.google.http-client:google-http-client-android:1.22.0'

Related

How to call second class method from one class and print output of method inside second class in java

MqConnection.java
package com.example.rabbitmq;
import android.os.StrictMode;
import android.util.Log;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
final static String QUEUE_NAME = "hello2";
final static String EXCHANGE_NAME = "logs_monitor";
final static String HOST = "localhost";
final static int PORT = 5672;
final static Connection connection;
final static Channel channel;
public class MqConnection {
public void setupConnection() {
Log.d("Debug","SetupConnection connected");
ConnectionFactory factory = new ConnectionFactory();
try {
factory.setHost(HOST);
factory.setPort(PORT);
// factory.setVirtualHost("/");
// factory.setUsername(USERNAME);
// factory.setPassword(PASSWORD);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connection = factory.newConnection();
channel = connection.createChannel();
} catch (IOException | TimeoutException e) {
throw new RuntimeException("Rabbitmq problem", e);
}
}
}
MqConsume.java
package com.example.rabbitmq;
import android.util.Log;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.DeliverCallback;
import java.io.IOException;
import static com.example.rabbitmq.setVariables.EXCHANGE_NAME;
//import static com.example.rabbitmq.setVariables.QUEUE_NAME;
import static com.example.rabbitmq.setVariables.QUEUE_NAME;
import static com.example.rabbitmq.setVariables.channel;
import com.example.rabbitmq.MainActivity.*;
public class MqConsume {
static String message = "";
public static void consumeMessages(String[] args) throws IOException {
Log.d("Debug","Before rabbitmq publish");
// channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
message = new String(delivery.getBody(), "UTF-8");
Log.d("Debug","Received");
Log.d("Debug",message);
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
MainActivity.java
package com.example.rabbitmq;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MqConnection mqConnection = new MqConnection();
mqConnection.setupConnection();
MqConsume mqConsume = new MqConsume();
final TextView received_msg;
received_msg = findViewById(R.id.received_messages);
System.out.println(received_msg);
}
}
Here i am Using Android Studio code with backend java code to connect rabbitmq. How to call message parameter in MqConsume.java from MainActivity.java
I need to print message parameter inside MainActivity class from MqConsume.java.
I have tried Calling MqConsume.java inside MainActivity.java and print message parameter inside MainActivity.java.
Is there any way to get data from one class to other class?
It looks like you want to retrieve data from an asynchronous API and use it in your activity. You can do this by declaring a custom interface and passing an instance of it to the function making the API call. Have a look here for more details about why this is needed.
public class MqConsume {
// declare a callback interface
public interface GotMessage {
void gotMessage(String msg);
}
// pass the interface in here and call it when
// the message is received
public static void consumeMessages(String[] args, GotMessage callback) throws IOException {
Log.d("Debug","Before rabbitmq publish");
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
Log.d("Debug","Received");
Log.d("Debug",message);
callback.gotMessage(message);
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
Then if you call it from MainActivity you can pass in a callback like this:
final TextView received_msg = findViewById(R.id.received_messages);
// create the interface in the activity and set
// view text inside it
MqConsume.consumeMessages(args, new MqConsume.GotMessage() {
#Override
void gotMessage(String message) {
received_msg.setText(message);
}
});

How to send XMPP Message to FCM using Spring Integration

I am totally new in XMPP and Spring Integration, and want to send message to FCM user. I created an XML configuration for Outbound Message as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-xmpp="http://www.springframework.org/schema/integration/xmpp"
...>
<context:component-scan base-package="com.avantovr.esysync_backend.webservices.restful.fcm.xmppserver" />
<int-xmpp:outbound-channel-adapter id="xmppOutboundAdapter" channel="xmppOutboundChannel" xmpp-connection="xmppConnection"/>
<int:service-activator ref="fcmSender" input-channel="xmppOutbound" />
<int:logging-channel-adapter id="xmppOutboundChannel" log-full-message="true" />
</beans>
Now I want to create a Java Class in which there is method for sending Downstrwam messagr via XMPP to FCM. Pls is there any beginner example for sending and receiving xmpp messages to FCM via Spring integration?
This may not be the best solution but its good enough for me. First time dealing with XMPP.
I dont have any XML configurations other than pom.xml dependencies.
There is a 5 seconds sleep and reconnect after a disconnect. FCM disconnects XMPP connection from time to time to load balance.
Sending ACKs back is working, receiveing ACKs and NACKs are not tested.
To send a message from java -> fcm -> phone;
#Autowired
private XmppConfig xmppConfig;
xmppConfig.getXmppConnection().sendStanza(generateStanza(messageId,json));
json above shoulde be like this, from https://firebase.google.com/docs/cloud-messaging/server
{
"to":"REGISTRATION_ID", // "to" replaces "registration_ids"
"message_id":"m-1366082849205" // new required field
"data":
{
"hello":"world",
}
"time_to_live":"600",
"delivery_receipt_requested": true/false
}
smack dependencies
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-tcp</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-java7</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-extensions</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
application.properties
fcm.sender_id=YOUR_SENDER_ID#fcm.googleapis.com
fcm.server_key=YOUR_SERVER_KEY
fcm.host=fcm-xmpp.googleapis.com
fcm.port=5235
XmppConfig.java
import com.alessoft.utils.Utils;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.stringprep.XmppStringprepException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.net.ssl.SSLSocketFactory;
#Configuration
class XmppConfig implements ConnectionListener {
#Value("${fcm.sender_id}")
private String senderId;
#Value("${fcm.server_key}")
private String server_key;
#Value("${fcm.host}")
private String host;
#Value("${fcm.port}")
private int port;
#Autowired
private XmppService xmppService;
private Logger logger = LoggerFactory.getLogger(XmppConfig.class);
private volatile boolean xmppConnected;
private XMPPTCPConnection xmppConnection;
public XMPPTCPConnection getXmppConnection() {
return xmppConnection;
}
#PostConstruct
public void postConstruct() throws Exception {
new Thread(() -> prepareXmppConnection()).start();
}
public XMPPConnection prepareXmppConnection() {
XMPPTCPConnectionConfiguration conf = null;
try {
conf = XMPPTCPConnectionConfiguration.builder()
.setHost(host)
.setPort(port)
.setSendPresence(false)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setSocketFactory(SSLSocketFactory.getDefault())
.setUsernameAndPassword(senderId, server_key)
.setXmppDomain("somedomain.com")
.build();
} catch (XmppStringprepException e) {
logger.info("prepareXmppConnection error", e);
}
xmppConnection = new XMPPTCPConnection(conf);
xmppConnection.addAsyncStanzaListener(xmppService, xmppService);
xmppConnection.addConnectionListener(this);
Roster.getInstanceFor(xmppConnection).setRosterLoadedAtLogin(false);
establishXmppConnection();
return xmppConnection;
}
private void establishXmppConnection() {
try {
xmppConnection.connect();
xmppConnection.login();
} catch (Exception e) {
logger.info("XMPP establishXmppConnection error", e);
}
}
#Override
public void connectionClosedOnError(Exception e) {
logger.info("LOST CONNECTION TO FCM XMPP ON ERROR", e);
Utils.sleep(5000);
establishXmppConnection();
}
#Override
public void connectionClosed() {
logger.info("LOST CONNECTION TO FCM XMPP");
Utils.sleep(5000);
establishXmppConnection();
}
#Override
public void connected(XMPPConnection connection) {
logger.info("CONNECTED TO FCM XMPP");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
logger.info("AUTHENTICATED TO FCM XMPP");
}
}
XmppService.java
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class XmppService implements StanzaListener, StanzaFilter {
private Logger logger = LoggerFactory.getLogger(XmppService.class);
#Autowired
private XmppConfig xmppConfig;
#Override
public void processStanza(Stanza stanzaXml) throws SmackException.NotConnectedException, InterruptedException, SmackException.NotLoggedInException {
JSONObject stanza = XML.toJSONObject(stanzaXml.toXML(null).toString());
if (!stanza.has("message")) return;
JSONObject message = stanza.getJSONObject("message");
if (message.has("type")) {
normalMessage(message);
} else {
otherMessage(message);
}
}
private void otherMessage(JSONObject message) {
JSONObject gcm = message.getJSONObject("gcm");
String contentString = gcm.getString("content");
JSONObject content = new JSONObject(contentString);
if (content.getString("message_type").equals("ack")) {
logger.info("RECEIVED ACK");
} else if (content.getString("message_type").equals("nack")) {
logger.info("RECEIVED NACK: \n" + content.toString(2));
} else {
logger.info("RECEIVED UNKNOWN: \n" + content.toString());
}
}
private void normalMessage(JSONObject message) {
JSONObject gcm = message.getJSONObject("gcm");
String contentString = gcm.getString("content");
JSONObject content = new JSONObject(contentString);
String message_id = content.getString("message_id");
String from = content.getString("from");
if (content.has("message_type")) {
logger.info("NOT FROM DEVICE:\n" + message.toString());
} else {
processMessage(content);
sendAck(message_id, from);
}
}
private void processMessage(JSONObject content) {
// your own processing
}
private void sendAck(String message_id, String regId) {
try {
JSONObject json = new JSONObject();
json.put("to", regId);
json.put("message_id", message_id);
json.put("message_type", "ack");
String messageString = String.format("<message><gcm xmlns=\"google:mobile:data\">%s</gcm></message>", json.toString());
Stanza stanza = PacketParserUtils.parseStanza(messageString);
xmppConfig.getXmppConnection().sendStanza(stanza);
} catch (Exception e) {
logger.info("fcm sending ack error", e);
}
}
private Stanza generateStanza(String messageId, JSONObject json) {
String messageString = String.format("<message id=\"%s\"><gcm xmlns=\"google:mobile:data\">%s</gcm></message>", messageId, json.toString());
try {
return PacketParserUtils.parseStanza(messageString);
} catch (Exception e) {
logger.info("generateStanza error", e);
return null;
}
}
#Override
public boolean accept(Stanza stanza) {
return true;
}
}

App crashing when I try and return http response

I have made a java class to handle HTTP post requests and it sends back the result in string form. For some reason when I send the request I can print the response to the log but when return the string of the response to update the UI in the method my app crashes. Could any one explain whats happening here? I am trying to get better at java so pointing out any other bad practices would be appreciated .
log:
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/OKHTTP3: Request body created
D/OKHTTP3: Request body created 2
D/OKHTTP3: Got Response
D/OKHTTP3: {
"failed": "Asset already exists"
}
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.john.okhttp, PID: 3166
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.IllegalStateException: closed
at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:374)
at okio.Buffer.writeAll(Buffer.java:993)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:106)
at okhttp3.ResponseBody.bytes(ResponseBody.java:128)
at okhttp3.ResponseBody.string(ResponseBody.java:154)
at com.example.john.okhttp.PostEx.doPostRequest(PostEx.java:40)
at com.example.john.okhttp.MainActivity$Requesting.doInBackground(MainActivity.java:59)
at com.example.john.okhttp.MainActivity$Requesting.doInBackground(MainActivity.java:51)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
Application terminated.
the code from both java files will be posted below:
MainActivity.java:
package com.example.john.okhttp;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class MainActivity extends AppCompatActivity {
private Button btnSendHttpRequest;
private EditText etJsonResponse;
private TextView View;
private TextView View2;
private OkHttpClient okHttpClient;
private Request request;
public final String URL = "http://www.mocky.io/v2/582ac99c280000d50953c316";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set button and text view values
btnSendHttpRequest = (Button) findViewById(R.id.btnSendRequest);
View = (TextView) findViewById(R.id.view1);
View2 = (TextView) findViewById(R.id.textView4);
etJsonResponse = (EditText) findViewById(R.id.etjson);
//response for button
btnSendHttpRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//http request
PostEx example = new PostEx();
new Requesting().execute();
}
});
}
public class Requesting extends AsyncTask<String, String, String> {
// post request stuff
#Override
protected String doInBackground(String... params) {
String id = "444454";
String userName = "john";
PostEx example = new PostEx();
String jsonstr = example.makeJsonForUser(id, userName);
if(example.doPostRequest(jsonstr)== null){
Log.d("OKHTTP3", "null pointer");
}
String response = example.doPostRequest(jsonstr);
Log.d("OKHTTP3", "sending response");
return response;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
//rewrite text view
try {
// create json ob from response
if(response == null){
Log.d("OKHTTP3", "null pointer");
}
JSONObject jsonObj = new JSONObject(response);
//get the values from the json key value pairs
String id = jsonObj.toString();
//update the text views
TextView textView = (TextView) findViewById(R.id.view1);
textView.setText(id);
} catch (Exception e) {
}
}
}
}
PostEx.java:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PostEx {
public String doPostRequest(String jsonstr) {
String url = "http://45.55.92.243/newuser";
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON,jsonstr);
Log.d("OKHTTP3","Request body created");
Request newReq = new Request.Builder()
.url(url)
.post(body)
.build();
Log.d("OKHTTP3","Request body created 2");
try {
Response response = client.newCall(newReq).execute();
Log.d("OKHTTP3","Got Response");
Log.d("OKHTTP3",response.body().string());
String Fresponse = response.body().string();
response.close();
return Fresponse;
} catch (IOException e) {
Log.d("OKHTTP3","Got Exception");
e.printStackTrace();
return null;
}
}
public String makeJsonForUser(String id, String Username){
JSONObject data = new JSONObject();
try {
data.put("id", id);
data.put("name", Username);
return data.toString();
} catch (JSONException e) {
Log.d("OKHTTP3", "JSON Exeption");
e.printStackTrace();
return null;
}
}
}
at okhttp3.ResponseBody.string(ResponseBody.java:154):
public final String string() throws IOException {
return new String(bytes(), charset().name());
}
at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:374):
#Override public long read(Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount);
if (closed) throw new IllegalStateException("closed");
if (bytesRemaining == 0) return -1;
long read = source.read(sink, Math.min(bytesRemaining, byteCount));
if (read == -1) {
endOfInput(false); // The server didn't supply the promised content length.
throw new ProtocolException("unexpected end of stream");
}
bytesRemaining -= read;
if (bytesRemaining == 0) {
endOfInput(true);
}
return read;
}
Your code works, mostly, up to this point
D/OKHTTP3: Request body created
D/OKHTTP3: Request body created 2
D/OKHTTP3: Got Response
I remember reading, you can only receive the body string once
// Log.d("OKHTTP3",response.body().string());
String Fresponse = response.body().string();
// log Fresponse here
And close the resources in a finally block after the catch
More importantly you are using Okhttp. You don't need Asynctasks! Use the enqueue method instead of execute on the client call object
client.newCall(newReq).enqueue(new Callback() {
// handle response here
});
And you're processing JSON, so Retrofit would help you implement what you're already trying to do
The problem is you can call string() once. But I don't know why

Why does this Java app fail to show JSON data on refresh?

This is a mobile app composed in Java with Codename One's CODAPPS plugin for NetBeans IDE.
The code is from a Coursera course where a Twitter-clone app was developed. In the course the coding of the app was show, but the end result -- a wall of "Roars" (Tweets) which appears when you click Refresh -- was not shown, and does not appear to work.
There are no errors, but I simply cannot get it to display any Roars (Tweets). These are downloaded as JSON data. I confirmed that the data uploads and downloads as it should; it's just not displaying.
All of the user-written code is stored in a file called StateMachine.java. I will paste this code below. The entire project is also available here on GitHub.
/**
* Your application code goes here
*/
package userclasses;
import com.codename1.analytics.AnalyticsService;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.NetworkManager;
import com.codename1.io.Preferences;
import com.codename1.io.Util;
import com.codename1.processing.Result;
import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.Layout;
import com.codename1.ui.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* #author Your name here
*/
public class StateMachine extends StateMachineBase {
String roar;
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class members there,
// the constructor might be invoked too late due to race conditions that might occur
}
/**
* this method should be used to initialize variables instead of the
* constructor/class scope to avoid race conditions
*/
protected void initVars(Resources res) {
AnalyticsService.init("UA-67803686-1", "irrelevant");
AnalyticsService.setAppsMode(true);
}
#Override
protected void onMain_ButtonAction(Component c, ActionEvent event) {
Hashtable infoToBeSent = new Hashtable();
infoToBeSent.put("roar", roar);
infoToBeSent.put("author", "seinecle");
final String infoInString = Result.fromContent(infoToBeSent).toString();
String firebase = "https://roar.firebaseIO.com/listofroars.json";
ConnectionRequest request = new ConnectionRequest() {
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(infoInString.getBytes("UTF-8"));
}
};
request.setUrl(firebase);
request.setPost(true);
request.setHttpMethod("POST");
request.setContentType("application/json");
NetworkManager.getInstance().addToQueueAndWait(request);
}
#Override
protected void onMain_TextAreaAction(Component c, ActionEvent event) {
roar = findTextArea().getText();
if (roar == null) {
roar = "we did not get a roar from you";
}
}
#Override
protected void onWall_ButtonAction(Component c, ActionEvent event) {
try {
String roars = "https://roar.firebaseIO.com/listofroars.json";
//if we want to retrieve only the latest 10 roars posted
//String roars = "https://roar.firebaseIO.com/listofroars.json" + "?" + "orderBy=\"$key\"" + "&" + "limitToLast=10";
ConnectionRequest request = new ConnectionRequest();
request.setUrl(roars);
request.setPost(false);
request.setHttpMethod("GET");
request.setContentType("application/json");
NetworkManager.getInstance().addToQueueAndWait(request);
ByteArrayInputStream allRoarsInBytes = new ByteArrayInputStream(request.getResponseData());
String responseInString = Util.readToString(allRoarsInBytes, "UTF-8");
JSONObject allRoarsInJsonFormat = new JSONObject(responseInString);
JSONArray listOfRoarIds = allRoarsInJsonFormat.names();
Form wallScreen = c.getComponentForm();
Container myContainerForAllRoars = new Container();
Layout myLayout = new BoxLayout(BoxLayout.Y_AXIS);
myContainerForAllRoars.setLayout(myLayout);
Integer counterOfRoars = 0;
while (counterOfRoars < allRoarsInJsonFormat.length()) {
String idOfOneRoar = listOfRoarIds.getString(counterOfRoars);
JSONObject oneRoarInJsonFormat = (JSONObject) allRoarsInJsonFormat.get(idOfOneRoar);
Container myRoarContainer = new Container();
String author = oneRoarInJsonFormat.getString("author");
String roarText = oneRoarInJsonFormat.getString("roar");
Label myLabelForAuthor = new Label(author);
Label myLabelForRoar = new Label(roarText);
myRoarContainer.addComponent(myLabelForAuthor);
myRoarContainer.addComponent(myLabelForRoar);
myContainerForAllRoars.addComponent(myRoarContainer);
counterOfRoars = counterOfRoars + 1;
}
wallScreen.addComponent(wallScreen.getComponentCount(), myContainerForAllRoars);
wallScreen.revalidate();
} catch (IOException ex) {
} catch (JSONException ex) {
}
}
#Override
protected void onCreateUserName() {
String userName;
userName = Preferences.get("username", "");
if (userName != null) {
showForm("Main", null);
AnalyticsService.visit("Main", "UserName");
}
}
#Override
protected void onUserName_ButtonAction(Component c, ActionEvent event) {
String userName = findTextField().getText();
if (userName == null || userName.length() == 0) {
} else {
Preferences.set("username", userName);
showForm("Main", null);
AnalyticsService.visit("Main", "UserName");
}
}
}
I tried adding wallScreen.show() and Wall.show() but it didn't fix the problem.
Just add the following code and it works well on both connections
request.setDuplicateSupported(true);

Android cannot serialize error

I am working on a project to invoke a web service using android. I use ksoap2 for that.
I created a my own data type(just to try) which contains two string variables. It is like this
public class MyType {
String fName;
String lName;
public MyType(String s1,String s2){
fName = s1;
lName = s2;
}
}
I created this data type at both ends.(web service end and android application end). I wrote a program to invoke web service and then to concatenate given strings using my data type.
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.os.AsyncTask;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
public final static String URL = "http://192.168.69.1:8080/WebApplication4/MyWebService?wsdl";
public static final String NAMESPACE = "http://mywebservice.android.com/";
public static final String SOAP_ACTION_PREFIX = "/";
private static final String METHOD = "objectMethod";
private TextView textView;
MyType mt = new MyType("Upul","Tharanga");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.test);
AsyncTaskRunner runner = new AsyncTaskRunner(mt);
runner.execute();
}
private class AsyncTaskRunner extends AsyncTask<Integer, String, String> {
private String resp;
MyType a;
public AsyncTaskRunner(MyType a){
this.a = a;
}
#Override
protected String doInBackground(Integer... params) {
publishProgress("Loading contents..."); // Calls onProgressUpdate()
try {
// SoapEnvelop.VER11 is SOAP Version 1.1 constant
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject request = new SoapObject(NAMESPACE, METHOD);
PropertyInfo pi1=new PropertyInfo();
pi1.setType(String.class);
pi1.setName("parameter");
pi1.setValue(a);
request.addProperty(pi1);
envelope.bodyOut = request;
HttpTransportSE transport = new HttpTransportSE(URL);
try {
transport.call(NAMESPACE + SOAP_ACTION_PREFIX + METHOD, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
//bodyIn is the body object received with this envelope
if (envelope.bodyIn != null) {
//getProperty() Returns a specific property at a certain index.
//SoapPrimitive resultSOAP = (SoapPrimitive) ((SoapObject) envelope.bodyIn).getProperty(0);
//Object resultSOAP = (SoapPrimitive)((SoapObject) envelope.bodyIn).getProperty(0);
Object resultSOAP = (SoapPrimitive)((SoapObject) envelope.bodyIn).getProperty(0);
resp=resultSOAP.toString();
}
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
/**
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
// In this example it is the return value from the web service
textView.setText(result);
}
/**
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
}
/**
*
* #see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
#Override
protected void onProgressUpdate(String... text) {
textView.setText(text[0]);
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
}
What my web service do is take the MyType parameter as input and concatenate those two given strings and return the concatenated string.
When I run the android application I get an error(run time error I think) saying cannot serialize MyType.
Any suggestions to solve the issue?
Try implementing Serializable
public class MyType implements Serializable {
String fName;
String lName;
public MyType(String s1,String s2){
fName = s1;
lName = s2;
}
}

Categories

Resources