unknown GoogleAuthException while getting the token - android

Similar questions are already available. But in my case I checked both SHA1 and my scope, they are correct and the account is also available. But still it returns unknown GoogleAuthException. My code is :-
MainActivity.java
package com.simon.learn.accountgetter;
import java.io.IOException;
import java.util.ArrayList;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
public class MainActivity extends Activity {
AccountManager am;
Account[] accounts;
ArrayList<String> accNames = new ArrayList<String>();
Button signin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = AccountManager.get(getApplicationContext());
accounts = am.getAccountsByType("com.google");
// accounts=am.getAccounts();
signin = (Button) findViewById(R.id.signinBt);
signin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = AccountPicker.newChooseAccountIntent(null,
null, new String[] { "com.google" }, false, null, null,
null, null);
startActivityForResult(intent, 13);
}
});
}
private void getToken(String accountName) {
new GetTokenTask(MainActivity.this, accountName,
"oauth2:https://www.googleapis.com/auth/userinfo.profile")
.execute();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String token = null;
if (requestCode == 13) {
if (resultCode == RESULT_OK) {
String accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.e("simon", accountName);
Toast.makeText(getApplicationContext(), accountName,
Toast.LENGTH_LONG).show();
getToken(accountName);
// Toast.makeText(getApplicationContext(),
// "The token is : "+token, Toast.LENGTH_LONG).show();
}
}
}
public class GetTokenTask extends AsyncTask<Void, Void, String> {
Activity activity;
String scope;
String email;
public GetTokenTask(Activity activity, String email, String scope) {
this.activity = activity;
this.scope = scope;
this.email = email;
}
#Override
protected String doInBackground(Void... params) {
String token = null;
try {
Log.e("simon","Scope : "+scope+ " email "+ email);
token = GoogleAuthUtil.getToken(activity, email, scope);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
Log.e("simon","UserRecoverableAuthException");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("simon","IOException");
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
Log.e("simon","GoogleAuthException : "+e.getMessage());
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Log.e("simon", "The Token is : " + result);
Toast.makeText(getApplicationContext(), "The Token is : " + result,
Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
}
It is showing unknown GoogleAuthException. See my manifest file also
Manifest.java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.simon.learn.accountgetter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Please help me. Thanks in advance

Related

Flash should turn on when double click power button

I have an application which has just a toggle button in it. The function of this toggle button is to turn the flash on, when I press it and to turn the flash off, when I press it again. But I want this to happen even when my device is locked or sleeping or working. Whenever I double click the power button the app function should run in services and through broadcast it should turn the flash on. Kindly let me know how this can be done.
Capture Image
package com.example.salal_khan.SecuriteCameraServices;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.hardware.Camera.Parameters;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
/**
* Created by salal-khan on 12/1/2017.
*/
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
Camera camera = null;
boolean isON = false;
int number_of_clicks = 0;
boolean thread_started = false;
final int DELAY_BETWEEN_CLICKS_IN_MILLISECONDS = 550;
Context contexts;
#Override
public void onReceive(final Context context, final Intent intent) {
contexts = context;
++number_of_clicks;
final SurfaceView mview = new SurfaceView(context);
if (camera==null) {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
}
if (!thread_started) {
new Thread(new Runnable() {
#Override
public void run() {
thread_started = true;
try {
Thread.sleep(DELAY_BETWEEN_CLICKS_IN_MILLISECONDS);
if (number_of_clicks == 1) {
} else if (number_of_clicks == 2) {
if (isON) {
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
camera.setParameters(parameters);
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
try {
camera.setPreviewDisplay(mview.getHolder());
camera.startPreview();
camera.takePicture(null, null, photoCallback);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} else {
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
camera.setParameters(parameters);
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
try {
camera.setPreviewDisplay(mview.getHolder());
camera.startPreview();
camera.takePicture(null, null, photoCallback);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
number_of_clicks = 0;
thread_started = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Log.e("LOB", "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wasScreenOn = false;
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.e("LOB", "userpresent");
Log.e("LOB", "wasScreenOn" + wasScreenOn);
}
}
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Uri uriTarget = contexts.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = contexts.getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
// Toast.makeText(contexts.getApplicationContext(), "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
Manifests
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.salal_khan.SecuriteCameraServices">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:name=".MyApplication"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="com.example.salal_khan.SecuriteCameraServices.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.salal_khan.SecuriteCameraServices.MyService" />
</application>
</manifest>
MainActivity
package com.example.salal_khan.flashlightservices;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = this;
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
startService();
}
public void startService() {
startService(new Intent(getBaseContext(), MyService.class));
}
// Method to stop the service
public void stopService() {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
Service
package com.example.salal_khan.flashlightservices;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
/**
* Created by salal-khan on 12/1/2017.
*/
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
final IntentFilter filter = new
IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
}
Broadcast Receiver
package com.example.salal_khan.flashlightservices;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.util.Log;
import android.hardware.Camera.Parameters;
/**
* Created by salal-khan on 12/1/2017.
*/
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
Camera camera;
boolean isON = false;
int number_of_clicks = 0;
boolean thread_started = false;
final int DELAY_BETWEEN_CLICKS_IN_MILLISECONDS = 550;
#Override
public void onReceive(final Context context, final Intent intent) {
++number_of_clicks;
if (!thread_started) {
new Thread(new Runnable() {
#Override
public void run() {
thread_started = true;
try {
Thread.sleep(DELAY_BETWEEN_CLICKS_IN_MILLISECONDS);
if (number_of_clicks == 1) {
} else if (number_of_clicks == 2) {
if (isON) {
if (camera == null) {
camera = Camera.open();
}
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isON = false;
} else {
if (camera == null) {
camera = Camera.open();
}
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isON = true;
}
}
number_of_clicks = 0;
thread_started = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Log.e("LOB", "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wasScreenOn = false;
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
wasScreenOn = true;
}
else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.e("LOB", "userpresent");
Log.e("LOB", "wasScreenOn" + wasScreenOn);
}
}
}
Manifests
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.salal_khan.flashlightservices">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
</manifest>

Coudn't connect to online database in Android app

I'm trying to connect my app to online database, i have all the php files working, but my app don't connect to the database. I have to do simple data insertion and data retrieve. I Keep getting null pointer exception.
RegOneActivity.java
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegOneActivity extends Activity {
Button okaBtn,regbtn;
EditText phno,password;
String phone,pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_one);
password = (EditText) findViewById(R.id.passwordedittext);
okaBtn =(Button) findViewById(R.id.okbtn);
phno = (EditText) findViewById(R.id.editTextpass1);
regbtn = (Button) findViewById(R.id.createbtn);
regbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(RegOneActivity.this, PasswordActivity.class);
startActivity(in);
}
});
okaBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
phone = phno.getText().toString();
pass = password.getText().toString();
String method = "login";
/*RegisterBackgroung backGround = new RegisterBackgroung(getApplicationContext());*/
RegisterBackgroung backGround = new RegisterBackgroung(RegOneActivity.this);
backGround.execute(method, phone, pass);
Intent in = new Intent(RegOneActivity.this, MapActivity.class);
startActivity(in);
RegOneActivity.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reg_one, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PasswordActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PasswordActivity extends Activity {
Button btn;
EditText password1,password2,phone;
String pass1,pass2,phonenumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password);
btn =(Button) findViewById(R.id.proceed1act);
password1 = (EditText) findViewById(R.id.editTextpass1);
phone = (EditText) findViewById(R.id.phoneedt);
password2 = (EditText) findViewById(R.id.editTextpass2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pass1 = password1.getText().toString();
pass2 = password2.getText().toString();
phonenumber = phone.getText().toString();
String method= "register";
RegisterBackgroung backtask = new RegisterBackgroung(PasswordActivity.this);
backtask.execute(method,phonenumber,pass1);
Intent in = new Intent(PasswordActivity.this, RegOneActivity.class);
startActivity(in);
PasswordActivity.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.password, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
RegisterBackground.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.widget.Toast;
public class RegisterBackgroung extends AsyncTask<String, Void, String>{
Context ctx;
AlertDialog diag;
SharedPreferences sp;
Editor edt;
public RegisterBackgroung(Context ctx) {
this.ctx = ctx;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String urlregister = "http://www.locationsharing.16mb.com/register.php";
String login = "http://www.locationsharing.16mb.com/retrieve.php";
String method = params[0];
if(method.equals("register"))
{
String phone = params[1];
String pass = params[2];
try {
URL reg_url = new URL(urlregister);
HttpURLConnection httpUrlConnection = (HttpURLConnection) reg_url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
OutputStream os = httpUrlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("phonenumber", "UTF-8")+"="+URLEncoder.encode(phone, "UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream is = httpUrlConnection.getInputStream();
is.close();
return "Registration Successful!";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(method.equals("login")){
String phone = params[1];
String pass = params[2];
try {
URL url = new URL(login);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
OutputStream os = httpUrlConnection.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data = URLEncoder.encode("phonenumber", "UTF-8")+"="+URLEncoder.encode(phone, "UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(pass, "UTF-8");
bw.write(data);
bw.flush();
bw.close();
os.close();
InputStream is = httpUrlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
String response = "";
String line = "";
while((line = br.readLine())!=null)
{
response += line;
}
br.close();
is.close();
httpUrlConnection.disconnect();
return response;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
diag.setTitle("Login Information");
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("Registration Successful!"))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
diag.setMessage(result);
diag.show();
}
}
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lavisor.locationsharing2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="15" />
<permission
android:name="com.testing.svma.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.testing.svma.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashActivity"
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=".RegOneActivity"
android:label="#string/title_activity_reg_one" >
</activity>
<activity
android:name=".PasswordActivity"
android:label="#string/title_activity_password" >
</activity>
<activity
android:name=".PassActivity"
android:label="#string/title_activity_pass" >
</activity>
<activity
android:name=".MapActivity"
android:label="#string/title_activity_map" >
</activity>
<activity
android:name=".SelectCircleActivity"
android:label="#string/title_activity_select_circle" >
</activity>
<activity
android:name=".ShareLocationActivity"
android:label="#string/title_activity_share_location" >
</activity>
<activity
android:name=".FavouritesActivity"
android:label="#string/title_activity_favourites" >
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAZx8eHxiQ5ZRgsDstuyseUKQ_PaH8rlps" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
</application>
</manifest>
I forgot to override OnProgressUpdate in the Async task :P and Now, it works perfectly..

Unable to start activity ComponentInfo: java.lang.NullPointerException

I have searched for this error and found numerous solutions but i'm not able to resolve the issue since i'm beginner in Android
Here is my Main Activity
package ***.***.greytrix.test;
import android.app.LauncherActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.webkit.CookieManager;
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
private Context context;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// please enter your sender id
String SENDER_ID = "11111111";
static final String TAG = "Pocket ";
GoogleCloudMessaging gcm;
TextView mDisplay;
String regid;
String fileurl="https://neel.test.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
if(checkPlayServices()){
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
//For Testing Purpose
new RegisterBackground().execute();
}
Bundle extras = getIntent().getExtras();
String url;
if (extras != null) {
url = extras.getString("url");
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
if (extras.getString("url").isEmpty()) {
mWebView.loadUrl("https://neel.test.com/");
} else {
mWebView.loadUrl(url);
}
mWebView.setWebViewClient(new MyAppWebViewClient());
} else {
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
fileurl = ReadFile();
if (fileurl == "") {
fileurl="https://neel.test.com/";
mWebView.loadUrl("https://neel.test.com/");
} else {
mWebView.loadUrl(fileurl);
}
mWebView.setWebViewClient(new MyAppWebViewClient());
}
}
private String ReadFile() {
String aBuffer = "";
try {
File myFile = new File(getFilesDir() + "/mysdfile.txt");
if (myFile.exists()) {
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
return aBuffer.trim();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.SetURL) {
Intent nextscreen = new Intent(PayrollApplication.getContext(), SecondScreenActivity.class);
startActivity(nextscreen);
//setContentView(R.layout.seturl);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onResume(){
super.onResume();
checkPlayServices();
}
//New Code developed by Nilesh Gajare on 10th July 2015
class RegisterBackground extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
Log.d("111", msg);
sendRegistrationIdToBackend();
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
//mDisplay.append(msg + "\n");
}
private void sendRegistrationIdToBackend() {
// Set Server URL for Storing Android Device Registration ID.
String CompanyCode= getCookie(fileurl,"CompanyId");
String UserName= getCookie(fileurl,"UserName");
String Password= getCookie(fileurl,"Password");
String url = "https://neel.test.com//api/v1.0/SaveAndroidRegId?RegId="+regid+"&CompanyId="+CompanyCode+"&UserName="+UserName+"&Password="+Password ;
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.i(TAG,httpResponse.getStatusLine().toString());
Log.i(TAG,httpResponse.getEntity().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
public String getCookie(String siteName,String CookieName){
String CookieValue = null;
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(siteName);
if(cookies != null) {
String[] temp = cookies.split(";");
for (String ar1 : temp) {
if (ar1.contains(CookieName)) {
String[] temp1 = ar1.split("=");
CookieValue = temp1[1];
}
}
}
return CookieValue;
}
}
In the MainActivy.xml, I got the following code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="fill_parent"
android:layout_height= "fill_parent"
android:layout_weight="1.0" />
</RelativeLayout>
The stack trace is
Process: com.pockethcm.xxx.test, PID: 2347
java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx.xxx.test/xxx.xxx.xxx.test.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean java.lang.String.isEmpty()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object
reference
at selfservice.pockethcm.greytrix.test.MainActivity.onCreate(MainActivity.java:106)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) device
offline
And the manifest is here below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="selfservice.xxx.xxx.test"
android:versionCode="2"
android:versionName="1.1">
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
<permission
android:name="selfservice.xxx.xxx.test.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="selfservice.xxx.xxx.test.gcm.permission.C2D_MESSAGE" />
<application
android:name="selfservice.xxx.xxx.test.PayrollApplication"
android:allowBackup="true"
android:icon="#mipmap/icon_pocket"
android:label="Pocket HCM"
android:theme="#style/AppTheme">
<activity
android:name="selfservice.xxx.xxx.test.MainActivity"
android:label="Pocket HCM"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="selfservice.xxx.xxx.test.SecondScreenActivity"
android:screenOrientation="portrait"></activity>
<receiver
android:name="selfservice.xxx.xxx.test.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="selfservice.xxx.xxx.test" />
</intent-filter>
</receiver>
<service android:name="selfservice.xxx.xxx.test.GcmIntentService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="selfservice.pockethcm.greytrix.test.ReceiveActivity">
</activity>
</application>
</manifest>
It is working for first time after installing app but when we close and reopen it crashes Unfortunately App has been closed
would you have any idea, it would be much appreciated :)
Thanks!
Here is your culprit which throws NPE:
if (extras.getString("url").isEmpty()) {
You should make a check here if url is null or not:
url = extras.getString("url");
if(url == null){
Log.d("url status","its null");
}

Google Drive file: Item not found or you are not authorized to access it

I am very very new to Google API's : I have gone thru documentation and my app [from android-demos-master] creates a file successfully and the content is "Hello World". The When trying to retrieve contents, the app connects successfully and the DriveID is returned. However, Status code 1502 "item not found or you do not have authorization" is retuned.
What am I doing wrong?
Manifest [ although the Activity Intent filter does not sem to fullfil any function]:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dishes4"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission
android:name="android.permission.GET_ACCOUNTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
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=".CreateFileActivity"
android:label="#string/title_activity_create_file" >
</activity>
<activity
android:name=".BaseDemoActivity"
android:label="#string/title_activity_base_demo" >
</activity>
<activity
android:name=".RetrieveContentsActivity"
android:label="#string/title_activity_retrieve_contents" >
<meta-data android:name="com.google.android.apps.drive.APP_ID" android:value="id=108614704480-ohna61c6boi21ak393pqhvjh1dm1or6f.apps.googleusercontent.com" />
<intent-filter>
<action android:name="com.google.android.apps.drive.DRIVE_OPEN" />
</intent-filter>
</activity>
</application>
The RetrieveContentsActivity which causes the problem:
package com.example.dishes4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.DriveIdResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
public class RetrieveContentsActivity extends BaseDemoActivity {
private static final String TAG = "RetrieveContentsActivity";
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_contents);
tv = (TextView) findViewById(R.id.text);
}
#Override
public void onConnected(Bundle connectionHint) {
tv.append("Connected");
showMessage("Connected");
super.onConnected(connectionHint);
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
tv.append("........ finising fetching DriveID");
}
final private ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
tv.append("Got a result!!!!!!!!!!! ");
showMessage("Got a result!!!!!!!!!!! ");
if (result.getStatus().isSuccess()) {
tv.append("Success DriveIDResult");
tv.append(result.toString());
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(), result.getDriveId());
return;
}
else
{tv.append("Status code: "+Integer.toString(result.getStatus().getStatusCode())+" ");
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;}
}
};
}
The CreateFileActivity
package com.example.dishes4;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.MetadataChangeSet;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class CreateFileActivity extends BaseDemoActivity {
private static final String TAG = "CreateFileActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
Drive.DriveApi.newDriveContents(getGoogleApiClient())
.setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write("Hello World!");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("New file")
.setMimeType("text/plain")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
final private ResultCallback<DriveFileResult> fileCallback = new
ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
}
};
}
and the BaseDemoActivity they both extend
package com.example.dishes4;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
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.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
public abstract class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BaseDriveActivity";
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
protected static final int REQUEST_CODE_RESOLUTION = 1;
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
}
Since nobody has answered your question. I take the liberty to answer, even if it is more than a few weeks old.
When you create your file you show your drive-id with the following lines:
showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
Then when reading your file you are using a constant:
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
Make sure that EXISTING_FILE_ID is the value you got when creating your file. Maybe it would be better to write result.getDriveFile().getDriveId() to the log, rather than showing it to the screen for a few seconds.
Replace:
showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
with:
Log.d("DriveID",Created a file with content: " + result.getDriveFile().getDriveId());
Then make a note of the drive-id, and update the constant: EXISTING_FILE_ID.

Can not receive chat messages in Android using XMPP and aSmack

I am writing a chat client in Android using the XMPP protocol. I have used the asmack.jar as provided by
http://asmack.freakempire.de/. The implementation works in plain Java (using smack.jar) which I have tested. But in Android, I can only send messages to the other client (he uses pidgin) and cannot receive messages from him. The app successfully connects to the server, logs in and appears online but simply doesn't receive any message.
My processMessage() never gets called nor does chatCreated() when a message is send to my client.
My Activity class:
package com.example.basicchat;
import org.jivesoftware.smack.AndroidConnectionConfiguration;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.SmackAndroid;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SmackAndroid.init(this);
MainActivity2 xmppClient= new MainActivity2("jabber.org", 5222);
try {
xmppClient.login();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class MainActivity2 implements MessageListener, ChatManagerListener, ConnectionListener {
private String server;
private int port;
public MainActivity2( String server, int port )
{
super();
this.server = server;
this.port = port;
}
private XMPPConnection connection = null;
public void login() throws XMPPException
{
String username = "my_user";
String password = "xxxxxxxx";
login(username, password);
}
private void login(String userName, String password) throws XMPPException
{
AndroidConnectionConfiguration config = new AndroidConnectionConfiguration(server,
port);
connection = new XMPPConnection(config);
connection.connect();
connection.addConnectionListener(this);
connection.login(userName, password);
ChatManager chatManager = connection.getChatManager();
chatManager.addChatListener(this);
Toast.makeText(MainActivity.this,"listener set", Toast.LENGTH_SHORT).show();
// sendMessage("helloooo","command_server#jabber.org"); /* this mssg is sent */
}
private void sendMessage(String message, String to) throws XMPPException
{
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}
public void disconnect()
{
connection.disconnect();
}
/** never gets called **/
#Override
public void processMessage(Chat chat, Message message)
{
/*********** Handle Request and construct response ******************/
Toast.makeText(MainActivity.this,"mssg: "+message.getBody(), Toast.LENGTH_SHORT).show();
switch (message.getType())
{
case chat:
String jsonData = (null==message.getBody())?"":message.getBody();
System.out.println(jsonData);
break;
case error:
break;
case groupchat:
break;
case headline:
break;
case normal:
break;
}
}
#Override
public void chatCreated(Chat arg0, boolean arg1) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Chat Created!", Toast.LENGTH_SHORT).show();
if (!arg1)
arg0.addMessageListener(this);
}
#Override
public void connectionClosed() {
// TODO Auto-generated method stub
}
#Override
public void connectionClosedOnError(Exception arg0) {
// TODO Auto-generated method stub
}
#Override
public void reconnectingIn(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void reconnectionFailed(Exception arg0) {
// TODO Auto-generated method stub
}
#Override
public void reconnectionSuccessful() {
// TODO Auto-generated method stub
}
}
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.basicchat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<activity
android:name="com.example.basicchat.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You must implements MessageListener class for MainActivity to receive chat messages

Categories

Resources