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();
Related
I want to update my location on server using service but i am not getting why my service is not running. here is code:
package com.example.friendlocation;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class UpdateLocationService extends Service {
String url = "http://coders-hub.com/googlemap/new/location.php";
JSONParser jsonParser = new JSONParser();
String id;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent==null || intent.getAction()==null)
return START_NOT_STICKY;
Toast.makeText(getApplicationContext(), "In onCreate()!", Toast.LENGTH_SHORT).show();
SharedPreferences sp=getSharedPreferences("location", Activity.MODE_PRIVATE);
id=sp.getString("id", null);
if(id!=null)
{
Toast.makeText(getApplicationContext(), "In id!", Toast.LENGTH_SHORT).show();
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria c=new Criteria();
String provider=lm.getBestProvider(c, false);
lm.requestLocationUpdates(provider, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
params.add(new BasicNameValuePair("lat", location.getLatitude()+""));
params.add(new BasicNameValuePair("longi", location.getLongitude()+""));
JSONObject json=jsonParser.makeHttpRequest(url,"POST", params);
Toast.makeText(getApplicationContext(), "In onLocationChanged()!", Toast.LENGTH_SHORT).show();
try {
int success = json.getInt("success");
if (success == 1)
Toast.makeText(getApplicationContext(), "Updated in Service!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "Not updated in Service!", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error in JsonException Service!", Toast.LENGTH_SHORT).show();
}
}
});
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
I added permissions in AndroidManifast.xml file and declare Service like this:
<service android:name="com.example.friendlocation.UpdateLocationService">
</service>
And calling it from listener class:
Intent i=new Intent(context, UpdateLocationService.class);
context.startService(i);
But service is not starting.
I am updating location details on server using service and it works fine if my app is opened otherwise it is giving error in service's starting time.."Unfortunately your app has stopped."
package com.example.friendlocation;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class UpdateLocationService extends Service {
String url = "http://znsoftech.com/googlemap/new/location.php";
JSONParser jsonParser = new JSONParser();
String id;
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "In onCreate()!", Toast.LENGTH_SHORT).show();
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "In onStart()!", Toast.LENGTH_SHORT).show();
getresult();
}
private void getresult() {
// TODO Auto-generated method stub
SharedPreferences sp=getSharedPreferences("location", Activity.MODE_PRIVATE);
id=sp.getString("id", null);
if(id!=null)
{
Toast.makeText(getApplicationContext(), "In id!"+id, Toast.LENGTH_SHORT).show();
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria c=new Criteria();
String provider=lm.getBestProvider(c, false);
lm.requestSingleUpdate(provider, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
params.add(new BasicNameValuePair("lat", location.getLatitude()+""));
params.add(new BasicNameValuePair("longi", location.getLongitude()+""));
JSONObject json=jsonParser.makeHttpRequest(url,"POST", params);
Toast.makeText(getApplicationContext(), "In onLocationChanged()!", Toast.LENGTH_SHORT).show();
try {
int success = json.getInt("success");
if (success == 1)
{
Toast.makeText(getApplicationContext(), "Updated in Service!", Toast.LENGTH_SHORT).show();
stopSelf();
}
else
Toast.makeText(getApplicationContext(), "Not updated in Service!", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error in JsonException Service!", Toast.LENGTH_SHORT).show();
stopSelf();
}
}
},null);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if(intent==null || intent.getAction()==null)
return Service.START_NOT_STICKY;
Toast.makeText(getApplicationContext(), "In onStartCommand()!", Toast.LENGTH_SHORT).show();
getresult();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
Added all permission in AndroidManifast.xml file. Where I am doing wrong? Should i have to use AsyncTask to update location in background?
If its because of NULLPOINTER EXCEPTION then please do add null safety for location object.I had faced similar kind of problem in nexus device.
if(location != null){
latitude = location.getLatitude();
}
I have set orientation of my activity to landscape and it remains in that state except one case.and the case is screen lock .when my activity is running and i lock my screen it changes orientation from landscape to portrait for little bit of time and causes my app to restart and which I don't want.any solution...?
package com.example.hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity{
VideoView vv;
public ArrayList<String> list = new ArrayList<String>();
int n,positio = 0;
String file = null;
Spinner spin;
MediaPlayer mp;
Intent intent;
File fl;
boolean isPlaying = true;
boolean screenOn = false;
PowerManager pm;
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
Log.d("zaid iqbal", "in onCreate");
requestFullScreen();
setContentView(R.layout.activity_main);
vv = (VideoView)findViewById(R.id.video);
spin = (Spinner)findViewById(R.id.spinner);
MediaController mc = new MediaController(this);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
vv.setMediaController(mc);
setupSpin();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onPause");
isPlaying = vv.isPlaying();
screenOn = pm.isScreenOn();
if (screenOn && isPlaying) {
// Screen is still on, so do your thing here
n++;
positio = vv.getCurrentPosition();
vv.pause();
//Toast.makeText(this, file, Toast.LENGTH_LONG).show();
intent = new Intent(this,playBack.class);
intent.putExtra("file", file);
intent.putExtra("position", positio);
intent.putExtra("n", n);
startService(intent);
}
if(!isPlaying){
positio = vv.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onResume");
if(!isPlaying){
vv.setVideoPath(file);
vv.seekTo(positio);
}else{
async aa = new async();
aa.execute();
}
super.onResume();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
}
public void requestFullScreen(){
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
,WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public void setupSpin(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/");
listFiles(root);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//Log.d("zaid iqbal","in onclick of spin");
if(n == 0){
file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/" + list.get(position);
Log.d("zaid", file);
//Toast.makeText(MainActivity.this, "original" + file, Toast.LENGTH_SHORT).show();
vv.setVideoPath(file);
vv.start();
}
//n = 0;
/*File fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
position = Integer.parseInt(reader.readLine());
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file);
writer.write(position);
writer.write(n);
position = Integer.parseInt(reader.readLine());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void listFiles(File f){
try{
File[] files = f.listFiles();
for(File file : files){
if(file.isFile()){
String filenameArray[] = file.toString().split("\\.");
String extension = filenameArray[filenameArray.length-1];
//if(extension == "mp4" || extension == "3gp")
list.add(file.getName());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
class async extends AsyncTask<String,Long,Long>{
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
if(intent != null){
stopService(intent);
//Reading file
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
//Log.d("zaid iqbal", "getted file");
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
//Toast.makeText(MainActivity.this, "getted file" + file, Toast.LENGTH_SHORT).show();
positio = Integer.parseInt(reader.readLine());
n = Integer.parseInt(reader.readLine());
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(n != 0){
n=0;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file + "\n" + positio + "\n" + n);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vv.setVideoPath(file);
vv.seekTo(positio);
vv.start();
}
super.onPostExecute(result);
}
}
}
First, I would read up on Android activity lifecycle. Personally I think this is the way begin to address the issue -
http://developer.android.com/training/basics/activity-lifecycle/index.html
Another option to investigate -
android:configChanges="orientation|keyboardHidden|screenSize"
how to stop activity recreation on screen orientation?
Try this in your Activity Tag of Manifest file :
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Here Orientation refers to Configuration changes which you want to handle by your own.
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle.
Use onSaveInstanceState() and onRestoreInstanceState() if you want to restore your previous state of an activity.
Refer this also
You may try to call setRequestedOrientation() in you activity so the orientation is forced.
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 can receive data on c# UDP server i have written through this code but instead of string i have typed in the editText box ... i receive android.widget.EditText#xxxxxx on the server. Some Help would be much appreciated.
package com.winmote.pro;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String cmd= editText1.toString();
new nwcomm().execute(cmd);
}
});
}
private class nwcomm extends AsyncTask<String,Void,Void>{
#Override
protected Void doInBackground(String... text) {
// TODO Auto-generated method stub
String msg=text[0].toString();
InetAddress to = null;
try {
to = InetAddress.getByName("192.168.0.105");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int port=55505;
DatagramSocket soc = null;
try {
soc = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = msg.getBytes();
DatagramPacket pac = new DatagramPacket(data, data.length, to, port);
try {
soc.send(pac);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You need to ask for the contents of the EditText, not the String representation of the variable... Change this line:
String cmd= editText1.toString();
To:
String cmd = editText1.getText().toString();