I am creating a project in which I am getting data from a server and displaying it through table view. Here is the code for Main activity class
package com.example.e_quates;
import java.net.URL;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
//import com.websmithing.broadcasttest.BroadcastService;
//import com.websmithing.broadcasttest.BroadcastService;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import java.sql.SQLException;
public class MainActivity extends Activity {
List<String> strs = new ArrayList<String>();
ResultSet rs=null;
TableLayout tl;
TableRow[] tr;
TextView[] tv;
private Intent intent;
private static final String TAG = "E-Quates";
int count=1;
public static DB db = new DB(<connection string>);
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
strs=db.sqlexec(query);
db.closeConnection();
Log.e("connected ","success");
System.out.println("connection sucess");
tl=(TableLayout)findViewById(R.id.table);
Log.e("first row","created");
tr=new TableRow[strs.size()/7];
tv=new TextView[strs.size()];
//int i=0;
for(int i=0,j=-1;i<strs.size();i++)
{
Log.e("index "+i,"value is "+strs.get(i));
if(i%7==0)
{
j++;
Log.e("inside if","value "+i);
tr[j]=new TableRow(this);
tr[j].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
tv[i] = new TextView(this);
tv[i].setText(strs.get(i));
tv[i].setId(i);
tv[i].setBackgroundResource(R.drawable.row_shape);
tr[j].addView(tv[i]);
}
for(int i=0,j=-1;i<strs.size()/7;i++)
{
tl.addView(tr[i]);
Log.e("adding row",""+i);
}
//Thread.sleep(5000);
}
catch(Exception E)
{
System.out.println(E.toString());
}
intent = new Intent(this, BroadcastService.class);
}
public void onResume() {
super.onResume();
startService(intent);
Log.e("service","called");
registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("in the","receiver");
updateUI(intent);
}
};
private void updateUI(Intent intent) {
strs.clear();
//String dummy = null;
Log.e("inside ","UI update");
//db.sqlexec(query);
try
{
strs = intent.getStringArrayListExtra("TAG");
//application_main apm=((application_main) getApplicationContext());
for(int i=0;i<strs.size();i++)
{
Log.e("inside for","loo[");
tv[i].setText(strs.get(i));
}
}
catch(Exception e)
{
Log.e("exception occured in intent value",e.toString());
}
//Log.e("value is ",dummy.toString());
//Thread.sleep(5000);
}
}
Here is my DB class
package com.example.e_quates;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
//import android.widget.*;
class DB extends Activity
{
List<String> strs = new ArrayList<String>();
ResultSet rs=null;
Connection conn=null;
private Intent intent;
#SuppressLint("NewApi")
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
public DB(String db_connect_string,String db_userid,String db_password) {
System.out.println("inside DB");
Log.e("inside DB","");
try
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.e("Inside first","try block");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
Log.e("Connection sucessfull","");
}catch (Exception e)
{
e.printStackTrace();
}
}
public List<String> sqlexec(String sql)
{
try
{
Statement stmt = null;
strs.clear();
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
Log.e("##########################################################################3","result in rs");
while (rs.next()) {
strs.add(rs.getString("SymbolName"));
strs.add(rs.getString("LTP"));
strs.add(rs.getString("Net_change"));
strs.add(rs.getString("Bid_vol"));
strs.add(rs.getString("Ask"));
strs.add(rs.getString("Ask_vol"));
strs.add(rs.getString("High_Index"));
Log.e("symbolname",rs.getString("SymbolName"));
}
}catch (Exception e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
Log.e("error:",e.toString());
}
Log.e("return ","to main");
int size=strs.size();
Log.e("array size in DB",""+size);
//Log.e("set string",String.valueOf(apm.getState()));
Log.e("application ","initialized");
return strs;
}
public void closeConnection()
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
And here is the service class
package com.example.e_quates;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class BroadcastService extends Service {
List<String> strs_array1 = new ArrayList<String>();
private static final String TAG = "E-Quates";
public static final String BROADCAST_ACTION = "com.example.e_quates";
private final Handler handler = new Handler();
Intent intent;
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
int counter = 0;
DB db1=new DB(<connection string>);
//String dummy;
#Override
public void onCreate() {
super.onCreate();
//db1.forService();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 3000); // 3 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 3000); // 3 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
strs_array1=db1.sqlexec(query);
intent.putStringArrayListExtra(TAG, (ArrayList<String>)strs_array1);
sendBroadcast(intent);
Log.e("Broadcast","done");
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
The problem is that when I am calling the DB class's sqlexec() function from main activity class it is return correct value but while is I am calling it service class it is not returning the SQL output. I have tried every possible combination of calling the sqlexec() function inside the service class,but same problem is occurring.
the function db.sqlexec(query) is not returning any value..
I have referred the link for help:
Don't do any initialization in the Service constructor. Android constructs Android components (Activity, Service, BroadcastReceiver, ContentProvider) using its own mechanisms. Move all your initialization code from the constructor to the onCreate() method.
EDIT: Clarify my instructions
I am referring to this code:
List<String> strs_array1 = new ArrayList<String>();
private static final String TAG = "E-Quates";
public static final String BROADCAST_ACTION = "com.example.e_quates";
private final Handler handler = new Handler();
Intent intent;
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
int counter = 0;
DB db1=new DB(<connection string>);
These variables will be initialized in the constructor (even though you haven't explicitly created a constructor, one will be created for you). The constants aren't a problem, but these may cause you a problem:
private final Handler handler = new Handler();
DB db1=new DB(<connection string>);
You will want to be creating the Handler in onCreate(). I don't know what your DB class is doing, but you probably want to be creating that instance also in onCreate().
EDIT 2
I now see the code for your DB class. You can't do this like this! Your DB class extends Activity. You cannot create an instance of this class like this:
DB db1=new DB(<connection string>);
Android components (Activity, Service, BroadcastReceiver, ContentProvider) are created by the Android framework using its own mechanisms.
Why does your DB class extend Activity? It doesn't need to.
Related
Hello iam stuck in problem since yesterday searched everything anywhere i create application which show device which arre connected to same router wifi , then iam able to connect both device using this exmple
https://developer.android.com/guide/topics/connectivity/wifip2p.html#creating-app
everything is okay both devices are connected but when transfer file serviceintent is not starting so thats why i cant transfer anything , there is not log error but happend nothing when i choose image to send
MainActivity Class
package com.b.wifip2p;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {
Button button;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
WifiP2pManager.Channel mChannel = null;
WifiP2pManager mManager;
private WifiP2pInfo info;
BroadCast broadCast;
private BroadcastReceiver receiver = null;
static List peers = new ArrayList();
ListView lv;
static Adapater myadapter;
ArrayList<DeviceInfo_Bean>list=new ArrayList<>();
private WifiP2pDevice device;
String hostaddd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=findViewById(R.id.lv);
myadapter=new Adapater(this,list);
button=findViewById(R.id.button);
lv.setAdapter(myadapter);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
connect();
}
});
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
System.out.println("---sucess discover");
}
#Override
public void onFailure(int reasonCode) {
System.out.println("---fail");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 007);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
System.out.println("---ip"+ipAddress);
}
});
}
#Override
public void onResume() {
super.onResume();
broadCast = new BroadCast(mManager, mChannel, MainActivity.this);
registerReceiver(broadCast, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadCast);
}
private static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void
onPeersAvailable(WifiP2pDeviceList peerList) {
List<WifiP2pDevice> refreshedPeers = (List<WifiP2pDevice>) peerList.getDeviceList();
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
System.out.println("---ref"+refreshedPeers);
}
if (peers.size() == 0) {
Log.d("-----deviceno", "No devices found");
return;
}
}
};
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for (WifiP2pDevice device : peers.getDeviceList())
{
list.clear();
String address=device.deviceAddress;
String name=device.deviceName;
System.out.println("---name"+name+address);
list.add(new DeviceInfo_Bean(name,address));
}
myadapter.notifyDataSetChanged();
Log.i("----", "Found some peers!!! " + peers.getDeviceList());
}
public void connect() {
DeviceInfo_Bean device = list.get(0);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.address;
config.wps.setup = WpsInfo.PBC;
System.out.println("device in"+device.address);
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
// TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
// statusText.setText("Sending: " + uri);
// Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
startService(serviceIntent);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
//private TextView statusText;
/**
* #param context
*
*/
public FileServerAsyncTask(Context context) {
this.context = context;
//this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
System.out.println("---socket");
Socket client = serverSocket.accept();
///Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
//Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
OutputStream stream = client.getOutputStream();
String s="---mymsg";
stream.write(s.getBytes());
Log.e("hello","context value "+context);
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
// statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime=System.currentTimeMillis();
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime=System.currentTimeMillis()-startTime;
Log.v("","Time taken to transfer all bytes is : "+endTime);
} catch (IOException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
System.out.println("---info");
this.info=info;
// view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
InetAddress groupOwnerAddress = info.groupOwnerAddress;
System.out.println("--g"+groupOwnerAddress);
System.out.println("--info"+info.groupOwnerAddress.getHostAddress());
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getApplication())
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
}
// hide the connect button
// mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
public void showDetails(WifiP2pDevice device) {
this.device = device;
// this.getView().setVisibility(View.VISIBLE);
// TextView view = (TextView) mContentView.findViewById(R.id.device_address);
// view.setText(device.deviceAddress);
//view = (TextView) mContentView.findViewById(R.id.device_info);
//view.setText(device.toString());
System.out.println("---device"+device.deviceAddress);
}
}'
Broadcast
package com.b.wifip2p;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import java.nio.channels.Channel;
/**
* Created by BHM on 3/3/2018.
*/
public class BroadCast extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity activity;
PeerListListener peerListListener=null;
public BroadCast(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.activity = (MainActivity) activity;
}
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("-----broadcast");
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
// activity.setIsWifiP2pEnabled(true);
} else {
//activity.setIsWifiP2pEnabled(false);
// activity.resetData();
}
// Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
// mManager.requestPeers(mChannel, (PeerListListener) mChannel);
}
// Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
if (mManager == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// we are connected with the other device, request connection
// info to find group owner IP
mManager.requestConnectionInfo(mChannel, activity);
} else {
// It's a disconnect
// activity.resetData();
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
// .findFragmentById(R.id.frag_list);
// fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
// WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
}
}
}
FileTransferService here intent is not coming
package com.b.wifip2p;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* Created by BHM on 3/4/2018.
*/
class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("--intent");
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
// Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
// Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
}
MainActivity.copyFile(is, stream);
// Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
I know this is a slightly old question by now, but for those looking for answers:
I would recommend checking that you have the intent filters properly in your AndroidManifest.xml file.
It should look something like:
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.ACTION_SEND_FILE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I'm novice with web service and i try to create a web service with netbeans, i test it with rest client (mozilla plugin) it work but when i try to use the android client, it's doesn't and i receive this android.os.NetworkOnMainThreadException in my logcat. Here is the code
<pre><code>
package cg.skylab.clientrest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
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 android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import cg.skylab.clientrest.model.Personne;
public class ListePersonnel extends ListActivity {
private ArrayList<Personne> personnes = new ArrayList<Personne>();
private String adresse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.liste);
startActivityForResult(new Intent(this, ChoixServeur.class), 1);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intention) {
if (resultCode == RESULT_OK) {
adresse = intention.getStringExtra("adresse");
try {
miseAJour();
} catch (Exception ex) {
Toast.makeText(this, "Reponse incorrecte", Toast.LENGTH_SHORT).show();
String tagException = ex.toString();
String tagAdresse = intention.getStringExtra("adresse");
Log.i(tagException, "Exception");
Log.i(tagAdresse, "Adresse IP");
}
}
}
#Override
protected void onResume() {
super.onResume();
if (adresse != null)
try {
miseAJour();
} catch (Exception ex) {
}
}
#Override
protected void onStop() {
super.onStop();
finish();
}
public void miseAJour() throws IOException, JSONException {
HttpClient client = new DefaultHttpClient();
HttpGet requete = new HttpGet("http://"+adresse+":8080/Personnel/rest/"+1);
HttpResponse reponse = client.execute(requete);
if (reponse.getStatusLine().getStatusCode() == 200) {
Scanner lecture = new Scanner(reponse.getEntity().getContent());
StringBuilder contenu = new StringBuilder();
while (lecture.hasNextLine())
contenu.append(lecture.nextLine() + '\n');
JSONArray tableauJSON = new JSONArray(contenu.toString());
StringBuilder message = new StringBuilder();
personnes.clear();
for (int i = 0; i < tableauJSON.length(); i++) {
JSONObject json = tableauJSON.getJSONObject(i);
Personne personne = new Personne();
personne.setId(json.getLong("id"));
personne.setNom(json.getString("nom"));
personne.setPrenom(json.getString("prenom"));
personne.setNaissance(json.getLong("naissance"));
personne.setTelephone(json.getString("telephone"));
personnes.add(personne);
}
setListAdapter(new ArrayAdapter<Personne>(this,
android.R.layout.simple_list_item_1, personnes));
} else
Toast.makeText(this, "Problème de connexion avec le serveur",
Toast.LENGTH_SHORT).show();
}
public void edition(View v) {
Intent intention = new Intent(this, Personnel.class);
intention.putExtra("id", 0);
intention.putExtra("adresse", adresse);
startActivity(intention);
}
protected void onListItemClick(ListView liste, View v, int position, long id) {
Personne personne = personnes.get(position);
Intent intention = new Intent(this, Personnel.class);
intention.putExtra("id", personne.getId());
intention.putExtra("adresse", adresse);
intention.putExtra("nom", personne.getNom());
intention.putExtra("prenom", personne.getPrenom());
intention.putExtra("naissance", personne.getNaissance());
intention.putExtra("telephone", personne.getTelephone());
startActivity(intention);
}
}
</code></pre>
You are getting NewtworkOnMainThread exception because you are making network calls on the UI thread. This is a bad practice because it can block/bog down your UI thread which would make your app feel slow.
To avoid that error you have to use AsyncTask.
You have to use like this:
public class DowloadTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
};
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Call your web service here
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// Update your UI here
return;
}
}
For more detail check out this article
I am developing an application in android wrein I call a service that will upload a xml file to the server on click of a button.Problem is when I click the button first time it dosent get uploaded but when I click the button second time its gets uploaded...so let me know if there is any solution..pls help me.
Here is code below which extends service
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
public class Uploader extends Service
{
String info;
String phot_loc;
int category;
String phonenumber = null,profile_name=null,email_id=null;
double longi;
double latti;
Runnable runner;
//UIhandler to display the status of upload on response from server
Handler uiHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
if(intent!=null)
{
info=intent.getStringExtra("info");
phot_loc=intent.getStringExtra("photo_loc");
category=intent.getIntExtra("category",0);
phonenumber=intent.getStringExtra("phone_number");
profile_name=intent.getStringExtra("profile_name");
email_id=intent.getStringExtra("email_id");
longi=intent.getDoubleExtra("longitude",0);
latti=intent.getDoubleExtra("latitude",0);
phonenumber=intent.getStringExtra("phone_number");
Log.d("UploadService","Indide upload Activity");
Thread t=new Thread(runner);
t.start();
}
//this will perform the uploading process
runner=new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try
{
Log.d("UploadService","Indide upload Activity RIUNNER");
String xml = createXml();
RestClient client = new RestClient("http://3pixelart.com/complaint_process.php",xml);
//Log.d("UploadService", xml);
try {
client.Execute();
MyRunnable r = new MyRunnable("Complaint Uploaded Successfully");
uiHandler.post(r);
}
catch(Exception e)
{
Log.e("UploadService", "Exception in uploading :"+e.getMessage());
MyRunnable r = new MyRunnable("There was an error while registering complaint. Pls try again "+ e.getMessage());
uiHandler.post(r);
}
}
catch(Exception e)
{
Log.e("UploadService", "Exception:"+e.getMessage());
MyRunnable r=new MyRunnable("Error in uploading the complaint..");
uiHandler.post(r);
}
}
};
}
public String createXml() {
Log.d("UploadService","Indide upload Activity create xml 1");
Log.d("UploadService","Indide upload Activity create xml 2");
Date d = new Date();
//SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
//String time = formatter.format(d);
Log.d("UploadService","Indide upload Activity create xml 3");
String imageData = getBase64ImageData();
SimpleDateFormat fileNameFormatter = new SimpleDateFormat("ddMMyyHHmm");
Log.d("UploadService","Indide upload Activity create xml 5");
String filename = "image"+fileNameFormatter.format(d)+".png";
String finaldata="<?xml version=\"1.0\"?>";
finaldata+="<ClientRequest><MobileNumber>"+phonenumber+"</MobileNumber><Longitude>";
finaldata+=longi+"</Longitude><Lattitude>"+latti+"</Lattitude>";
finaldata+="<Category>"+category+"</Category>";
finaldata+="<Profilename>"+profile_name+"</Profilename><Email>"+email_id+"</Email>";
finaldata+="<FileName>"+filename+"</FileName><Image>"+imageData+"</Image><Info>";
finaldata+=info+"</Info></ClientRequest>";
Log.d("UploadService","The DATA IS : "+finaldata);
return finaldata;
}
private String getBase64ImageData() {
// TODO Auto-generated method stub
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapOrg = BitmapFactory.decodeFile(phot_loc,options);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String encodedImage = Base64.encodeToString(ba, Base64.DEFAULT);
//Log.d("UploadService", encodedImage);
bitmapOrg=null;
System.gc();
return encodedImage;
}
//this is used to display the status of uploading for this u require UIHandler
public class MyRunnable implements Runnable{
private String message=null;
public MyRunnable(String message) {
// TODO Auto-generated constructor stub
this.message=message;
}
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
};
}
and this is my activity which strats that service
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class ComplaintActivity extends Activity implements OnClickListener
{
boolean pic_taken=false;
Button bpicture,bregister;
EditText description;
ImageView iv1;
int category=0;
private static final int TAKE_PICTURE = 1;
String Provider_name="";
Location currentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint);
bpicture=(Button) findViewById(R.id.button1);
bregister=(Button) findViewById(R.id.button2);
iv1=(ImageView) findViewById(R.id.taken_pic);
description=(EditText)findViewById(R.id.editText1);
bpicture.setOnClickListener(ComplaintActivity.this);
bregister.setOnClickListener(ComplaintActivity.this);
LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
List <String> l1=manager.getProviders(true);
if(l1.contains(LocationManager.GPS_PROVIDER))
{
Provider_name=LocationManager.GPS_PROVIDER;
}
if(l1.contains(LocationManager.NETWORK_PROVIDER))
{
Provider_name=LocationManager.NETWORK_PROVIDER;
}
currentLocation=manager.getLastKnownLocation(Provider_name);
Toast.makeText(ComplaintActivity.this, "GPS PROVIDERS "+Provider_name+"Lattti:"+currentLocation.getLatitude()+"Long:"+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
LocationListener listener=new MyLocationListener();
manager.requestLocationUpdates(Provider_name, 0, 0, listener);
}
class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentLocation=location;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0==bpicture)
take_picture();
if(arg0==bregister)
register_complaint();
}
private void take_picture() {
// TODO Auto-generated method stub
Intent int_cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri Outputfile=Uri.parse("file:///sdcard/temppic.jpg");
int_cam.putExtra(MediaStore.EXTRA_OUTPUT,Outputfile);
startActivityForResult(int_cam,TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//Log.d("BAKRA","INSIDE CAMEra Activity>>>>>>>>>>>");
if(requestCode==1)
{
//Log.d("BAKRA","INSIDE FIRST IF >>>>>>>>>>>");
if(resultCode==RESULT_OK)
{
// Log.d("BAKRA","INSIDE SECONG IF >>>>>>>>>>>");
if(data==null)
{
// Log.d("BAKRA","INSIDE THIRD IF >>>>>>>>>>>");
pic_taken=true;
BitmapFactory.Options opt=new BitmapFactory.Options();
opt.inSampleSize=8;
Bitmap bitorg=BitmapFactory.decodeFile("sdcard/temppic.jpg", opt);
// Log.d("BAKRA","INSIDE CAME>>>>>>>>>>>");
iv1.setImageBitmap(bitorg);
}
}
}
}
private void register_complaint() {
// TODO Auto-generated method stub
if(!pic_taken)
{
Toast.makeText(ComplaintActivity.this, "Please Take the Picture Related to the Query", Toast.LENGTH_LONG).show();
return;
}
if(description.getText().toString().equals(""))
{
Toast.makeText(ComplaintActivity.this, "Please Enter Details About the Complaint",Toast.LENGTH_LONG).show();
return;
}
else
{
Intent up=new Intent(ComplaintActivity.this,Uploader.class);
up.putExtra("category",getIntent().getIntExtra("Selected",1));
up.putExtra("info", description.getText().toString());
up.putExtra("photo_loc", "/sdcard/temppic.jpg");
up.putExtra("latitude", currentLocation.getLatitude());
up.putExtra("longitude", currentLocation.getLongitude());
SQLiteDatabase db=openOrCreateDatabase("LBA", MODE_PRIVATE, null);
Cursor c=db.rawQuery("select * from users", null);
String phonenumber = null,profile_name=null,email_id=null;
if(c.moveToFirst())
{
profile_name=c.getString(c.getColumnIndex("profilename"));
email_id=c.getString(c.getColumnIndex("emailid"));
phonenumber=c.getString(c.getColumnIndex("phonenumber"));
}
up.putExtra("phone_number", phonenumber);
up.putExtra("profile_name", profile_name);
up.putExtra("email_id", email_id);
startService(up);
Toast.makeText(ComplaintActivity.this, "Uploading to Server...",Toast.LENGTH_LONG).show();
finish();
}
}
}
onStartCommand intent:
This may be null if the service is being restarted after its process
has gone away, and it had previously returned anything except
START_STICKY_COMPATIBILITY.
http://developer.android.com/reference/android/app/Service.html
So try use:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
rather than finish();
i'm trying to get the communication between activities and a service to work.
i am pretty new to android and java, learned it my self through youtube :D, but cant find or solve this one.
at first i made an activity with a class thread which handles an ethernet socket. but i discovered when i leave the activity and switch to another the thread is destroyed. to preserve the thread i included the thread inside an service. but now i cant use the functions inside the thread (like sending/getting status). how can i get the instance of my ethernet class back to all of my activities. below i clipped my code.
the code works and run. but when i want to call my send() function or getConStatus() it crashed.
working on a client server communication for home domotics.
// my main activity
import java.io.IOException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
//UI declerations
Button button1, button2;
EditText text1,text2;
ProgressBar waiter;
Ethernets eth;
house house;
Toast message;
ProgressTask Task;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
text1 = (EditText)findViewById(R.id.editText1);
text2 = (EditText)findViewById(R.id.editText2);
waiter = (ProgressBar)findViewById(R.id.Waiter);
}
protected void onStop()
{
Intent intent = new Intent(this, Ethernet_Service.class);
stopService(intent);
}
public void start(View view)
{
eth.send("Turn ON"); // i cant USE this !!
}
public void connect(View view) throws UnknownHostException, IOException
{
String ip = null;
int port = 0;
ip = text1.getText().toString();
port = Integer.parseInt(text2.getText().toString());
Intent intent = new Intent(this, Ethernet_Service.class);
startService(intent);
}
}
// my service
package com.example.homeapp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class Ethernet_Service extends Service{
public Ethernet_Service() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startid)
{
Ethernets eth = new Ethernets("I9001", "192.168.1.101", 4000);
eth.start();
return startid;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
// my ethernet thread class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import android.util.Log;
public class Ethernets extends Thread {
Thread ethernetThread, recieveThread;
Socket ethernetSocket;
PrintStream PW;
String IP;
int PORT;
boolean connect_status = false;
String Client_Name;
public Ethernets(String name, String ip, int port)
{
Client_Name = name;
PORT = port;
IP = ip;
}
public void run()
{
try
{
ethernetSocket = new Socket(IP,PORT);
if(ethernetSocket.isConnected() == true)
{
connect_status = true;
}
else{connect_status = false;}
PW = new PrintStream(ethernetSocket.getOutputStream(),true);
}catch(Exception ex){}
recieveThread = new Thread(new Runnable() {
#Override
public void run() {
String message;
try
{
BufferedReader BR = new BufferedReader(new InputStreamReader(ethernetSocket.getInputStream()));
while((message = BR.readLine()) != null)
{
System.out.println("message: "+message);
}
} catch (IOException e) {e.printStackTrace();}
}
});
recieveThread.start();
}
public void send(String msg)
{
//protocol description
byte[] buffer = {(byte) 0x02, (byte) 0x04, (byte) 'B', (byte) 0x02, 0x00, 0x00, (byte) 0x46 };
try
{
Log.i("hi","hi");
PW.write(buffer);
PW.flush();
} catch (IOException e) {e.printStackTrace();}
}
public boolean getconStatus()
{
return connect_status;
}
}
I am writing a service based app with a bound service, and the service's onBind() method never seems to be called (testing it with Toasts and Logs).
The service:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.MyActivity;
import com.gmail.zack.yovel.FlickAround.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 19:06
* To change this template use File | Settings | File Templates.
*/
public class UpdateService extends Service implements LocationListener, UpdatePhotosTask.OnHttpResponseListener {
private final static String API_KEY = "5255c7b02750c0fa4b15bd8ad4ec1fb7";
private final static String GET_PHOTOS_FOR_LOCATION_SCHEMA = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + API_KEY + "&lat=%d&lon=%d&format=json&nojsoncallback=1";
private static final String KEY_PHOTOS = "photos";
private static final String KEY_PHOTO = "photo";
private int NOTIFICATION = R.string.update_service_started;
private NotificationManager mNManager;
private LocationManager mLManager;
private String mProvider;
private Location mLocation;
private IBinder mBinder = new LocalBinder();
private UpdatePhotosTask task;
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "UpdateService.onBind()", Toast.LENGTH_LONG).show();
Log.i("test", "UpdateService.onBind()");
mLManager.requestLocationUpdates(mProvider, 0, 1000, this);
return mBinder;
}
#Override
public void onCreate() {
mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
mLManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mProvider = mLManager.getBestProvider(criteria, false);
mLocation = mLManager.getLastKnownLocation(mProvider);
return START_STICKY;
}
#Override
public void onDestroy() {
mNManager.cancel(NOTIFICATION);
Toast.makeText(this, R.string.update_service_stoped, Toast.LENGTH_SHORT).show();
}
private void showNotification() {
CharSequence text = getText(R.string.update_service_active);
Notification notification = new Notification(R.drawable.refresh, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
notification.setLatestEventInfo(this, getText(R.string.update_service_label), text, contentIntent);
mNManager.notify(NOTIFICATION, notification);
}
#Override
public void onLocationChanged(Location location) {
beginUpdate(location);
}
private void beginUpdate(Location location) {
Toast.makeText(this, "beginning update", Toast.LENGTH_LONG).show();
String url = buildUrl(location);
task = new UpdatePhotosTask(this);
task.execute(url);
}
private String buildUrl(Location location) {
return String.format(GET_PHOTOS_FOR_LOCATION_SCHEMA, location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onHttpResponse(ArrayList<String> responses) {
if (responses.size() > 0) {
String response = responses.get(0);
try {
JSONObject jsonObject = new JSONObject(response);
jsonObject = jsonObject.getJSONObject(KEY_PHOTOS);
JSONArray jsonArray = jsonObject.getJSONArray(KEY_PHOTO);
ArrayList<String> photos = new ArrayList<String>();
for (int i = 0, length = jsonArray.length(); i < length; i++) {
jsonObject = jsonArray.getJSONObject(i);
Log.i("photo info", jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class LocalBinder extends Binder {
public UpdateService getService() {
return UpdateService.this;
}
}
}
The AsyncTask:
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 07:38
* To change this template use File | Settings | File Templates.
*/
public class UpdatePhotosTask extends AsyncTask<String, Void, ArrayList<String>> {
private OnHttpResponseListener listener;
public UpdatePhotosTask(OnHttpResponseListener listener) {
this.listener = listener;
}
#Override
protected ArrayList<String> doInBackground(String... urls) {
ArrayList<String> responses = new ArrayList<String>();
for (String url : urls) {
StringBuilder response = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
StatusLine statusLine = execute.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response.append(s);
}
responses.add(response.toString());
} else {
Log.e(this.getClass().toString(), "Failed to download photo list");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responses;
}
#Override
protected void onPostExecute(ArrayList<String> responses) {
listener.onHttpResponse(responses);
}
public interface OnHttpResponseListener {
public void onHttpResponse(ArrayList<String> responses);
}
}
The activity:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.background.UpdateService;
public class MyActivity extends Activity {
private UpdateService mUpdateService;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mUpdateService = ((UpdateService.LocalBinder) service).getService();
Toast.makeText(MyActivity.this, R.string.update_service_connected, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
mUpdateService = null;
Toast.makeText(MyActivity.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show();
}
};
private boolean mIsBound;
void doBindService() {
Toast.makeText(this, "MyActivity.doBindService()", Toast.LENGTH_LONG).show();
bindService(new Intent(this, UpdateService.class), mConnection, BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Activate StrictMode
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().penaltyDeath().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().penaltyDeath().build());
}
#Override
protected void onStart() {
super.onStart();
doBindService();
}
}
Why isn't it working?
Probably the most common source of binding silently failing is not having the service listed in the manifest. This does not raise an exception, so your app does not crash, but there should be a message (warning, IIRC) in LogCat pointing out your issue.