Single socket.IO connection for all activities in android - java

I have created Singleton class for SocketIOClient reference by here. Server was connected. I can able to send request from activity to SocketIOClient. But how can I get response from Singleton class in Activity?
Here My Activity:
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText uname, passwd;
Button login;
JSONObject json;
SocketIOClient socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
socket = new SocketIOClient();
try {
SocketIOClient.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json = new JSONObject();
uname = (EditText) findViewById(R.id.unameED);
passwd = (EditText) findViewById(R.id.passwdED);
login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
json.put("username", uname.getText().toString().trim());
json.put("password", passwd.getText().toString().trim());
//request send to server
SocketIOClient.emit("login_request", json);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Also My Singleton Class have on() method:
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
if (event.equals("registration_status")) {
jarr_args.put(args[0]);
try {
jobj_in = jarr_args.getJSONObject(0);
Log.d("Result", jobj_in.getString("result"));
if (jobj_in.getString("result").equals("success")) {
} else {
Log.d("check:", "username and password");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here Singleton class can get response from server. But I want to know,how to get the response in my activity?

Create an abstract class like this
public abstract class ResponseHandler
{
private Context context;
public abstract void execute (JSONObject jsonObject) throws JSONException;
public ResponseHandler (Context ctx)
{
this.context = ctx;
}
public void handleObject(JSONObject jsonObject) throws Exception
{
execute(jsonObject);
}
}
Inside your activity
While calling socket class, pass the ResponseHadler also as a parameter
Example:
SocketIOClient.initInstance(your parameters, new ResponseHandler(this)
{
//ResponseHandler have an abstract method called execute(). So you are overriding it here
#Override
public void execute(JSONObject jsonObject) throws JSONException
{
// Here you will get your JSONObject passed from socket class
}
}
And inside your socket class
public class YourSocketClass
{
private ResponseHandler handler;
public static void initInstance(your parameter, ResponseHandler responseHandler)
{
this.handler = responseHandler;
// Do your operations here
}
#Override
public void on(String event, IOAcknowledge ack, Object... args)
{
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
if (event.equals("registration_status"))
{
jarr_args.put(args[0]);
try
{
jobj_in = jarr_args.getJSONObject(0);
Log.d("Result", jobj_in.getString("result"));
if (jobj_in.getString("result").equals("success"))
{
//If you want to pass your jsonobject from here to activity
//Do something like this
handler.handleObject(jobj_in);
}
else
{
Log.d("check:", "username and password");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}

Related

Could not display data from json in listview java and android.os.asynctask is deprecated

I got a problem when i want showing data with json from android with java
it showing nothing in here
But from json generator its fine
here is the example of json http://www.json-generator.com/api/json/get/cfYdxbAzma?indent=2
and here is my MainActivity.java
package com.example.callapi;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private static String url = "http://www.json-generator.com/api/json/get/cfYdxbAzma?indent=2";
ArrayList<HashMap<String,String>> bookList;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
bookList = new ArrayList<>();
}
private class getBooks extends AsyncTask<Void, Void,Void> {
#Override
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
if(progressDialog.isShowing())
{
progressDialog.dismiss();
}
ListAdapter listAdapter = new SimpleAdapter(MainActivity.this, bookList,R.layout.item,new String[]{"book_name"},new int[]{R.id.book_name});
listView.setAdapter(listAdapter);
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading.....");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids){
Handler handler = new Handler();
String jsonString = handler.httpServiceCall(url);
if(jsonString!=null){
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray books = jsonObject.getJSONArray("Book");
for(int i= 0; i<books.length(); i++){
JSONObject jsonObject1 = books.getJSONObject(i);
String id_book = jsonObject1.getString("id_book");
String book_name = jsonObject1.getString("book_name");
HashMap<String,String> bookMap = new HashMap<>();
bookMap.put("id_book",id_book);
bookMap.put("book_name",book_name);
bookList.add(bookMap);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
}
});
}
}
else {
Toast.makeText(getApplicationContext(),"Server Error",Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}
}
and i saw something like this android.os.AsyncTask is deprecated
What's going on here? is something wrong with my code?
thanks
Yes, Async Task is deprecated now. There are already better and best alternate available those already handled these hacks of handling automatically and provide more readable and maintainable code. You must try one of those as I am mentioned below:
Retrofit
Volley
LoopJ
And many examples can be found over stack-overflow very easily.
First of all, we would need a full stack trace of your exception to check what is wrong with the code. At first, what I don't see is you ever executing AsyncTask. Even though AsyncTask is deprecated it still works but it's an old solution to modern problems.
To fix this I would probably suggest working with RxJava, here is an example of how:
private void process() {
try {
Observable.fromCallable(new Callable<JsonNode>() {
#Override
public JsonNode call() {
try {
JSONObject jsonObject;
//prepare your JSONObject for HttpClient
JsonParser jsonParser = new CustomHttpClient().postParser(url, jsonObject.toString());
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(jsonParser);
} catch (Exception e) {
e.getMessage();
}
return JsonNodeFactory.instance.objectNode();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<JsonNode>() {
#Override
public void accept(#NonNull JsonNode node) throws Exception {
try {
if (node == null || node.isEmpty()) {
return;
}
if (node.get("status_code").asInt() != 200) {
return;
}
//do something with your data
} catch (Exception e) {
e.getMessage();
}
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) {
Exception e = new Exception(throwable.getMessage());
}
}, new Action() {
#Override
public void run() throws Exception {
try {
} catch (Exception e) {
e.getMessage();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
To get the data you need just call the function like anyother
process();
In my case, I work with JsonNode and I use my CustomHttpClient which is a class for itself. But you can do whatever you want, just edit it accordingly. There are also many other implementations of this using other libraries but I found this easy to read, quick and understandable.

Java for Android Call getPackageName() from within an AsyncTask

I am working on an Android app using InAppBilling. I recently moved the following code from my main Activity to an AsyncTask, as recommended by Google:
class GetItemList extends AsyncTask<Integer, Integer, Long> {
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
#Override
protected Long doInBackground(Integer... params) {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("i001");
skuList.add("i002");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object;
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
String mPremiumUpgradePrice;
String mGasPrice;
if (sku.equals("i001")) mPremiumUpgradePrice = price;
else if (sku.equals("i002")) mGasPrice = price;
}
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error Remote: " + e.getMessage());
e.printStackTrace();
}
catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error JSON: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
My problem is that the call to getPackageName() (the first line of the try block) is giving the error, "The method getPackageName() is undefined for the task GetItemList." How do I call getPackageName() from within an AsyncTask? I've tried GetContextWrapper.getPackageName(), getApplicationContext.getPackageName(), and getResources.getPackageName().
Corrected code, based on mixel's answer below:
package com.myknitcards;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.vending.billing.IInAppBillingService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class AvailableCards extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_cards);
String packagename = this.getPackageName();
new GetItemList(packagename).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.available_cards, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class GetItemList extends AsyncTask<Integer, Integer, Long> {
private String pName;
GetItemList(String packagename){
pName = packagename;
}
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
#Override
protected Long doInBackground(Integer... params) {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("i001");
skuList.add("i002");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, pName, "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object;
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
String mPremiumUpgradePrice;
String mGasPrice;
if (sku.equals("i001")) mPremiumUpgradePrice = price;
else if (sku.equals("i002")) mGasPrice = price;
}
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error Remote: " + e.getMessage());
e.printStackTrace();
}
catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error JSON: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
Add constructor to GetItemList that accepts packageName and assigns it to private field. Then use it in mService.getSkuDetails().
And when you instantiate GetItemList in your activity pass value that returned by getPackageName() to GetItemList constructor.

load data from JSON ArrayList into spinner

I can't seem to figure this out, since im just a beginner with this android stuff.
My app gets the customer names from my WebAPI via JSON.
Now I am trying to load it into a spinner, but how can I load my JSON arraylist in there?
I tried loading custTable in it but its shows "com.jetron.jetronbuitendienst.CustomerDetailsTable....." in the spinner now.
My Code:
package com.jetron.jetronbuitendienst;
import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Gegevens extends Main {
String Naam;
Spinner spCustomers;
private ArrayList<CustomerDetailsTable> Klanten;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gegevens);
new AsyncLoadCustDetails().execute();
spCustomers = (Spinner) findViewById(R.id.spKlanten);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
protected class AsyncLoadCustDetails extends
AsyncTask<Void, JSONObject, ArrayList<CustomerDetailsTable>> {
ArrayList<CustomerDetailsTable> custTable = null;
#Override
protected ArrayList<CustomerDetailsTable> doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetCustomerDetails();
JSONParser parser = new JSONParser();
custTable = parser.parseCustomerDetails(jsonObj);
Log.d("Customers: ", jsonObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadCustDetails", e.getMessage());
}
return custTable;
}
#Override
protected void onPostExecute(ArrayList<CustomerDetailsTable> result) {
// TODO Auto-generated method stub
// Application of the Array to the Spinner
ArrayAdapter<CustomerDetailsTable> spinnerArrayAdapter = new ArrayAdapter<CustomerDetailsTable>(getApplicationContext(), android.R.layout.simple_spinner_item, custTable);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spCustomers.setAdapter(spinnerArrayAdapter);
}
}
}
This is the jsonObj: D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}
Well Since you are getting this:
D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}
That implies that you are having an array that is called Value. So what you can do is this:
declare public variables :
private JSONObject jsonChildNode;
private JSONArray jsonMainNode;
private String name;
and then modify your code as:
try {
JSONObject jsonObj = api.GetCustomerDetails();
JSONParser parser = new JSONParser();
custTable = parser.parseCustomerDetails(jsonObj);
Log.d("Customers: ", jsonObj.toString());
jsonMainNode = jsonObj.optJSONArray("Value");
for (int i = 0; i < jsonMainNode.length(); i++) {
jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("Naam");
}
//and then you can add the name to a List<String> which will contain all the values of each item in the Value JSON Array.
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadCustDetails", e.getMessage());
}
Hope it helps!!!
That worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
Check API reference here.
ArrayAdapter uses the Object.toString() to fill the view.
Here in the code, with the Object CustomerDetailsTable does not override the toString() function, So it just print the name of the class.

Memory leak in service android

I am implementing the bound service for the socket.io implementation in android for single socket maintenance to connect with nodejs server by this Gottox library. When I implementing this the memory of the service is not stable like while on starting of the service it takes around 30MB to 40MB, after some time it also leads to 200MB. So I thought it may be memory leak. But i don't get any single clue to find it.
Codes
DemoActivity.java
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.actionbarsherlock.app.SherlockActivity;
import com.devspark.appmsg.AppMsg;
import com.devspark.appmsg.AppMsg.Style;
import com.nuappz.Demo.DemoService.MyLocalBinder;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
public class DemoActivity extends SherlockActivity {
MySharedPreferences pref;
DemoService socketService;
boolean isBound;
EditText name, mobile_no, email, password;
Button Demo;
Style style_alert, style_success;
JSONObject json_Demo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Demo);
isBound = false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// start the bind service
if (!isBound) {
bindService(new Intent(DemoActivity.this,
DemoService.class), myConnection,
Context.BIND_AUTO_CREATE);
isBound = true;
startService(new Intent(this, DemoService.class));
socketService = DemoService.getInstance();
}
}
public ServiceConnection myConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
socketService = ((MyLocalBinder) service).getService();
isBound = true;
}
};
protected void onDestroy() {
if (isBound) {
// Disconnect from an application service. You will no longer
// receive calls as the service is restarted, and the service is
// now allowed to stop at any time.
unbindService(myConnection);
isBound = false;
}
stopService(new Intent(DemoActivity.this, DemoService.class));
super.onDestroy();
}
}
DemoService.java
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
/*
* This class is Background service for the Blood Drop application
*/
public class DemoService extends Service {
private static final String serverUrl = "http://nuappzdev.hello.com:8080/";
private static SocketIO socket;
private static DemoService instance;
private static ResponseHandler handler;
public boolean bound;
JSONObject jobj_in = new JSONObject();
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("Service", "Started");
super.onCreate();
// connecting socket
try {
DemoService.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public DemoService() {
}
public static DemoService getInstance() {
return instance;
}
// start the service to handle the functions
public int onStartCommand(Intent intent, int flags, int startId) {
// HandleReceiveRequest();
return START_STICKY;
}
// Stop the services
public void onDestroy() {
Log.d("Service", "Stopped");
getSocket().disconnect();
}
// Binder class initialize
public class MyLocalBinder extends Binder {
DemoService getService() {
return DemoService.this;
}
}
private final IBinder myBinder = new MyLocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
bound = true;
return myBinder;
}
// initiate the socket connection
public static void initInstance() throws MalformedURLException {
if (instance == null) {
instance = new DemoService();
if (DemoService.getSocket() == null) {
DemoService.setSocket(new SocketIO());
}
DemoService.connectIO();
}
}
// Method to get socket
public static SocketIO getSocket() {
return socket;
}
// Method to set socket
public static void setSocket(SocketIO socket) {
DemoService.socket = socket;
}
// Method to ConnectIO to server
public static void connectIO() throws MalformedURLException {
try {
SocketIO.setDefaultSSLSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DemoService.getSocket().connect(serverUrl, new IOCallback() {
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
}
#Override
public void onError(SocketIOException socketIOException) {
Log.d("Connection:", "Error in Connection");
}
#Override
public void onDisconnect() {
// TODO Auto-generated method stub
Log.d("Connection:", "disConnected");
}
#Override
public void onConnect() {
Log.d("Connection:", "Connected");
}
#Override
// Method to getting response from server
public void on(String event, IOAcknowledge ack, Object... args) {
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
try {
jarr_args.put(args[0]);
jobj_in = jarr_args.getJSONObject(0);
jobj_in.put("event", event);
Log.d("jobject: event", jobj_in.getString("event"));
try {
handler.handleObject(jobj_in);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
// Method to send request to server
public static void emit(String event, Object args,
ResponseHandler responseHandler) throws MalformedURLException {
handler = responseHandler;
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, args);
}
// Method to send request to server with Acknowledge
public static void emitWithAcknowledge(String event, Object args)
throws MalformedURLException {
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, new IOAcknowledge() {
#Override
public void ack(Object... args) {
// TODO Auto-generated method stub
}
}, args);
}
}
}
What are the chances of memory leak in this code.
You needs to unbind service in onStop of your activity and you should never call stopService from your activity. Let Android do the handling of life cycle of your service.

Android: how to restart a method with a button click

I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources