I'm trying to make a mini yamba.newcircle.com from my Android project training. I'm saving text messages when the Internet is not available, and with connectivity broadcast receiver if the Internet is up. This app automatically starts a service that loops to push all saved text rows in ActiveAndroid from a table, via HTTP posts to the web API.
When I turn Wifi off, save some messages with ActiveAndroid, and turn Wifi back on; if my app connects, it simply crashes with NullPointereException.
Any suggestions?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pt.flag.miniyamba" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="MiniYamba"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<meta-data
android:name="AA_DB_NAME"
android:value="yamba.db" />
<meta-data
android:name="AA_DB_VERSION"
android:value="5" />
<activity android:name=".Main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OnlineStatus" >
</activity>
<activity android:name=".OfflineStatus" >
</activity>
<activity android:name=".SingleStatus" >
</activity>
<activity android:name=".NewStatus" >
</activity>
<receiver android:name=".NetworkBroadCastReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
</intent-filter>
</receiver>
<service android:name=".PushOfflineSavedService"/>
</application>
</manifest>
broacast
public class NetworkBroadCastReceiver extends BroadcastReceiver {
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = manager.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnectedOrConnecting()){
Toast.makeText(context, "net is up, pushing our previous offline saved posts ", Toast.LENGTH_SHORT).show();
//inicializar o servico de push de posts, guardados anteriormente
Intent novointent = new Intent(context, PushOfflineSavedService.class);
context.startService(novointent);
}
//mudou de conectividade, mas nao tem internet
else{
Toast.makeText(context, "Connectivity is changed. Internet seens not working.", Toast.LENGTH_SHORT).show();
}
}
}
intentservice
public class PushOfflineSavedService extends IntentService {
private String LOG_TAG;
public PushOfflineSavedService() {
super("PushOfflineSavedService");
ActiveAndroid.initialize(this);
}
#Override
protected void onHandleIntent(Intent intent) {
//enviar os status guardados, por enviar
List<OfflinePostToSend> lista = new Select().from(OfflinePostToSend.class).execute();
//loop para enviar os status
if (lista.size() > 0) {
for (int i = 0; i < lista.size(); i++) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
String path = "http://yamba.newcircle.com/api/statuses/update.json";
String status = lista.get(i).getText();
URL url = new URL(path);
String userPass = "student:password";
String token = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.NO_WRAP);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
// Adicionar o token como header do pedido
urlConnection.addRequestProperty("Authorization", token);
urlConnection.setDoOutput(true);
String postParameters = "status="+status;
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Adicionar o status ao método post
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();
reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
//se buffer nao for full, temos 1 respota do API
if (buffer.length() != 0) {
// Stream was NOT empty.
//apagar este elemento da lista e da db
lista.get(i).delete();
}
//return buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
}
}
}
The ActiveAndroid guide shows the call to initialize() in an Application subclass, like this:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
ActiveAndroid.initialize(this);
}
}
Try extending Application and putting your initialize() call there instead of in the service.
Related
I am sending images to firebase. but when my upload pictures method starts running, I get no auth token printed into my logcat couple of times. I tried using both camera and gallery, but they both make the same output even though my firebase storage rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my code is:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plantss = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plantss.setPlname(pname);
plantss.setPldate(pdate);
plantss.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plantss);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
System.out.println("IMAGE IS THIS MY MAN: "+ getimage.getString(0));
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
if (bm == null){
return;
}else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
System.out.println("FAILED:::: "+exception);
}
});
}
}
}
}
Mainfest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.varroxsystems.plant">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/plant"
android:label="#string/app_name"
android:roundIcon="#drawable/plant"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/AppTheme">
<activity android:name=".Donenewplant"></activity>
<activity android:name=".newPlant" />
<activity android:name=".MainActivity" />
<activity android:name=".Splash_screen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.varroxsystems.plant.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
So does anyone know a solution for that, or is it just a bug, because I use the same exact code in another app and it works just fine.
EDIT: The other app I use uses a different database, not the same one.
I'm trying to make an app that blocks calls with ITelephony depending on which radio button is pressed in my main activity. However, my onReceive method never gets called and therefore, doesn't block the call.
Here is my class that extends BroadcastReceiver
public class CallBlocking extends BroadcastReceiver {
private static final int MODE_WORLD_READABLE = 1;
private String mPhoneNumber;
private String mCallerName;
private SharedPreferences mPreferences;
#Override
public void onReceive(Context context, Intent intent) {
mPreferences = context.getSharedPreferences("mPreferences", MODE_WORLD_READABLE);
String blockMode = mPreferences.getString("mode", "not retrieved");
if (!blockMode.equals("cancel")) {
Bundle b = intent.getExtras();
String phoneState = b.getString(TelephonyManager.EXTRA_STATE);
if ((phoneState.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))) {
mPhoneNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (blockMode.equals("all")) {
disconnect(context);
} else if (blockMode.equals("unsaved")) {
mCallerName = getContactName( mPhoneNumber, context);
if((mCallerName == null) || (mCallerName.length() < 2))
disconnect(context);
else if (blockMode.equals("list"))
{
if(CallBlockerFragment.sBlockedList.contains(new BlockedList(mPhoneNumber)))
disconnect(context);
}
}
}
}
}
#SuppressWarnings({"rawtypes", "unchecked"})
private void disconnect(Context context) {
ITelephony telephonyService;
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getContactName(String phoneNumber, Context context) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String callerName = "?";
String data = null;
ContentResolver contentResolver = context.getContentResolver();
Cursor findContact = contentResolver.query(uri, new String[] {BaseColumns._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
try {
if (findContact != null && findContact.getCount() > 0) {
findContact.moveToNext();
data = findContact.getString((findContact.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)));
}
}
finally
{
if(findContact != null)
findContact.close();
}
return data;
}
}
and here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.uwp.sean.pike.csci323.callblocker">
<application
android:allowBackup="true"
android:icon="#drawable/quevedo"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".CallBlockerActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".AddToBlockedListActivity">
android:label="#string/app_name"
android:parentActivityName=".CallBlockerActivity">
</activity>
<activity
android:name=".BlockedListActivity">
android:label="#string/app_name"
android:parentActivityName=".CallBlockerActivity">
</activity>
<receiver android:name=".CallBlocking">
<intent-filter android:priority="100" >
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</manifest>
Why isn't it calling the onReceive method?
maybe what you would like to achieve is to listen for phone state changes...please check out the following link Listen to Change of Phone State State - Android
I've rooted Nexus phone with lollipop. I'm trying to record incoming & outgoing calls.
My application extends DeviceAdminReceiver with policy of <force-lock />
I'm able to create the file with size > 0bytes. But when I play it, it is blank.
Please take a look at the code below:
Manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
.....
<service android:name=".RCService"
android:exported="false" >
</service>
.....
<receiver
android:name=".utils.MyDeviceAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<intent-filter>
<!-- This action is required -->
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
</intent-filter>
<!-- This is required this receiver to become device admin component. -->
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/device_admin" />
</receiver>
<receiver android:name=".CallRecoderBroadcast">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
device_admin.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
CallRecoderBroadcast.java
/**
* Lifecycle :
* Incoming call : RINGING -> OFFHOOK -> IDLE
* Outgoing Call : OFFHOOK -> IDLE
*/
public class CallRecoderBroadcast extends BroadcastReceiver {
private static final String TAG = "CallRecoderBroadcast";
private static final String ACTION_PHONE = "android.intent.action.PHONE_STATE";
private static final String OUTGOING_CALL = "android.intent.action.NEW_OUTGOING_CALL";
private static Boolean mCallOnGoing = Boolean.FALSE;
private MediaRecorder mRecorder = new MediaRecorder();
// private File mFile = null;
private String mNumber;
#Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals(ACTION_PHONE)) {
Bundle bundle = intent.getExtras();
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
Log.e(TAG, state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Log.e(TAG, bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER));
mNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (!mCallOnGoing) {
recordCall(context);
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
if (mCallOnGoing) {
stopRecording();
}
}
} else if (intent.getAction().equals(OUTGOING_CALL)) {
Log.e(TAG, "OUTGOING cALL");
Log.e(TAG, intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
mNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
private void recordCall(Context context) throws IOException, CustomExcpetion {
File file = prepareFile(context);
if (file.exists()) {
mCallOnGoing = Boolean.TRUE;
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(file.getAbsolutePath());
mRecorder.prepare();
mRecorder.start();
}
}
private void stopRecording() {
mCallOnGoing = Boolean.FALSE;
// mRecorder.stop();
mRecorder.release();
}
private File prepareFile(Context context) throws CustomExcpetion {
File outputFile = null;
try {
File dir = new File(context.getFilesDir(), "recorderdFiles");
if (!dir.exists()) {
dir.mkdirs();
}
Long timeStamp = System.currentTimeMillis();
outputFile = new File(dir, timeStamp.toString());
if (!outputFile.exists()) {
outputFile.createNewFile();
}
} catch (IOException exp) {
throw new CustomExcpetion(context, exp);
}
return outputFile;
}
}
P.S. - I've also tried with example given here, but it only working form Mic & not for uplink & downlink at the same time.
Unfortunately, voice call recorder is not supported on that device,
I think that will work fine on other devices.
I have working on my code for lots of hours and I could not figure out, what is wrong there.
I have a simple class TwitterActivity. Inside it I have also a mSignin button. I set event handling for mSignin button and inside its onClick(..) method I call an inner class named CheckInternetConnection which extends AsyncTasck.
Then in doInBackground(...) method I try to get an response code by opening a connection to "http://www.google.com".
As a result I always get IOexception. I tried it with different ConnectTimeout and different website, but nothing changed.
What might be going wrong here? Thanks.
public class TwitterActivity extends Activity
{
private static final String LOG_TAG = null;
private Button mSignin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);
mSignin = (Button)findViewById(R.id.login_id);
mSignin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new CheckInternetConnection().execute();
}
});
}
class CheckInternetConnection extends AsyncTask<Void, Void, Boolean>{
#Override
protected void onPostExecute(Boolean result){
if(result)
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "failure", Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(Void... params) {
if (isNetworkAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL( "http://www.google.com" ).openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
EDIT 1:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bledi.android.twittertest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="11"
android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name="TwitterActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".SearchTwitter"
android:label="#string/app_name"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="oauth" android:host="com.bledi.TwitterTest" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
EDIT 2
If anyone will come across with the same problem, DON'T forget to try it in a real Device. The emulator sometime sucks and you have no idea why.
If you just want to check if you have internet connection you can use your isNetworkAvailable() , with activeNetworkInfo.isConnected(). It's enough to validate the availability of internet.
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
If you really want to ping http://www.google.com try this :
protected Boolean doInBackground(Void... params) {
if (isNetworkAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL( "http://www.google.com" ).openConnection());
urlc.connect();
int resp = urlc.getResponseCode();
return resp == 200;
} catch (IOException e) {
Log.e("DD", "Error checking internet connection", e);
}
} else {
Log.d("DD", "No network available!");
}
return false;
}
I cant get registration ID for all the devices.
The manifest is good and i add all premission.
the Sender_ID is good.
the device has an account logged in. (Google account).
the code below is the activity which handles with the GCM device register.
Please help me!
public class ClientRegisterActivity extends Activity {
private static final String SENDER_ID = "*******";
private Client client = null;
private GoogleCloudMessaging gcm;
TextView tvHeader;
EditText etEmail;
EditText etPass;
EditText etPassConf;
EditText etFname;
EditText etLname;
EditText etPhone;
// Spinner spWorkArea;
Button bReg;
// Variables used for conversion into database
String fName;
String lName;
String email;
String password;
String phone;
// String workArea;
String regId = "";
String rg;
MyGCMBroadcastReceiver myReci;
// SQLLiteData entry = new SQLLiteData(RegisterActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_activity_register);
initialize();
}
private void initialize() {
tvHeader = (TextView) findViewById(R.id.ctvHeader);
etEmail = (EditText) findViewById(R.id.cemail);
etPass = (EditText) findViewById(R.id.cpassword);
etPassConf = (EditText) findViewById(R.id.cpassword_confirm);
etFname = (EditText) findViewById(R.id.cfirst_name);
etLname = (EditText) findViewById(R.id.clast_name);
etPhone = (EditText) findViewById(R.id.cetPhone);
// spWorkArea = (Spinner) findViewById(R.id.cspWorkArea);
bReg = (Button) findViewById(R.id.cbRegister);
regId="";
// Avoiding NullPointerException in checks
etEmail.setText("");
etPass.setText("");
etPassConf.setText("");
etFname.setText("");
etLname.setText("");
etPhone.setText("");
myReci=new MyGCMBroadcastReceiver();
registerReceiver(myReci,new IntentFilter("com.avshalom.ilani.easymovers.DISPLAY_MESSAGE_ACTION"));
bReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean didItWork;
registerInBackground();
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
}
else
setContentView(R.layout.client_activity_register);
Log.d("Text", "kobi: regId = " + regId);
Gson gson = new Gson();
client = new Client();
SendHttpRequest snd = new SendHttpRequest((etFname.getText()
.toString()), etLname.getText().toString(), etEmail
.getText().toString(), etPass.getText().toString(),
etPhone.getText().toString(), regId.toString());
snd.start();
// HttpResponse
// response=SendHttpRequest.SendLogin(etFname.getText().toString(),etLname.getText().toString(),etEmail.getText().toString(),etPass.getText().toString(),etPhone.getText().toString(),
// regId.toString());
Log.d("Text", "kobi: after httpresponse");
// client = gson.fromJson(reader, Client.class);
Toast.makeText(ClientRegisterActivity.this,
client.getFirstName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.register, menu);
return true;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
// while(regId=="")
rg = gcm.register(SENDER_ID);
regId=rg;
msg = "Device registered, registration ID=" + regId;
System.out.println(msg);
Log.d("Text", msg);
Log.d("Text", "kobi: " + regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
}
}.execute(null, null, null);
}
register activity after onpreexecute:
bReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//boolean didItWork;
registerInBackground();
/*
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
}
else
setContentView(R.layout.client_activity_register); */
Log.d("Text", "kobi: regId = " + regId);
Gson gson = new Gson();
client = new Client();
SendHttpRequest snd = new SendHttpRequest((etFname.getText()
.toString()), etLname.getText().toString(), etEmail
.getText().toString(), etPass.getText().toString(),
etPhone.getText().toString(), regId.toString());
snd.start();
// HttpResponse
// response=SendHttpRequest.SendLogin(etFname.getText().toString(),etLname.getText().toString(),etEmail.getText().toString(),etPass.getText().toString(),etPhone.getText().toString(),
// regId.toString());
Log.d("Text", "kobi: after httpresponse");
// client = gson.fromJson(reader, Client.class);
Toast.makeText(ClientRegisterActivity.this,
client.getFirstName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.register, menu);
return true;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
// while(regId=="")
rg = gcm.register(SENDER_ID);
regId=rg;
msg = "Device registered, registration ID=" + regId;
System.out.println(msg);
Log.d("Text", msg);
Log.d("Text", "kobi: " + regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
boolean didItWork;
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
else
setContentView(R.layout.client_activity_register);
}
}
}.execute(null, null, null);
}
Here is the Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avshalom.ilani.easymovers"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<!-- For receiving messaged from the GCM -->
<permission
android:name="com.avshalom.ilani.easymovers.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.avshalom.ilani.easymovers.permission.C2D_MESSAGE" />
<!-- For receiving messaged from the GCM -->
<!-- For receiving the GCM messages -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- For accessing the internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- For google accounts -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- When receiving a message, to keep the device awake -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.avshalom.ilani.easymovers.Login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.Choose"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.ClientRegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.offers.tabs"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.MoverRegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver
android:name="com.avshalom.ilani.easymovers.MyGCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.avshalom.ilani.easymovers" />
</intent-filter>
</receiver>
<service android:name="com.avshalom.ilani.easymovers.GCMIntentService" />
</application>
</manifest>