How to fix android.os.NetworkOnMainThreadException [duplicate] - android

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

Related

Reading data inserted into Google Fit API through HistoryAPI

I'm developing Google Fit API application and last 2 days I've been trying to store and retrieve data belongs to the BPM data type in different android applications. Meanwhile retrieving it returns zero points, although meanwhile inserting framework reports that everyting is inserted. I created OAuth keys for both applications, each of them has a subscription to this data type. Also I use enableServerQueries() for retrieval.
Datasource is being created as
daataSource=new DataSource.Builder().setName("measurementsSource").setDataType(DataType.TYPE_HEART_RATE_BPM).
setAppPackageName(getApplicationContext())
.setType(TYPE_RAW).build();
Does anyone has any ideas how to fetch data in a proper way?
Upd. According to the advice, I've added full code to add 1 point of custom DataType which I'd like to use. I've tried it number of times, but it still says 'ok' and no data could be available for getting back (for example, with API explorer).
package test.com.cloudydiscoverer;
import android.content.Intent;
import android.content.IntentSender;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataSource;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataTypeCreateRequest;
import com.google.android.gms.fitness.result.DataTypeResult;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static android.content.ContentValues.TAG;
import static com.google.android.gms.fitness.data.DataSource.TYPE_RAW;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_OAUTH = 1;
private static boolean authInProgress = false;
protected GoogleApiClient googleApiClient = null;
private GoogleApiClient.ConnectionCallbacks connectionCallbacks = null;
private void buildFitnessClient() {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this);
builder.addApi(Fitness.RECORDING_API);
builder.addApi(Fitness.SENSORS_API);
builder.addApi(Fitness.BLE_API);
builder.addApi(Fitness.SESSIONS_API);
builder.addApi(Fitness.HISTORY_API);
builder.addApi(Fitness.CONFIG_API);
builder.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE)); //TODO; verify scopes
builder.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE));
builder.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE));
builder.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE));
googleApiClient = builder.build();
}
public boolean flag=false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
connectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
/* try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
DataTypeCreateRequest request = new DataTypeCreateRequest.Builder()
.setName("test.com.cloudydiscoverer.cloudy_s")
.addField("value", Field.FORMAT_INT32)
.build();
Fitness.ConfigApi.createCustomDataType(googleApiClient, request)
.setResultCallback(new ResultCallback<DataTypeResult>() {
#Override
public void onResult(#NonNull DataTypeResult dataTypeResult) {
if (!dataTypeResult.getStatus().isSuccess()) {
Log.i(TAG, "DataType creation/retrieval failed with result: " + dataTypeResult.getStatus().getStatusMessage());
} else {
Log.i(TAG, "created");
DataSource wSource=new DataSource.Builder().setName(dataTypeResult.getDataType().getName()+".source").setDataType(DataType.TYPE_HEART_RATE_BPM).
setType(TYPE_RAW).setAppPackageName("test.com.cloudydiscoverer").build();
/* DataSource wetSource = new DataSource.Builder()
.setDataType(dataTypeResult.getDataType())
.build();*/
DataPoint b = DataPoint.create(wSource);
b.setTimestamp(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
b.setFloatValues(5.0f);
//b.getValue(dataTypeResult.getDataType().getFields().get(0)).setInt(42);
DataSet dataSet = DataSet.create(wSource);
dataSet.add(b);
Fitness.HistoryApi.insertData(googleApiClient, dataSet).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Log.i(TAG, String.valueOf(status.isSuccess()));
}
}
);
}
}
});
}
#Override
public void onConnectionSuspended(int i) {
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Toast.makeText(MainActivity.this, "Network is unavailable. " +
"Connection will be restored automatically.", Toast.LENGTH_SHORT).show();
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(MainActivity.this, "Service has been disconnected. " +
"Connection will be restored automatically.", Toast.LENGTH_SHORT).show();
}
}
};
GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed with result: " + result.getErrorCode());
if (!result.hasResolution()) {
return;
}
if (!authInProgress) {
try {
Toast.makeText(MainActivity.this, "You need to authorize.", Toast.LENGTH_SHORT).show();
authInProgress = true;
result.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Toast.makeText(MainActivity.this, "Exception has been caught.", Toast.LENGTH_SHORT).show();
}
}
}
};
Log.i("1","1");
buildFitnessClient();
googleApiClient.registerConnectionCallbacks(connectionCallbacks);
googleApiClient.registerConnectionFailedListener(onConnectionFailedListener);
Log.i("2","2");
googleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == RESULT_OK) {
if ((!googleApiClient.isConnected()) || (!googleApiClient.isConnecting()))
googleApiClient.connect();
} else {
Log.i(TAG, "Nothing could be done.");
}
}
}
}

