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..
Related
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");
}
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.
I am Newbie to Android.
I have tried all the posts in this forum. But could not get the success.
I am trying to share an mp3 file from asset folder to whatsapp.
Below is my code.
This is my Code in Main Activity:
package com.example.sharedemo;
import com.example.sharedemo.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button sharebutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharebutton = (Button) findViewById(R.id.sharebutton1);
sharebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri theUri = Uri.parse("content://com.example.sharedemo.Assetsprovider/gotShocked.mp3");
Intent theIntent = new Intent(Intent.ACTION_SEND);
theIntent.setType("audio/mp3");
theIntent.setPackage("com.whatsapp");
theIntent.putExtra(Intent.EXTRA_STREAM,theUri);
startActivity(Intent.createChooser(theIntent,"Share using"));
}
});
}
}
Code in ContentProvider:
package com.example.sharedemo;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
public class Assetsprovider extends ContentProvider {
#Override
public AssetFileDescriptor openAssetFile( Uri uri, String mode ) throws FileNotFoundException
{
AssetManager am = getContext( ).getAssets( );
String file_name = uri.getLastPathSegment( );
// String file_name = uri.getPath();
if( file_name == null )
throw new FileNotFoundException( );
AssetFileDescriptor afd = null;
try
{
afd = am.openFd(file_name);
}
catch(IOException e)
{
e.printStackTrace( );
}
return afd;//super.openAssetFile(uri, mode);
}
#Override
public String getType( Uri p1 )
{
// TODO: Implement this method
return null;
}
#Override
public int delete( Uri p1, String p2, String[] p3 )
{
// TODO: Implement this method
return 0;
}
#Override
public Cursor query( Uri p1, String[] p2, String p3, String[] p4, String p5 )
{
// TODO: Implement this method
return null;
}
/* #Override
public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal )
{
// TODO: Implement this method
return super.query( uri, projection, selection, selectionArgs, sortOrder, cancellationSignal );
}*/
#Override
public Uri insert( Uri p1, ContentValues p2 )
{
// TODO: Implement this method
return null;
}
#Override
public boolean onCreate( )
{
// TODO: Implement this method
return false;
}
#Override
public int update( Uri p1, ContentValues p2, String p3, String[] p4 )
{
// TODO: Implement this method
return 0;
}
}
Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sharedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Assetsprovider"
android:label="#string/app_name" >
</activity>
<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>
<provider
android:name="com.example.sharedemo.Assetsprovider"
android:authorities="com.example.sharedemo.Assetsprovider"
android:grantUriPermissions="true"
android:exported="true" />
</application>
</manifest>
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM,Uri.parse("file:///"+mypath));
startActivity(Intent.createChooser(share, "Share Sound File"));
break;
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}```
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
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();