Getting value in Service class from another class

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.

Uploading xml file to server using Android Service

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();

Error in http connectionandroid.os.NetworkOnMainThreadException [duplicate]

This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
when I launched my application I have a problem with emulator 4.1 and 4.2 even I have already made ​​the Internet permission, logcat shows this mssage:
Error in http connectionandroid.os.NetworkOnMainThreadException ?
package com.example.eagletracking;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.audiofx.BassBoost.Settings;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
public class GPSTrackingActivity extends Activity implements LocationListener {
Toast toast;
boolean isGPSAvaible;
private LocationManager lm;
private Location location;
private static String key =DBconection.key;
Calendar currentDate;
SimpleDateFormat formatter;
public static double latitude; // latitude
public static double longitude; // longitude
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 0) {
synchronisation();
}
else if (msg.what == 1) {
updateDatabase(location);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accueil);
if (isInternetAvailable(this)) {
Thread th = new Thread() {
public void run() {
try {
while (true) {
Thread.sleep(80000);
{
handler.sendEmptyMessage(0);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
th.start();
}
}
public static boolean isInternetAvailable(Context context) {
boolean isInternetAvailable = false;
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
if (networkInfo != null && (networkInfo.isConnected())) {
isInternetAvailable = true;
}
} catch (Exception exception) {
// Do Nothing
}
return isInternetAvailable;
}
#Override
protected void onResume() {
super.onResume();
try {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSAvaible = lm.isProviderEnabled (LocationManager.GPS_PROVIDER);
if (isGPSAvaible)
{
abonnementGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void abonnementGPS() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,
this);
if (lm != null) {
location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Thread th = new Thread() {
public void run() {
try {
while (location != null) {
Thread.sleep(6000);
{
handler.sendEmptyMessage(1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
th.start();
}
}
private void synchronisation() {
DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
SQLiteDatabase db = maBaseSQLite.getReadableDatabase();
Cursor c = maBaseSQLite.getAllRows();
int col = c.getCount(); // col=0 pas de enregistrement qui
// verifie la condition
if (col == 0) {
Toast.makeText(GPSTrackingActivity.this, "Pas de donnees ",
Toast.LENGTH_LONG).show();
// effacer le contenue champ login et mot de passe
} else {
c.moveToFirst();
while (c.isAfterLast() == false) {
// conversion int to string casting
String id = "" + c.getInt(0);
String longitude = c.getString(1);
String latitude = c.getString(2);
String time = c.getString(3);
String key_employe = c.getString(4);
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
4);
// nameValuePairs.add(new BasicNameValuePair("id",
// ch1));
nameValuePairs.add(new BasicNameValuePair("longitude",
longitude));
nameValuePairs
.add(new BasicNameValuePair("latitude", latitude));
nameValuePairs.add(new BasicNameValuePair("time", time));
nameValuePairs.add(new BasicNameValuePair("key_employe", key_employe));
c.moveToNext();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2:8888/android/synchron.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.d("connexion_expired",
"Error in http connection" + e.toString());
}
}
}
c.close();
maBaseSQLite.del();
maBaseSQLite.close();
}
private void updateDatabase(Location location) {
DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
SQLiteDatabase DB = maBaseSQLite.getWritableDatabase();
// maBaseSQLite.onCreate(DB);
//maBaseSQLite.onUpgrade(DB, 0, 0);
longitude= location.getLatitude();
latitude=location.getLatitude();
currentDate = Calendar.getInstance();
formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
maBaseSQLite.addPoint(String.valueOf(longitude),
String.valueOf(latitude),
formatter.format(currentDate.getTime()),(key));
Log.i("insert ", "ok");
maBaseSQLite.close();
}
#Override
public void onLocationChanged(Location arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
NetworkOnMainThread exception occurs when you are running network related operation on the main UI thread. http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
You use should use a asynctask for this purpose or create your own thread.
You are making a http request on the main ui thread.
http://developer.android.com/reference/android/os/AsyncTask.html
Check the link above especially the topic under the heading The 4 steps.
Example:
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)
{
//Network related opearaiton. Do not update ui here
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui
}
}
As doc says about NetworkOnMainThreadException:
the exception that is thrown when an application attempts to perform a networking operation on its main thread.
So, you're getting this error because you're running your client in the main Thread. To avoid this exception you can use an AsyncTask, Executor or simply using a Thread

onBind() is never called in a service

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.

Categories

Resources